Arduino Tweet Tool 2.0

  • Posted on: 24 June 2014
  • By: jimusik

I've managed to upgrade and modify the Arduino Tweet Tool.  Version 2.0 currently does the following:

  • Monitores it's up time
  • Flashes a Green Light while it's waiting for input
  • Sends a Check-in Tweet weekly with time in PST
  • When activated, flashes a Red LED for as long as the trigger is activated or approx. 60 seconds (delayed to reduce too many tweets to the server)
  • The alarm sends a tweet warning of the Alarm, tagging my personal twitter account and includes PST

This will be built into a small black box with the LED's visable.  The trigger will be connected to a Float Switch that will activate the Alarm.

Here's the code (sans personal information):

/*

 Udp NTP Client parsed together with simple twitter interface
 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.

 */

#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("aaaaaaaaa"); // 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
int REDLED = 8;
int GREENLED = 6;
int timezone = 8; //PST this will not monitor daylight savings
long previousMillis = 0;
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
  pinMode(GREENLED, OUTPUT); //set pin 6 to be the active LED
  pinMode(REDLED, OUTPUT); //set pin 8 to be the ALARM LED 
  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();
   }
  digitalWrite(GREENLED, HIGH);
  delay(1000); // wait 1000 ms
  digitalWrite(GREENLED, LOW);
  delay(1000); 
  
  //routine checkin
  unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis > 604800000) { //604800000 weekly
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   
   getTime();
   checkin(); 
  }
}

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 checkin()
{
  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, "System Functional from Arduino PST = %d:0%d", timestring[1] - timezone, timestring[2]);
                }
else{ //pring the gathered info normally if minutes above 10
  sprintf(tweetText, "System Functional from Arduino PST = %d:%d", timestring[1] - timezone, 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
  
// FLASH RED LED once
  digitalWrite(REDLED, HIGH); 
  delay(500);
  digitalWrite(REDLED, LOW);
  delay(500);
}

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 PST = %d:0%d", timestring[1] - timezone, timestring[2]);
                }
else{ //pring the gathered info normally if minutes above 10
  sprintf(tweetText, "Current Status: ALARM @username from Arduino PST = %d:%d", timestring[1] - timezone, 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
  
  for (int i = 0; i < 61; i++) {// FLASH RED LED
  digitalWrite(REDLED, HIGH); 
  delay(500);
  digitalWrite(REDLED, LOW);
  delay(500);
  }
}
// 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(); 
}

Tags: Arduino Uno, Ethernet Shield, Tweet, Twitter, Digital Alarm System, Sump Pump, Arduino Code, Time Server, Triggering SMS and Email