fg71
I asked ChatGPT to give me Schedule Timer in Function Block Structured Text.
FUNCTION_BLOCK FB_ScheduleTimer
VAR_INPUT
    StartDateTime: DT;    // Start date and time
    Duration: TIME;       // Duration to keep the output on
    CurrentDateTime: DT;  // Current date and time
END_VAR
VAR_OUTPUT
    TimerOutput: BOOL;    // Output of the timer
END_VAR
VAR
    EndDateTime: DT;      // End date and time
    TimerStarted: BOOL;   // Flag indicating if the timer has started
END_VAR

// Initialize the end date and time
IF NOT TimerStarted THEN
    EndDateTime := StartDateTime + Duration;
    TimerStarted := TRUE;
END_IF

// Check if the current date and time is within the scheduled period
IF CurrentDateTime >= StartDateTime AND CurrentDateTime < EndDateTime THEN
    TimerOutput := TRUE;
ELSE
    TimerOutput := FALSE;
    TimerStarted := FALSE; // Reset the timer for next activation
END_IF
END_FUNCTION_BLOCK

PROGRAM Main
VAR
    ScheduleTimer: FB_ScheduleTimer; // Instance of the schedule timer function block
    CurrentTime: DT;                 // Current date and time
    OutputSignal: BOOL;              // Output signal from the timer
END_VAR

// Assume CurrentTime is being updated regularly by an RTC or system clock

// Call the schedule timer function block with example start date/time and duration
ScheduleTimer(
    StartDateTime := DT#2024-11-14-15:00:00,
    Duration := T#2h,
    CurrentDateTime := CurrentTime
);

OutputSignal := ScheduleTimer.TimerOutput;
 
I compare my implementation from plc.st file that look like this. (They are the same)
Is the data type DT = current time ??
 
I couldn't get it to work 🙁
 
TYPE
  LOGLEVEL : (CRITICAL, WARNING, INFO, DEBUG) := INFO;
END_TYPE

FUNCTION_BLOCK LOGGER
  VAR_INPUT
    TRIG : BOOL;
    MSG : STRING;
    LEVEL : LOGLEVEL := INFO;
  END_VAR
  VAR
    TRIG0 : BOOL;
  END_VAR

  IF TRIG AND NOT TRIG0 THEN
  {{
   LogMessage(GetFbVar(LEVEL),(char*)GetFbVar(MSG, .body),GetFbVar(MSG, .len));
  }}
  END_IF;
  TRIG0:=TRIG;
END_FUNCTION_BLOCK


FUNCTION_BLOCK FB_ScheduleTimer
  VAR_INPUT
    StartDateTime : DT;
    Duration : TIME;
    CurrentDateTime : DT;
  END_VAR
  VAR_OUTPUT
    TimerOutput : BOOL;
  END_VAR
  VAR
    EndDateTime : DT;
    TimerStarted : BOOL;
  END_VAR

  (* Initialize the end date and time *)
  IF NOT TimerStarted THEN
    EndDateTime := StartDateTime + Duration;
    TimerStarted := TRUE;
  END_IF;

  (* Check if the current date and time is within the scheduled period *)
  IF CurrentDateTime >= StartDateTime AND CurrentDateTime < EndDateTime THEN
    TimerOutput := TRUE;
  ELSE
    TimerOutput := FALSE;
    TimerStarted := FALSE; (* Reset the timer for next activation *)
  END_IF;
END_FUNCTION_BLOCK

