Arduino Tweet Tool

  • Posted on: 17 June 2014
  • By: jimusik

I'm attempting to build something that will send a message about an alarm over ethernet.  I currently have the following:

  • Arduino Uno
  • Ethernet Shield
  • Breadboard with switch and resistors

Currently the attempt is to get the current UTC from a NTP and send a tweet when the button is pressed warning of the alarm along with the time.  Ultimately I will connect an optioisolator to the 12volt circut activating the alarm and have it trigger the same digital pin read to send the tweet.  

Code is patched from: http://arduino.cc/en/Tutorial.UdpNtpClient and http://tronixstuff.com/2013/12/04/arduino-tutorials-chapter-30-twitter/ using http://arduino-tweet.appspot.com/ to do the actual tweeting.

Here's the breadboard setup:

 

Here's the code:

/*

 Udp NTP Client parsed together with simple twitter interface

 */

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Twitter.h>

byte mac[] = {   0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 1, 5}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaaa"); // replace aaaaaaa with your token

unsigned int localPort = 8888;      // local port to listen for UDP packets
unsigned long hours, minutes;  //this will store UTC time later
int timestring[] = {00, 00}; //this sets an array to hold the UTC time for dispaying in the tweet
int digital7; //this is our digital input
char tweetText[140];
IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  // start Ethernet and UDP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }
  Udp.begin(localPort);
  pinMode(7, INPUT); //set the pin 7 to INPUT for noticing the buttin input
  Serial.print("My IP address: ");  //just to show the ip address through serial
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("."); 
  }
  Serial.println();
  }
 
void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()  //in order to only run the time and tweet functions when the button is pushed.
{
  
 while (digitalRead(7) == HIGH){
   getTime();
   alarm();
   }

}
void getTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server

    // wait to see if a reply is available
  delay(1000);  
  if ( Udp.parsePacket() ) {  
    // We've received a packet, read the data from it
    Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;  
    Serial.print("Seconds since Jan 1 1900 = " );
    Serial.println(secsSince1900);               

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;     
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;  
    // print Unix time:
    Serial.println(epoch);                               


    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    hours = (epoch  % 86400L) / 3600; //this takes what was printed and stores it in hours
    Serial.print(':');  
    if ( ((epoch % 3600) / 60) < 10 ) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    minutes = (epoch  % 3600) / 60; //this takes what was printed and stores it in minutes
    Serial.print(':'); 
    if ( (epoch % 60) < 10 ) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch %60); // print the second
  }
  // wait ten seconds before asking for the time again (left over from the previous loop)
  //delay(10000); 
}

void alarm()
{
  timestring[1] = hours; //dump the above UTC hours into an array
  timestring[2] = minutes; //dump the above UTC minutes into an array
  if(minutes<10){ //make sure the minutes look correct with a leading zero when below 10
  sprintf(tweetText, "Current Status: ALARM @username from Arduino UTC = %d:0%d", timestring[1], timestring[2]);
                }
else{ //pring the gathered info normally if minutes above 10
  sprintf(tweetText, "Current Status: ALARM @username from Arduino UTC = %d:%d", timestring[1], timestring[2]); // change @username to your twitter account name
}
  delay(1000);
  tweet(tweetText); //just comment this line to run test and avoid multiple tweets
  Serial.println("tweeting");
  Serial.println(tweetText); //serial print to see what was tweeted
}
// send an NTP request to the time server at the given address 
unsigned long sendNTPpacket(IPAddress& address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE); 
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49; 
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:         
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket(); 
}

Obviously I'm new to Arduino Code and always would appreciate feedback if you have any.