Sponsored Content
Top Forums Programming Arduino UNIX Time - Syncing Computer UNIX Time to Arduino Time with Python Post 303042409 by Neo on Monday 23rd of December 2019 11:53:59 PM
Old 12-24-2019
Here is a quick sketch I put together for the Arduino UNO to get the unix time from the usb serial port and sync the Arduino time to the computer (in my case macos).

This sketch works but needs more refinement (trap errors, disconnects, add options, etc) but since I will not be doing much with this for the next few weeks, I post the first working draft below and will also post the python script I use on macos soon:

Code:
/*
  Sync UNIX Time with Computer and
  LCD Display with I2C on Arduino UN0
  Rough Draft 0.1  (needs improvements)
  Neo December 2019
  https://www.unix.com
*/

// Include Wire Library for I2C
#include <Wire.h>
// Include NewLiquidCrystal Library for I2C
#include <LiquidCrystal_I2C.h>
#include <Time.h>
#include <TimeLib.h>

#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by Unix time_t as ten ASCII digits
#define TIME_HEADER 'T' // Header tag for serial time sync message
#define TIME_REQUEST 7  // ASCII bell character requests a time sync message
#define DEBUG_SKETCH false
// Define LCD pinout
const int en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3;
// can be any integer greater than zero and less than recent unix time
const int time_int = 1000;
// Define I2C Address - change if reqiuired
const int i2c_addr = 0x27;
String s;
bool flag = true;
time_t t = now();
LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE);
void setup()
{
    Serial.begin(9600);
    Wire.begin();
    time_t t = now();
    lcd.begin(16, 2);
    lcd.clear();
}

void loop()
{
    lcd.clear();
    int count = 0;
    if (Serial.available() and flag)
    {
        lcd.clear();
        lcd.setCursor(0, 1);
        lcd.print("Serial OK");
        count = processSyncMessage();
        if (DEBUG_SKETCH)
        {
               Serial.println("Serial Available: " + count);
        }
        if (count > time_int)
            flag = false;
    }

    lcd.setCursor(0, 0);
    if (timeStatus() == timeNotSet)
    {
        if (flag)
        {
            Serial.println("waiting for sync message");
            lcd.print("Arduino Time:");
        }
    }
    else
    {

        lcd.print("Unix Time:");
        if (DEBUG_SKETCH)
        {
            Serial.println("Time Synced");
        }
    }
    t = now();
    s = String(t);
    if (s != '0')
    {
        lcd.setCursor(0, 1);
        lcd.print(t);
        lcd.print(" secs");
    }
    Serial.println(s);
    delay(1000);
    lcd.clear();
}

int processSyncMessage()
{
    while (Serial.available() >= TIME_MSG_LEN)
    { // time message consists of header & 10 ASCII digits
        char c = Serial.read();
        int count = 0;
        Serial.print(c);
        time_t pctime = 0;
        if (c == TIME_HEADER)
        {
            for (int i = 0; i < TIME_MSG_LEN - 1; i++)
            {
                c = Serial.read();
                if (c >= '0' && c <= '9')
                {
                    Serial.print(c);
                    count++;
                    pctime = (10 * pctime) + (c - '0'); // convert digits to a number
                }
            }
            Serial.print("\n");
            if (DEBUG_SKETCH)
            {
                Serial.write(pctime + "\n");
                Serial.println(pctime);
            }
            setTime(pctime); // Sync Arduino clock to the time received on the serial port
        }
        return count;
    }
}

 

9 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Help me!First time use UNIX.

I am assigned a programming work.It is my first time to use unix. The task is writing a shell script to interrogate the university Unix operating system to determine the number of "Runnable" processes at any given time.Then append the result,along with a time-stamp,on a log file. Also there are... (1 Reply)
Discussion started by: zhshqzyc
1 Replies

2. UNIX for Advanced & Expert Users

How To Provide Time Sync Using Nts-150 Time Server On Unix Network?

can anybody tel lme,how to instal NTS -150 on a unix network,it needs some patch to fetch time frm serve,,?? (2 Replies)
Discussion started by: pesty
2 Replies

3. Shell Programming and Scripting

Convert Unix Time to Standard Time