PROGRAM main
  VAR
    ScheduleTimer : FB_ScheduleTimer;
    CurrentTime : DT;
  END_VAR
  VAR
    OutputSignal AT %QX0.3 : BOOL;
  END_VAR

  ScheduleTimer(StartDateTime := DT#2024-11-14-16:10:00, Duration := T#1h, CurrentDateTime := CurrentTime);
  OutputSignal := ScheduleTimer.TimerOutput;
END_PROGRAM


CONFIGURATION Config0

  RESOURCE Res0 ON PLC
    TASK task0(INTERVAL := T#20ms,PRIORITY := 0);
    PROGRAM instance0 WITH task0 : main;
  END_RESOURCE
END_CONFIGURATION
 
 
Reply 0 0
fg71
If I do exactly what you are saying then I believe it should be like this. In other words I add 1 hour
 
[203128%2F9070417%2Fmceclip0]
Reply 0 0
fg71
I think the problem I have with your example is that epochTimestamp return the number 9 and not something that looks like this 1731627635
The below demonstration show that when I do not use Arduino extension. I get correct date and time.
 
So do you have any idea why I get number 9 from epochTimestamp ??, I also run your Arduino code in Arduino IDE and it return 9 there also.
 
[203128%2F9070479%2Fmceclip0]
Reply 0 0
fg71
This Arduino sketch work for me, there I set a offset in second 3600 to get the date, time and unix epoch
 
#include <RTClib.h>
//#include <Wire.h>
//#include <ESP8266WiFi.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <TimeLib.h>  


RTC_DS3231 rtc;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);


char t[32];
byte last_second, second_, minute_, hour_, day_, month_;
int year_;


void setup()
{
  Serial.begin(9600);  // Initialize serial communication with a baud rate of 9600
  //Wire.begin();  // Begin I2C communication
  rtc.begin();  // Initialize DS3231 RTC module


  // Connect to WiFi
  char* ssid = "ssid"; // Replace with your WiFi SSID
  char* password = "password"; // Replace with your WiFi password
  WiFi.begin(ssid, password);


  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");


  timeClient.begin();  // Start NTP client
  timeClient.update();  // Retrieve current epoch time from NTP server
  unsigned long unix_epoch = timeClient.getEpochTime();  // Get epoch time
  rtc.adjust(DateTime(unix_epoch));  // Set RTC time using NTP epoch time


  DateTime now = rtc.now();  // Get initial time from RTC
  last_second = now.second();  // Store initial second
}


void loop()
{
  timeClient.update();  // Update time from NTP server
  unsigned long unix_epoch = timeClient.getEpochTime();  // Get current epoch time


  second_ = second(unix_epoch);  // Extract second from epoch time
  if (last_second != second_)
  {
    minute_ = minute(unix_epoch);  // Extract minute from epoch time
    hour_ = hour(unix_epoch);  // Extract hour from epoch time
    day_ = day(unix_epoch);  // Extract day from epoch time
    month_ = month(unix_epoch);  // Extract month from epoch time
    year_ = year(unix_epoch);  // Extract year from epoch time

  // Format and print NTP time on Serial monitor
  sprintf(t, "NTP Time: %02d:%02d:%02d %02d/%02d/%02d", hour_, minute_, second_, day_, month_, year_);
  Serial.println(t);
  Serial.println(unix_epoch);
  delay(1000);  // Delay for 1 second before the next iteration
}
}
 
Reply 0 0
thiagoralves
I’m using another method from the library. The OpenPLC project I attached is fully functional if you want to test it. It is adjusted for GMT-5 as you can see from the ladder diagram. You can change the math to be whatever you want
Reply 0 0
fg71
To debug your code in Arduino IDE to be able to print on serial console. In other words it almost impossible to debug anything in OpenPLC if the PLC program compile without any error. To be able to Serial.println() in setup loop I need to include delay of 1 second so the connection was success.
I was able to print the epochTimestamp to Serial console with Arduino IDE.
 
If I try to do the same with Arduino extension with delay of 1 second and do Serial.println(epochTimestamp); it will only return 1 or 2 digits.
 
So I do not think its a problem with your code (Arduino Extension), there is something else that is different compare to Arduino IDE vs OpenPLC Editor.
The only way for me to print on Serial Console in Arduino IDE with correct epochTimestamp was to make sure the WiFi connection was success
before we could get data. I have also try to change the cycle time but that didn't work.
 
I couldn't understand why OpenPLC (your code) only return 2 digits for epochTimestamp variable when it doesn't in Arduino IDE.
 
I understand about the timezone but I have a different problem that you could read above. If the epochTimestamp only return 1 or 2 digits
it will not work and the rest of your blocks.
Reply 0 0
thiagoralves
I'm not using Arduino IDE, just OpenPLC. You don't have to print to console. You can launch the debugger (blue bug icon on toolbar) and then visualize the code in realtime - including the current value of the DT variable.
 
Your code probably is messed up because you included delays. You should never add delays on Arduino Extension or it will lock up the runtime. My code only makes one retrieval from the NTP server on initialization to get the right time. It does not make recurrent retrievals in a loop. After the first retrieval at initialization, the time is counted internally using the RTC block
Reply 0 0
fg71
Dear Thiago Alves, Lets me explain, I think you have misunderstood me.
 
If I run your code without touching it, it will not get the hole bytes of epochTimestamp it only give 1 or 2 digits.
It means current time become 9 second before the RTC. I see this from the Remote Debugger.
 
Here is a screenshot of your PLC program that I have not touch, the digits is 9 and not what I aspects like 1731677843
 
[203128%2F9070956%2Fmceclip0]
 
 
Why I use a delay is to debug your code in Arduino IDE and output to Serial Console from setup loop() that is only running once.
When we know what a variable value contains we remove this delay. In other words the delay has nothing to do with your PLC program.
What it does explain is that epochTimestamp variable return something different from Arduino IDE compare to OpenPLC + Arduino extension.
 
I use Nano ESP32 and not same board you have been using.
 
Lets say your PLC program start before the WiFi connection is success it will not get RTC. And will not check again because it doesn't know if the
data is correct or not. So I used Arduino IDE with your Arduino extension code and it was the same. So to rule out if there is connection delay.
I need to set a delat in setup loop so the epochTimestamp have time to get it data. That was the reason for the delay to debug in Arduino IDE.
 
If you do not believe me test this code and if you could print in console the correct epochTimestamp without a delay in Arduino IDE then
you system is different from mine. I will do more research why it doesn't work for Nano Esp32.
My conclusion is if Serial.println() function couldn't print the correct RTC from a variable it could be that the connection is delayed.
 
The code below is exactly the code you made, I have only include things so I could use WiFi.
I also included offset of 3600 seconds to match my time +1
 
Let me know what below Arduino Code return with or without delay in Arduino IDE (Not in OpenPLC)
 
#include <NTPClient.h>
#include <WiFi.h>
#include <WiFiUdp.h>

const char *ssid = "ssid";
const char *password = "password";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP,"europe.pool.ntp.org", 3600, 60000);

