]> git.piffa.net Git - arduino/blob - books/pdummies/Libraries/Time/Examples/Processing/SyncArduinoClock/SyncArduinoClock.pde
first commit
[arduino] / books / pdummies / Libraries / Time / Examples / Processing / SyncArduinoClock / SyncArduinoClock.pde
1 /**
2  * SyncArduinoClock. 
3  *
4  * portIndex must be set to the port connected to the Arduino
5  * 
6  * The current time is sent in response to request message from Arduino 
7  * or by clicking the display window 
8  *
9  * The time message is 11 ASCII text characters; a header (the letter 'T')
10  * followed by the ten digit system time (unix time)
11  */
12  
13
14 import processing.serial.*;
15
16 public static final short portIndex = 1;  // select the com port, 0 is the first port
17 public static final char TIME_HEADER = 'T'; //header byte for arduino serial time message 
18 public static final char TIME_REQUEST = 7;  // ASCII bell character 
19 public static final char LF = 10;     // ASCII linefeed
20 public static final char CR = 13;     // ASCII linefeed
21 Serial myPort;     // Create object from Serial class
22
23 void setup() {  
24   size(200, 200);
25   println(Serial.list());
26   println(" Connecting to -> " + Serial.list()[portIndex]);
27   myPort = new Serial(this,Serial.list()[portIndex], 9600);
28 }
29
30 void draw()
31 {
32   if ( myPort.available() > 0) {  // If data is available,
33     char val = char(myPort.read());         // read it and store it in val
34     if(val == TIME_REQUEST){
35        long t = getTimeNow();
36        sendTimeMessage(TIME_HEADER, t);   
37     }
38     else
39     { 
40        if(val == LF)
41            ; //igonore
42        else if(val == CR)           
43          println();
44        else  
45          print(val); // echo everying but time request
46     }
47   }  
48 }
49
50 void mousePressed() {  
51   sendTimeMessage( TIME_HEADER, getTimeNow());   
52 }
53
54
55 void sendTimeMessage(char header, long time) {  
56   String timeStr = String.valueOf(time);  
57   myPort.write(header);  // send header and time to arduino
58   myPort.write(timeStr);   
59 }
60
61 long getTimeNow(){
62   // java time is in ms, we want secs    
63   GregorianCalendar cal = new GregorianCalendar();
64   cal.setTime(new Date());
65   int   tzo = cal.get(Calendar.ZONE_OFFSET);
66   int   dst = cal.get(Calendar.DST_OFFSET);
67   long now = (cal.getTimeInMillis() / 1000) ; 
68   now = now + (tzo/1000) + (dst/1000); 
69   return now;
70 }