I have a list of interfaces and time the interface was last active. I can't figure out how to convert the time in the second column, Fa1/14 0 Se0/0/0 0 Fa1/11 0 Fa1/9 0 Fa1/0 0 Se0/0/1 1240401408 Gi1/0 0 Fa0/0 1240401408 Fa1/3 0 Fa1/8 0 Fa1/15 0 Fa1/13 0 Fa1/10 0 Fa1/1 0 Fa1/12... (7 Replies)
Discussion started by: mrlayance
7 Replies

4. Shell Programming and Scripting

Unix time

how do i convert unix time to show normal eg i have unix time 1297702242 and i want it converted to normal time. how do i do that (2 Replies)
Discussion started by: blackzinga80
2 Replies

5. Shell Programming and Scripting

How to get time duration between two human readable time stamp in Unix?

Here is two time I have: Jul 12 16:02:01 Jul 13 01:02:01 and how can I do a simple match to get difference between two time which is 09:00:00 Thanks in advance. (3 Replies)
Discussion started by: ford99
3 Replies

6. UNIX for Dummies Questions & Answers

Converting string date time to unix time in AWK

I'd like to convert a date string in the form of sun aug 19 09:03:10 EDT 2012, to unixtime timestamp using awk. I tried This is how each line of the file looks like, different date and time in this format Sun Aug 19 08:33:45 EDT 2012, user1(108.6.217.236) all: test on the 17th ... (2 Replies)
Discussion started by: bkkid
2 Replies

7. Shell Programming and Scripting

Adding time to date time in UNIX shell scipting

I needed some help in adding a duration (in seconds) to a start time (in hhmmss format) and a start date (in mmddyy format) in order to get an end date and end time. The concept of a leap year is also to be considered while incrementing the day. The code/ function that I have formed so far is as... (3 Replies)
Discussion started by: codehelp04
3 Replies

8. Shell Programming and Scripting

Convert UTC time into current UNIX sever time zone

Hi guys thanks for the help for my previous posts.Now i have a requirement that i download a XMl file which has UTC time stamp.I need to convert UTC time into Unix server timezone. For ex if the time zone of unix server is CDT then i need to convert into CDT.whatever may be the system time... (5 Replies)
Discussion started by: mohanalakshmi
5 Replies

9. Programming

Arduino-cli - Uploading to Unknown Chinese Arduino Boards using the Arduino Command Line Interface

In my further exploration of Arduino, today I decided to install the arduino-cli on my mac today. https://github.com/arduino/arduino-cli I followed the instructions for macOS but when I got to this part: arduino-cli board list I got the dreaded "Unknown" Fully Qualified Board Name... (1 Reply)
Discussion started by: Neo
1 Replies
ost::Serial(3)						     Library Functions Manual						    ost::Serial(3)

