To Obtain Network Time
ObjectiveThe course will teach you how to use Processing to display the network time acquired by Microduino. Equipment
SchematicJust stack the four Microduino modules mentioned above. ProgramDebuggingStep 1: Build the hardware environment according to the schematic, as follows:
The code of the two ends(Processing and Microduino) Microduino: There are many time servers on the internet such as the time server offered by American's NIST(National Institute of Standards and Technology) and the time server provided by Italy's INRiM(Istituto Nazionale di Ricerca Metereologica):
static byte ntpServer[] = {193,204,114,232}; There are two methods for NTP request:
The srcPort parameter is used to find a data packets containing NTP server response among many receiving packets of the ENC28J60 module. You can choose the value according to individual needs, but the parameters in the ntpRequest and ntpProcessAnswer methods should remain the same. After acquiring the value of the time stamp, you have to convert it into data-time format. As follows:
Mistakes easily to be made: Leap Year probably: If it is Leap Year, 365*86500 seconds must be replaced by 366*86500 seconds. Here is the way to judge whether it is Leap Year: boolean isLeapYear(unsigned int year) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } Since the number of days in each month changes, you should put these values in an array. Here is the format: static int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; If it is Leap Year, there are 29 days in February: if(isLeapYear(year) && month == 1) seconds = SECONDS_IN_DAY * 29; The time stamp refers to GMT(Greenwich Mean Time). If you live in a different time zone, you must correct the value: #define TIME_ZONE +1 [...] printDate(timeStamp + 3600 * TIME_ZONE);
Processing: //Acquire the data of the first serial port and define it. Or cache it if there is a new line println(Serial.list()); // is always my Arduino, so I open Serial.list()[0]. // Open whatever port is the one you're using. myPort = new Serial(this, Serial.list()[0], 9600); myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
//read port data String val = myPort.readStringUntil('\n'); if (val != null) { val = trim(val); println(val); if (val.startsWith("time:")) { //if some exception happend, initial time is 0 colock try { timeShow=val.substring(5,13); } catch (NumberFormatException e) { println("error:"+val); } //Display Text text ( timeShow, 90, 120); } } Step 3: Download the code and get it compiled successfully. Step 4: See what happens in Processing. ResultThere will appear network time on the screen
Video |