int cycleCount = 0;
bool clockSet;
unsigned long epochTimestamp;

void setup()
{
    // Read time from NTP Server
    Serial.begin(9600);
    WiFi.begin(ssid, password);
    
    // wait 1 second so we have time to connect.
    //delay(1000);

    timeClient.begin();
    timeClient.update();
    epochTimestamp = timeClient.getEpochTime();
    Serial.println(epochTimestamp);
}

void loop()
{
    // Wait for a couple scan cycles to start RTC clock
    if (cycleCount < 10)
    {
        cycleCount++;
    }
    else
    {
        clockSet = true; // Start RTC clock
    };
}
 
Reply 0 0
thiagoralves
The PLC program I uploaded works just fine on my environment, however I'm using Arduino Nano 33 IoT, not the Nano ESP32 like you. I don't know why it is having different results on the Arduino IDE and on OpenPLC, maybe the version of the library is different on both? Try updating the library to the latest version on Arduino IDE, which should make it up to date on OpenPLC as well. OpenPLC runtime initializes the network first before running the Arduino Extension, so you should be good there. The other thing you can try is run the query 3 or 4 times on the loop function before setting the clockSet variable to true.
Reply 0 0
fg71
I did the same test on Giga r1, and I didn't need a delay of 1 second to get RTC in Arduino IDE.
 
I will trying to see if I could find anything on the net if someone else have a delay in connection with Nano Esp32
Reply 0 0
thiagoralves
Instead of adding a delay, just do a cycle count on your Arduino Extension loop function. You can increment a cycleCount variable by one every time the loop is called. If your cycle time is 20ms (that's the default), and you count cycles up to 100, that's equivalent of a 2 second delay. Something like this should work:
//////////////////////////////// sketch section ////////////////////////////////

#include <NTPClient.h>

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
int cycleCount = 0;

void sketch_setup()
{
    
}

void sketch_loop()
{
    // Wait for a couple scan cycles to fetch time from the NTP server
    if (cycleCount < 100)
    {
        cycleCount++;
    }
    else if (cycleCount == 100)
    {
        // Read time from NTP Server
        timeClient.begin();
        timeClient.update();
        epochTimestamp = timeClient.getEpochTime();
    }
    else if (cycleCount == 150)
    {
        clockSet = true; // Start RTC clock
    }
}
 
Reply 0 0
fg71
I will try it, looks like the only option (its not a good day). I told you Giga r1 worked in Arduino IDE without delay but it do not work at all in OpenPLC Editor. I do know I updated the firmware and board library to 4.2.1 like most mbed os share the same version number. This version fixed many things from LVGL library for GigaDisplay Shield. That said now it doesn't upload the sketch to the board. It compile and everything but it will not find the board.
I will check my computer if there is other dfu-util I get Failed uploading: uploading error: exit status 74 on the Giga r1
 
Everything is working fine in Arduino IDE for Giga r1
 
I will not be surprised if this error is not present in macOS, I have many strange issues with usb on Windows.
 
But first test would be to install the old firmware and board library, I know that have worked before.
Reply 0 0
fg71
I could confirm that Giga r1 version 4.1.5 do work with OpenPLC but not 4.2.1
 
Do you know any reason for that?
 
One of the biggiest reason to use version 4.2.1 it have support for LVGL 9 and I use Squareline Studio with this board and GigaDisplay Shield
Reply 0 0
fg71
I did some reset of the boatloader with a custom script not sure if that made it, but I got Giga 4.2.1 to work with OpenPLC.
So know I have at least 1 device that work with your Arduino extension.
 
Its one step closer to my Schedule Function Block.
 
Here is a screenshot from Giga r1
 
[203128%2F9071847%2Fmceclip0]
Reply 0 0
Reply