NAME
ost::Serial - The Serial class is used as the base for all serial I/O services under APE. SYNOPSIS
#include <serial.h> Inherited by ost::SerialPort, and ost::TTYStream. Public Types enum Error { errSuccess = 0, errOpenNoTty, errOpenFailed, errSpeedInvalid, errFlowInvalid, errParityInvalid, errCharsizeInvalid, errStopbitsInvalid, errOptionInvalid, errResourceFailure, errOutput, errInput, errTimeout, errExtended } enum Flow { flowNone, flowSoft, flowHard, flowBoth } enum Parity { parityNone, parityOdd, parityEven } enum Pending { pendingInput, pendingOutput, pendingError } typedef enum Error Error typedef enum Flow Flow typedef enum Parity Parity typedef enum Pending Pending Public Member Functions virtual ~Serial () The serial base class may be 'thrown' as a result on an error, and the 'catcher' may then choose to destory the object. Serial & operator= (const Serial &from) Serial ports may also be duplecated by the assignment operator. Error setSpeed (unsigned long speed) Set serial port speed for both input and output. Error setCharBits (int bits) Set character size. Error setParity (Parity parity) Set parity mode. Error setStopBits (int bits) Set number of stop bits. Error setFlowControl (Flow flow) Set flow control. void toggleDTR (timeout_t millisec) Set the DTR mode off momentarily. void sendBreak (void) Send the 'break' signal. Error getErrorNumber (void) Often used by a 'catch' to fetch the last error of a thrown serial. char * getErrorString (void) Often used by a 'catch' to fetch the user set error string of a thrown serial. int getBufferSize (void) Get the 'buffer' size for buffered operations. virtual bool isPending (Pending pend, timeout_t timeout=TIMEOUT_INF) Get the status of pending operations. Protected Member Functions void open (const char *fname) Opens the serial device. void close (void) Closes the serial device. virtual int aRead (char *Data, const int Length) Reads from serial device. virtual int aWrite (const char *Data, const int Length) Writes to serial device. Error error (Error error, char *errstr=NULL) This service is used to throw all serial errors which usually occur during the serial constructor. void error (char *err) This service is used to thow application defined serial errors where the application specific error code is a string. void setError (bool enable) This method is used to turn the error handler on or off for 'throwing' execptions by manipulating the thrown flag. int setPacketInput (int size, unsigned char btimer=0) Set packet read mode and 'size' of packet read buffer. int setLineInput (char newline=13, char nl1=0) Set 'line buffering' read mode and specifies the newline character to be used in seperating line records. void restore (void) Restore serial device to the original settings at time of open. void flushInput (void) Used to flush the input waiting queue. void flushOutput (void) Used to flush any pending output data. void waitOutput (void) Used to wait until all output has been sent. void endSerial (void) Used as the default destructor for ending serial I/O services. void initConfig (void) Used to initialize a newly opened serial file handle. Serial () This allows later ttystream class to open and close a serial device. Serial (const char *name) A serial object may be constructed from a named file on the file system. Protected Attributes HANDLE dev int bufsize Detailed Description The Serial class is used as the base for all serial I/O services under APE. A serial is a system serial port that is used either for line or packet based data input. Serial ports may also be 'streamable' in a derived form. Common C++ serial I/O classes are used to manage serial devices and implement serial device protocols. From the point of view of Common C++, serial devices are supported by the underlying Posix specified 'termios' call interface. The serial I/O base class is used to hold a descriptor to a serial device and to provide an exception handling interface for all serial I/O classes. The base class is also used to specify serial I/O properties such as communication speed, flow control, data size, and parity. The 'Serial' base class is not itself directly used in application development, however. Common C++ Serial I/O is itself divided into two conceptual modes; frame oriented and line oriented I/O. Both frame and line oriented I/O makes use of the ability of the underlying tty driver to buffer data and return 'ready' status from when select either a specified number of bytes or newline record has been reached by manipulating termios c_cc fields appropriately. This provides some advantage in that a given thread servicing a serial port can block and wait rather than have to continually poll or read each and every byte as soon as it appears at the serial port. Author: David Sugar dyfet@ostel.com base class for all serial I/O services. Member Typedef Documentation typedef enum Error ost::Serial::Error typedef enum Flow ost::Serial::Flow typedef enum Parity ost::Serial::Parity typedef enum Pending ost::Serial::Pending Member Enumeration Documentation enum ost::Serial::Error Enumerator: errSuccess errOpenNoTty errOpenFailed errSpeedInvalid errFlowInvalid errParityInvalid errCharsizeInvalid errStopbitsInvalid errOptionInvalid errResourceFailure errOutput errInput errTimeout errExtended enum ost::Serial::Flow Enumerator: flowNone flowSoft flowHard flowBoth enum ost::Serial::Parity Enumerator: parityNone parityOdd parityEven enum ost::Serial::Pending Enumerator: pendingInput pendingOutput pendingError Constructor &; Destructor Documentation ost::Serial::Serial () [inline], [protected] This allows later ttystream class to open and close a serial device. ost::Serial::Serial (const char *name) [protected] A serial object may be constructed from a named file on the file system. This named device must be 'isatty()'. @param name of file. virtual ost::Serial::~Serial () [virtual] The serial base class may be 'thrown' as a result on an error, and the 'catcher' may then choose to destory the object. By assuring the socket base class is a virtual destructor, we can assure the full object is properly terminated. Member Function Documentation virtual int ost::Serial::aRead (char *Data, const intLength) [protected], [virtual] Reads from serial device. Parameters: Data Point to character buffer to receive data. Buffers MUST be at least Length + 1 bytes in size. Length Number of bytes to read. virtual int ost::Serial::aWrite (const char *Data, const intLength) [protected], [virtual] Writes to serial device. Parameters: Data Point to character buffer containing data to write. Buffers MUST Length Number of bytes to write. void ost::Serial::close (void) [protected] Closes the serial device. Reimplemented in ost::ttystream. void ost::Serial::endSerial (void) [protected] Used as the default destructor for ending serial I/O services. It will restore the port to it's original state. Error ost::Serial::error (Errorerror, char *errstr = NULL) [protected] This service is used to throw all serial errors which usually occur during the serial constructor. Parameters: error defined serial error id. errstr string or message to optionally pass. void ost::Serial::error (char *err) [inline], [protected] This service is used to thow application defined serial errors where the application specific error code is a string. Parameters: err string or message to pass. References error(). Referenced by error(). void ost::Serial::flushInput (void) [protected] Used to flush the input waiting queue. void ost::Serial::flushOutput (void) [protected] Used to flush any pending output data. int ost::Serial::getBufferSize (void) [inline] Get the 'buffer' size for buffered operations. This can be used when setting packet or line read modes to determine how many bytes to wait for in a given read call. Returns: number of bytes used for buffering. Error ost::Serial::getErrorNumber (void) [inline] Often used by a 'catch' to fetch the last error of a thrown serial. Returns: error numbr of last Error. char* ost::Serial::getErrorString (void) [inline] Often used by a 'catch' to fetch the user set error string of a thrown serial. Returns: string for error message. void ost::Serial::initConfig (void) [protected] Used to initialize a newly opened serial file handle. You should set serial properties and DTR manually before first use. virtual bool ost::Serial::isPending (Pendingpend, timeout_ttimeout = TIMEOUT_INF) [virtual] Get the status of pending operations. This can be used to examine if input or output is waiting, or if an error has occured on the serial device. Returns: true if ready, false if timeout. Parameters: pend ready check to perform. timeout in milliseconds. Reimplemented in ost::TTYStream. void ost::Serial::open (const char *fname) [protected] Opens the serial device. Parameters: fname Pathname of device to open Reimplemented in ost::ttystream. Serial& ost::Serial::operator= (const Serial &from) Serial ports may also be duplecated by the assignment operator. void ost::Serial::restore (void) [protected] Restore serial device to the original settings at time of open. void ost::Serial::sendBreak (void) Send the 'break' signal. Error ost::Serial::setCharBits (intbits) Set character size. Returns: 0 on success. Parameters: bits character size to use (usually 7 or 8). void ost::Serial::setError (boolenable) [inline], [protected] This method is used to turn the error handler on or off for 'throwing' execptions by manipulating the thrown flag. Parameters: enable true to enable handler. Error ost::Serial::setFlowControl (Flowflow) Set flow control. Returns: 0 on success. Parameters: flow control mode. int ost::Serial::setLineInput (charnewline = 13, charnl1 = 0) [protected] Set 'line buffering' read mode and specifies the newline character to be used in seperating line records. isPending can then be used to wait for an entire line of input. Parameters: newline newline character. nl1 EOL2 control character. Returns: size of conical input buffer. int ost::Serial::setPacketInput (intsize, unsigned charbtimer = 0) [protected] Set packet read mode and 'size' of packet read buffer. This sets VMIN to x. VTIM is normally set to '0' so that 'isPending()' can wait for an entire packet rather than just the first byte. Returns: actual buffer size set. Parameters: size of packet read request. btimer optional inter-byte data packet timeout. Error ost::Serial::setParity (Parityparity) Set parity mode. Returns: 0 on success. Parameters: parity mode. Error ost::Serial::setSpeed (unsigned longspeed) Set serial port speed for both input and output. Returns: 0 on success. Parameters: speed to select. 0 signifies modem 'hang up'. Error ost::Serial::setStopBits (intbits) Set number of stop bits. Returns: 0 on success. Parameters: bits stop bits. void ost::Serial::toggleDTR (timeout_tmillisec) Set the DTR mode off momentarily. Parameters: millisec number of milliseconds. void ost::Serial::waitOutput (void) [protected] Used to wait until all output has been sent. Member Data Documentation int ost::Serial::bufsize [protected] HANDLE ost::Serial::dev [protected] bool ost::Serial::linebuf bool ost::Serial::thrown Author Generated automatically by Doxygen for GNU CommonC++ from the source code. GNU CommonC++ Sat Jun 23 2012 ost::Serial(3)
All times are GMT -4. The time now is 07:25 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy