In this post, I will explain how to get the Local Time from your TwinCAT CPU.Although Some applications are connected with NTP server to sync the Time,lots of applications set the time directly.
Insert the Library
References>Add library.
Search the Tc2_Utilities and OK.
Function Block
FB_LocalSystemTime is a function block for you to get the local time of the local windows system.This Function Block is combined with a couple of Functions.
-RTC_EX2:create a timestamp for log
-NT_GetTime:as to be resynchronized cyclically via the NT_GetTime function block
-FB_GetTimeZoneInformation,NT_SetTimeToRTCTime
FInally we can define the cycle time to get the local time .
And also Summer,Winter,Timezone is an option.
The Output format is TIMESTRUCT.
*Please call the FB_LocalSystemTime cyclically.
VAR_INPUT
sNetID | T_AmsNetID | The ID of TwinCAT Target、Please use empty in the local system. |
bEnable | BOOL | Pulse rise = start |
dwCycle | DWORD(1..86400) | sync cycle |
dwOpt | DWORD | Options,Bit0=True,Windows System Will sync the time with Hardware RTC. |
tTimeout | TIME |
VAR_OUTPUT
bValid | BOOL | 1=the current output of time is valid or not. |
systemTime | TIMESTRUCT | Local Windows System Time |
tzID | E_TimeZoneID | Summer/Winter |
PROGRAM
Here is the sample code and The Function block of LocalSystemTime is called and get the local time in a fixed cycle,
VAR
VAR bTimeSyncError :BOOL; bReset :BOOL; bTimeIsSynced :BOOL; TimeStruct :TIMESTRUCT; InitTimeStruct :TIMESTRUCT; LocalSystemTime :FB_LocalSystemTime; dwCycle:INT:=1; TON:TON; END_VAR |
VAR CONSTANT
VAR CONSTANT ciTimeValidCheckOffset:INT:=1; END_VAR |
Code
IF NOT bTimeIsSynced THEN TimeStruct:=InitTimeStruct; END_IF LocalSystemTime( bEnable:=TRUE ,dwCycle:=1 ); TON( IN:=NOT LocalSystemTime.bValid ,PT:=INT_TO_TIME( (dwCycle+ciTimeValidCheckOffset)*1000 ) ); IF LocalSystemTime.bValid THEN bTimeIsSynced:=TRUE; TimeStruct:=LocalSystemTime.systemTime; END_IF IF TON.Q THEN bTimeSyncError:=TRUE; END_IF IF bReset THEN bTimeSyncError:=FALSE; END_IF |
Result
TimeStruct output.
Please download the source code from here:
https://github.com/soup01Threes/TwinCAT3/blob/main/TwinCAT%20Project_getSystemTime.tnzip