Arduino: Ethernet UDP Send isi Analog Input 0 ke Graphite di Server

From OnnoWiki
Jump to navigation Jump to search

Code

/*
 UDPSendAnalogInput:
 
 Kirim pakai UDP ke 192.168.0.100:2003
 
 Format
 test.data analogdata unixtime
 
 Sinkronisasi waktu dari PC linux menggunakan perintah
 
 date +T%s\n > /dev/ttyACM0
 date +T%s\n > /dev/ttyACM1
 date +T%s\n > /dev/ttyACMx

 created 27 Feb 2016
 by Onno W. Purbo
*/

#include <SPI.h>   // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
#include <TimeLib.h> 

#define TIME_HEADER  "T"   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message 
 

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0x02, 0xCA, 0xFF, 0xEE, 0xBA, 0xBE
};
IPAddress ip(192, 168, 0, 4);
unsigned int localPort = 8888; // local port to listen on

// Kirim ke graphite carbon cache di 192.168.0.100:2003 melalui UDP
EthernetUDP Udp;
IPAddress remoteIP(192,168,0,100);
unsigned int remotePort = 2003;
void setup() {
  // start the Ethernet and UDP:
  Ethernet.begin(mac, ip);
  Udp.begin(localPort);
  Serial.begin(9600);
  setSyncProvider( requestSync);  //set function to call when sync required
  Serial.println("Waiting for sync message");
}

void loop() {
  if (Serial.available()) {
    processSyncMessage();
  }
  if(timeStatus() == timeNotSet)
    Serial.println("waiting for sync message");
  else {
    Udp.beginPacket(remoteIP, remotePort);
    int sensorReading = analogRead(0);
    Udp.write("test.data ");
    Udp.print(sensorReading); 
    Udp.write(" ");
    Udp.println(now());
    
    Serial.write("test.data ");
    Serial.print(sensorReading); 
    Serial.write(" ");
    Serial.println(now());
    Udp.endPacket(); }
  delay(100);
}

void processSyncMessage() {
  unsigned long pctime;
  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 

  if(Serial.find(TIME_HEADER)) {
     pctime = Serial.parseInt();
     if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
       setTime(pctime); // Sync Arduino clock to the time received on the serial port
     }
  }
}

time_t requestSync()
{
  Serial.write(TIME_REQUEST);  
  return 0; // the time will be sent later in response to serial mesg
}

Referensi