Monday, 16 November 2015

ESP8266 and Arduino for Logging Data to the Web

Update 2016-12-30: The process has become much simpler. Use the ThingSpeak or AdafruitIO libraries available for IDE 1.6.x and above to interact and avoid having to assemble your own network communications. ThingSpeak is free for the first 3 million channel updates a year, then paid. AdafruitIO is free, but you are limited to 10 fields total. Both limit the update speeds.

One of my students (Stephane Leahy) insisted I should find a way to include the ESP8266 in my grad measurements course for next term, so I had to give it a try. Now that I've proven I can do it, I'm not sure putting it in a course would be so useful, as this is bound to be a moving target. I think the best advice is to know this is possible, then go looking for a sensible solution when you have an actual application that needs it. The ESP8266 is a really cheap solution to adding WiFi when you need it, and may be enough micro-controller to stand alone if you don't need a lot of analog input.

I bought an Adafruit Huzzah ESP8266 breakout board and combined it with an Arduino Micro and some sensors. I used some sample code Stephane provided, then built on it to overcome some of the difficulties I ran into. Wiring was straightforward following the instructions. I added a TMP36 connected to the A (analog A0) pin on the 8266 and connected the RX/TX pins to listen to output from the Micro.


The 8266 is programmed with an FTDI cable over the serial port, so the micro needs to be unpowered, or at least silent, while the programming the 8266. I sorted this out by using a diode to bridge the two power busses at the top of the board. (It's hiding behind the blue pot.) When the Micro is plugged in, it will power both, with the 8266 getting about 4.1V. When only the 8266 is plugged in the Micro is unpowered and silent. I used the Arduino IDE to program the 8266 because it was familiar. When live, the Micro was just chugging along in data logger mode, spitting out lines of CSV data every second or so to the serial port that looked like this:

477971510,   734,   719,   719, 11001111,  1500,  1466,  1461,  3

The 8266 reads this data, parses it, reads an analog input and converts it to temperature, then sends all of that off to ThingSpeak for logging and reporting in the cloud. The resulting graphs look like this once things work:

This particular sequence shows how measuring temperature requires a little finesse. Sitting in the dark all night, the temperature was stable around 22.5C, but once I started working the temperature around my desk started rising. Unplugging the breadboard let it cool down, only to heat back up when it was plugged in again. Finally around 1500 I moved the board to a windowsill to catch the last few rays of late November sun. The indicated temperature peaked just as the sun went behind the building next door. It's hard to tell what is actual room temperature rise through the day and what is just sensor heating from the electronics or the sun.

ESP8266 Challenges

Analog Reading Scale: It wasn't obvious to me what the 8266 was using as a voltage reference for the analog conversions, so I used my multimeter to measure the conversion constant. The lack of clear documentation for the chip is a significant failing, observed by plenty of others.

The fiddly little buttons need to be actuated in sequence, so it was difficult for me to start the programming sequence with my full size fingers.

Analog disables connection for about 5 seconds for no apparent reason (see above for lack of documentation). This quirk would be enough to make me avoid using the analog input entirely, especially since there's only the one channel.

Retrying connection can crash the whole system with an exception number 9, which the web seems to think has something to do with too many connections open, or something (docs?).

Power hungry is only an issue if you need to run the chip on batteries for an extended period.

The code below should be reasonably readable to show how I got past these hurdles. It took a few days to track down the random exceptions, but I will keep my fingers crossed. Feel free to copy and play around with it. Good Luck!


// a minimal ThingSpeak logger based on Stephane Leahy's code --- Rick Sellens 2015-11-14
#include <ESP8266WiFi.h>

// this file should include the next few lines, but with your ssid, password, and thingspeak channel API key
#include "ssid.h"   // create ssid.h as another file tab in your Arduino IDE project.
// #define SSID "MyNetworkName" 
// #define PASS "MyCleverPassword"
// #define HOST "api.thingspeak.com"   // usually results in 0 or 1 retries to get a connection but takes longer then IP
// String link = "/update?key=TheAPIKeyFromMyThingSpeakChannel";

/*
The first client.connect(HOST,80) after reboot always succeeds with 0 retries.
Defining HOST as numerical and commenting out the analogRead() and delay(5000) connects first time, every time.
Uncommenting the analogRead() and success requires about 500 retries (about 5 seconds at 10 ms each).
Switching to a domain name for HOST succeeds after 1 retry (about 5 seconds).
Uncommenting the delay(5000) succeeds with 0 retries for domain name and 0 or 1 retries for numerical IP.
Making the delay 7000 succeeds with 0 retries most times for the numerical IP.

Behaviour is the same when HOST is 205.189.10.43 for weather.gc.ca, so it seems to be a local issue
Moral is probably to accept failure for a while..... and use the domain name version

The logging sometimes fails, so I added a restart condition if the connection doesn't get made quickly enough.
The latest failure said "ets Jan  8 2013,rst cause:4, bootmode:(1,7) \n\n wdt reset" which the online people
suggest has to do with a watchdog timer reset that may happen if it gets stuck in a loop for more than a second,
so it seems like a good idea to make the serial timeout shorter than a second to see if that makes the problem go away.
It didn't go away
  
 870942170,   4998,    477,    343, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    970,    720, 
 871442210,   4998,    476,    346, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    970,    721, 
 871942210,   4998,    476,    348, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    970,    721, 
 872442250,   4998,    477,    344, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    972,    673, 
 872942280,   4998,    477,    341, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    972,    673, 
 873442310,   4998,    477,    338, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    972,    671, 
 873942350,   4998,    477,    336, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    973,    668, 
 874442390,   4998,    477,    338, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    970,    701, 
 874942420,   4998,    477,    340, 0, 1, 1, 1, 1, 1, 1, 0,  10230,    970,    703, 
 875442450, 875442432, 875442432, 875442432, 875442432, 875442432, 875442432, 875442432, 8, 7, 5, 4, 4, 2, 4, 5, 0, 875442450,   4998,    476,    342, 1111110,  10230,    970, 
Exception (9):
epc1=0x401018af epc2=0x00000000 epc3=0x00000000 excvaddr=0x202c3029 depc=0x00000000

ctx: cont 
sp: 3ffea5f0 end: 3ffea870 offset: 01a0

>>>stack>>>
3ffea790:  ffffffff 00000007 3ffea8c8 40202541  
3ffea7a0:  3738200a 32343435 2c303534 35373820  
3ffea7b0:  34323434 202c3233 34353738 33343234  
3ffea7c0:  38202c32 34343537 32333432 3738202c  
3ffea7d0:  32343435 2c323334 35373820 34323434  
3ffea7e0:  202c3233 34353738 33343234 38202c32  
3ffea7f0:  34343537 32333432 2c38202c 202c3720  
3ffea800:  34202c35 2c34202c 202c3220 35202c34  
3ffea810:  2c30202c 35373820 34323434 202c3035  
3ffea820:  39342020 202c3839 34202020 202c3637  
3ffea830:  33202020 202c3234 31313131 2c303131  
3ffea840:  30312020 2c303332 20202020 2c303739  
3ffea850:  3fff0020 00000000 3ffea894 4020186e  
3ffea860:  00000000 00000000 3ffe9850 40100378  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,7)


 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

Apparently exception 9 has something to do with too many floating clients, or something, so I tried lengthening the time
between connection attempts from 10 ms to 100 ms, so it doesn't have to try as many times before the 5 s runs out, or whatever.
2015-11-16: Then it ran all night. 
 */


float smoothTemp = 20.0;
unsigned long t = 0;

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(500L);  // timeout in half a second to keep the wdt reset from triggering on the ESP8266

  // connect to WiFi
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected with ");
  Serial.print("IP address ");
  Serial.println(WiFi.localIP());

}

static unsigned raw[] = {0,0,0,0,0,0,0,0,0,0};
static float cal[] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
static byte digio[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

void loop() {
  static unsigned connFail = 0;       // number of times the connection has failed
  static unsigned smoothies = 0;      // number of samples that have fed into the smoothing, or 20000 max
  static unsigned reported = 0;       // set to one when new data comes in, then back to zero when logged
  unsigned data = 750;                // a not-stupid, not-zero value that could have come from the analog input

  // serial incoming lines from the logger like:  477971510,   734,   719,   719, 11001111,  1500,  1466,  1461,  3
  if(Serial.available()){                            // only if there's something waiting
    String line = Serial.readStringUntil('\n');
    //parse the string for data to report
    String s = line.substring(line.length()-1);     // last character is the number of channels        
    unsigned n = s.toInt();
    line = line.substring(0,line.lastIndexOf(","));

    // take n channels of raw values off the end of the string
    for(int i = n-1;i>=0;i--){
      s = line.substring(line.lastIndexOf(",")+1);
      raw[i] = s.toInt();
      line = line.substring(0,line.lastIndexOf(","));
    }
    
    // take the digital data off the end of the string
    s = line.substring(line.lastIndexOf(",")+1);
    s.trim();
    unsigned nd = s.length();
    for(int i = 0;i < nd;i++) digio[i] = s.charAt(i) - '0';
    line = line.substring(0,line.lastIndexOf(","));

    // take n channels of calibrated data off the end of the string
    for(int i = n-1;i>=0;i--){
      s = line.substring(line.lastIndexOf(",")+1);
      cal[i] = s.toFloat();
      line = line.substring(0,line.lastIndexOf(","));
    }

    // take the time since reboot in us off the end of the string
    line = line.substring(0,line.length() - 1);       // drop a digit to fit inside the long int limits
    unsigned ts = (unsigned long) line.toInt() * 10;  // put the digit back on to read rounded down to 10
    
    // report as a check.
    char scratchy[100];
    sprintf(scratchy,"\n%10lu, ",ts);
    for(int i = 0; i < n; i++) sprintf(scratchy,"%s%6u, ",scratchy,(unsigned) cal[i]);
    for(int i = 0; i < nd; i++) sprintf(scratchy,"%s%1u, ",scratchy,(unsigned) digio[i]);
    for(int i = 0; i < n; i++) sprintf(scratchy,"%s%6u, ",scratchy,raw[i]);
    if(connFail == 0) Serial.print(scratchy);
    
    // ditch any leftovers
    while (Serial.available()){ 
      char c = Serial.read();
    }
    reported++;     // some data got reported on the Serial port
  }
  
  data = analogRead(A0);
  if(data != 0){
    float mvData = data /1.056;   // constant is empirically measured
    smoothTemp = smoothTemp *.99 + ((mvData - 500.) / 10.)*.01;
  }
  if (smoothies < 20000) smoothies++;

  // This part should be last in the loop, since it will generate an early return on failure.
  // if( long enough to have valid data && (it has been long enough || this is the first time) ) then log data
  if ( smoothies > 10000 && ((millis() - t > 1000 * 20L) || (t == 0)) ) {
    String url = link + "&field1=" + smoothTemp;
    // report the Serial data if it has been updated a few times since last logging -- ignore plug/unplug
    if(reported > 5) url = url + "&field2=" + (cal[0]/1000) + "&field3=" + (cal[1]/1000)   + "&field4=" + (cal[2]/1000) 
                      + "&field5=" + (1.6 + 0.8 * digio[2])  
                      + "&field6=" + (4.6 + 0.8 * digio[5]) 
                      + "&field7=" + (6.6 + 0.8 * digio[7]);
    WiFiClient client;            // create TCP connection
    if(connFail == 0){ Serial.print("\nOpening connection to: ");  Serial.print(HOST); }
    //delay(5000);                // this delay may let things settle long enough to get a connection first time
    if (!client.connect(HOST, 80)) {    // this connection seems to fail often, except the first try after reboot
      if (connFail == 0) Serial.print(" failed ... ");
      else if(connFail%100 == 0) Serial.print(".");
      connFail++;
      delay(200);             // don't retry immediately -- avoid flooding net connection and ESP exception 9
      if(connFail > 100){     // redo from start if it has taken too long
        Serial.print("Making a clean start of it\n\n");
        WiFi.disconnect();
        delay(1000);
        setup();
        connFail = 0;
      }
      return;       // don't even bother with the GET
    }
    // send GET request to the server, read reply and print it
    Serial.print(" success after "); Serial.print(connFail); Serial.print(" retries!\nRequesting URL: ");
    connFail = 0;
    Serial.print(url); Serial.print(" ... ");
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + HOST + "\r\n" + "Connection: close\r\n\r\n");
    reported = 0;       // the data just got logged
    // wait up to 1000 ms to hear back from the server, then move on
    for(unsigned long waiting = millis(); !client.available() && millis()-waiting < 1000;);
    //while (client.available()) {      // uncomment the while if you want more than just one line
      String line = client.readStringUntil('\r');
      Serial.print(line);
    //}
    t = millis();
  }

}

Wednesday, 28 October 2015

Serial Buffer Sizes on Arduino

Often you want to leave the serial port alone to send or receive data under interrupts while the main loop of the code wanders off to do other things. If you don't get back often enough, the buffer may overflow. The standard buffer size in the Arduino IDE is 64 bytes (or only 16 for really small RAM boards). The code is in arduino/avr/cores/arduino/HardwareSerial.h and looks something like this:

#if !defined(SERIAL_TX_BUFFER_SIZE)
#if (RAMEND < 1000)
#define SERIAL_TX_BUFFER_SIZE 16
#else
#define SERIAL_TX_BUFFER_SIZE 64
#endif
#endif

Altering that code to something like this can get you some more buffer space on larger processors.

#if !defined(SERIAL_RX_BUFFER_SIZE)
#if (RAMEND < 1000)
#define SERIAL_RX_BUFFER_SIZE 16
#else
// this test will create a large buffer on anything big
#if (RAMEND > 2200)
#define SERIAL_RX_BUFFER_SIZE 512
#else
#define SERIAL_RX_BUFFER_SIZE 64
#endif
#endif
#endif

The downside of this is you will probably lose your mods when you next upgrade the IDE, and they won't move with your sketch code if you take it to another platform. I would like to be able to include these defines in my sketch, but I'm not sure how to get them snuck in at the right point in the build process.

Also, this file change won't translate to other processors that install their own code under the IDE, like the Teensy family. Paul Stoffregen has kept all his defines in the individual c code files like teensy/avr/cores/teensy3/serial1.c, where changing these should let you increase the size as needed:

////////////////////////////////////////////////////////////////
// Tunable parameters (relatively safe to edit these numbers)
////////////////////////////////////////////////////////////////

#define TX_BUFFER_SIZE 64 // number of outgoing bytes to buffer
#define RX_BUFFER_SIZE 64 // number of incoming bytes to buffer

I saw a note somewhere recommending power of two buffer sizes for efficiency in index arithmetic, and I can't really imagine going anything other than 64, 128, 256, 512, etc. anyway. In my current application I'm expecting to get packets of around 250 bytes back on request, so I will set the RX buffer size to 512 to be sure it's big enough to catch the whole packet. The request code is short, so I won't increase the size of the TX buffer.


Wednesday, 10 December 2014

Python Plots from Serial Input

The Arduino IDE doesn't do much with serial data returned from the board, other than display it on the serial console. Python provides a platform independent way to listen to your Arduino and draw graphs of analog data, or whatever you want. The code below provides a stripchart display based on the assumption that lines of

millis(), A0, A1, A2, A3, A4, A5

format are coming back from the Arduino on the serial port. It's hardcoded with port and speed, but easy to edit. I think the indents are OK, but this blog platform strips out the tabs on pasting...

Update: I did all of this with an arduino micro. Like the Leonardo, it doesn't reboot when you re-initialize the USB. When I switched to the UNO with the same code, I had to adjust it so it waited and read a few more lines before acting on the data. If you don't want to disrupt the UNO, you probably need to make a direct RS232 connection through an FTDI cable, rather than the onboard USB.



import matplotlib.pyplot as plt
import time
import serial

plt.ion()
ser = serial.Serial('/dev/tty.usbmodemfd1471',57600,timeout=1)
line = ser.readline() # throw away any part lines
while(ser.inWaiting() < 100): # make sure something is coming
  now = 0.0
t=[] # initialize the data lists
d1=[]
d2=[]
d3=[]
d4=[]
d5=[]
d6=[]
while (ser.isOpen()):
  line = ser.readline() # read a line of text
  mylist = line.split(",") # parse it into CSV tokens
  #print mylist
  now = float(mylist[0])/1000 # time now in seconds
  t.append(float(mylist[0])/1000) # from first element as milliseconds
  d1.append(float(mylist[1])) # six data elements added to lists
  d2.append(float(mylist[2]))
  d3.append(float(mylist[3]))
  d4.append(float(mylist[4]))
  d5.append(float(mylist[5]))
  d6.append(float(mylist[6]))
  if(ser.inWaiting() < 100): # redraw only if you are caught up
    plt.clf() # clear the figure
    plt.plot(t,d1) # plot a line for each set of data
    plt.plot(t,d2)
    plt.plot(t,d3)
    plt.plot(t,d4)
    plt.plot(t,d5)
    plt.plot(t,d6)
    plt.axis([now-60,now,min(d1)-50,max(d1)+50])
    plt.xlabel("Time Since Boot [s]")
    plt.draw()

By request, here's the arduino code I was running, which does a bunch more than just print analog values

//// AvgDAQ
// Makes the potentially dangerous assumption that the analog pins are numbered in sequence, starting at A0

//// Constants
int d = 1;
int navg = 10;
int nan = 6;
int nrpt = 500;
int ndisp = 20000;

void setup() {
  for(int i = 0; i < nan; i++) pinMode(A0 + i, INPUT);
  Serial.begin(57600);   
  analogReference(INTERNAL);  // 2.56 volts on the YUN, 1.1 on UNO
  //analogReference(EXTERNAL);  // based on the input to AREF
  Serial.print("\n\nAvgDAQ\n");
}

void loop() {
  static int linesShown = 0;
  unsigned long sums[10];    // doesn't want to work with NAN as a dimension
  getAvgDAQ(sums);
  if(linesShown < ndisp){ 
    showSums(sums);
    linesShown++;
  }
  while(millis()%nrpt);
}

void getAvgDAQ(unsigned long *sums) {
  sums[nan] = (unsigned long) millis();
  for(int i = 0;i < nan;i++) sums[i] = 0;
  for(int i = 0;i < navg;i++) for(int j = 0;j < nan;j++){ 
    sums[j] += analogRead(A0+j); 
    delayMicroseconds(d);
  }
  for(int i=0;i < nan;i++){ 
    //sums[i] *= 1404;  //convert to mv for 1.404 V AREF
    //sums[i] *= 2560;  //convert to mv for 2.56 V internal ref
    sums[i] *= 1100;    //convert to mv for 1.10 V internal ref
    sums[i] /= 1024;
    sums[i] /= navg;    // average over NAVG samples
  }
}

void showSums(unsigned long *sums) {
  char scratch[80];
  
  Serial.print(sums[nan]);
  scratch[0]=0;    // when in doubt code dangerously, writing a string over itself ;-)
  for(int i = 0;i < nan;i++) sprintf(scratch,"%s, %5d",scratch,(int) sums[i]);
  sprintf(scratch,"%s,   *",scratch);
  Serial.print(scratch);
  for(int i=0;i<80;i++) scratch[i] = '.';
  scratch[79] = 0;
  for(int i=0;i<nan;i++){
    long j = sums[i] / 20;
    if(j > 78) j = 78;
    scratch[j] = '0'+i;
  }
  Serial.println(scratch);
}

and of course to get all of this to run, you need to have pyserial and matplotlib installed. On a mac you can try

sudo easy_install pip
sudo pip install pyserial
sudo pip install matplotlib

Saturday, 15 November 2014

Bigger Hammer!

I read a couple of things online that made oblique references to inverting signals, then decided I wanted to invert a TTL signal, despite having no inverter chips lying around, so... this code allows an Arduino to emulate an inverter that could be made from a couple of resistors and a transistor:

void setup(){
  pinMode(7,INPUT);
  pinMode(8,OUTPUT);
}

void loop(){
  if(digitalRead(7) == HIGH) digitalWrite(8, LOW);
  else digitalWrite(8,HIGH);
}

which in turn allowed me to successfully read the NMEA data from my antique Standard Horizon CP150C chart plotter. The plotter provides 2 wire connection for the serial NMEA sentences it shares with the world, but for some unknown reason related to RS232 and RS 422 and NMEA, the data is inverted, 5 volts when the listener expects 0 and 0 when the listener expects 5. Suddenly, by magic, I get

$GPGLL,,,,,215457,V*06

instead of

..\%........3g..*.N.Y..L.=..\%........3ge.>>N.Y....=..\%....

and that GLL sentence would have a whole lot more position data between those commas if the antenna could just see a few satellites from here in the workshop.
$GPGLL,4413.734,N,07629.154,W,221318,A*3B
I hope the next person who googles for

CP150C NMEA to RS232 serial

finds this page to answer their question quickly.

Tuesday, 11 February 2014

Sleepy Wireless Temperature Sender

It would be nice to know the temperature in the greenhouses at Made in the Shade without having to be there. The obvious first solution step is a commercial remote monitor, good enough to read 300 ft away, which just manages to display temperatures from 3 different greenhouses on an LCD display if the base station is by the back window of the house. It doesn't do much good if you are off the property, and doesn't have an obvious way to hijack the readings from the base station. To get them off the property, we'll have to reacquire the temperature signals, preferably with a battery powered wireless gadget. The obvious solution is some kind of Arduino / XBee combination, except an UNO with an XBee attached consumes about 100 mA and would burn through an AA battery pack in a day or less.

Low Power Means Putting Things to Sleep!


Plugged in a new XBee on the FTDI cable and couldn't remember the right terminal settings (9600, Raw, Echo,  then +++ with no return should get an OK.) I used ATID2711, ATMY0, ATDL1, ATBD6 to match the one at the sailboat end of the IOM controller so the TX can listen to either one at 57600 baud. Don't forget the ATWR to write it all out! Upgraded the IOM TX program to echo any serial it gets back on the XBee to the console.

Now to get a trinket talking to the XBee... I couldn't get software serial to work reliably on the trinket at 57600, so backed all the XBees down to 19200. I created SleepyTrinket based on the code from Nathan Seidle at  https://github.com/sparkfun/H2OhNo/tree/master/firmware/WatchDogTest. That code uses pins 3 and 4 for the software serial, but I switched it to 0 and 1, then used pin 2 for the XBee sleep line, which leaves 3 (A3) and 4 (A2) for something analog useful. I cut the current draw on the trinket by 3 mA by breaking off the green power LED. The XBee sleeps when pin 9 is set high if sleep mode is enabled (ATSM1 for hibernate or ATSM2 for doze, plus ATWR).

I first powered the Trinket and the XBee directly on the 3V line from a 3.7 V 100 mAh LiPo, hoping to bypass any regulator losse, but that worried me a little so I switched to the regulated battery input. Either way, with everything awake it used about 60 mA and with everything asleep that fell to about 40 uA! That's about 1 mAh per day while sleeping and 1 mAh per minute while awake.

How quickly can I wake everything up, spit out a serial burst and go back to sleep? It works with delays in the code of 1 s, 500 ms, 100 ms, so 50 ms is probably fast enough with a total time around 200 ms per burst. To split the power consumption between awake and asleep would mean reporting about 300 times a day or about once every 5 seconds.

When I enabled the ADC and started reading a TMP 36 the sleep load came up to about 270 uA, or about 6 mAh per day, which would still get months on a 1300 mAh battery. Still, enabling and disabling the ADC each cycle brings the sleep load back down to about 60 uA. Better stability for the TMP 36 comes from a 2 M resistor and a 104 ceramic cap bridging the signal pin to ground. Based on these measurements, the little 500 mAh LiPo in the background should be good for more than 6 months between recharges. The next step is a little tidier packaging and something at the house end that will listen, repeat the data out to the world, and maybe send an SMS if alarm conditions come up.

A little more testing shows that the accuracy of the temperature measurements from this combo are a little dodgy, so time to track down where the error comes from. (Yes I know that the TMP36 spec says +-2C, but I want better ;-) )



/*
Use with Adafruit Trinket 3V - remove green power LED - compile as trinket 8MHz

about 6 mA awake and 25 uA asleep, 10 mA if the LED is turned on for just the trinket

sleep current goes up to about 1 mA if connected to FTDI cable

2014-02-11
Rick Sellens adapted from:

 1-14-2013
 Spark Fun Electronics
 Nathan Seidle

 This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
 https://github.com/sparkfun/H2OhNo/tree/master/firmware/WatchDogTest
*/
#define TRX 1      // Trinket RX pin
#define TTX 0      // Trinket TX pin
#define XBS 2      // XBee sleep pin
#define BLNK 1     // Blinking LED pin
#define TMP 2      // Analog pin number for TMP 36

#define WT 50

#include <avr/sleep.h> //Needed for sleep_mode

#include <SoftwareSerial.h>

SoftwareSerial mySerial(1, 0); // RX, TX

volatile int watchdog_counter;

//This runs each time the watch dog wakes us up from sleep
ISR(WDT_vect) {
  watchdog_counter++;
}

void setup()
{
  digitalWrite(XBS,LOW);  // start with the XBee awake
  delay(WT);
  mySerial.begin(19200);    // flaky at 57600, but seems OK at 9600, 19200, 38400
  delay(WT);
  mySerial.println("\n\nRWS Sleeper");
  pinMode(XBS,OUTPUT);
  pinMode(BLNK,OUTPUT);
  delay(WT);
  
  watchdog_counter = 0;

  //Power down various bits of hardware to lower power usage  
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); //Power down everything, wake up from WDT
  sleep_enable();
  ADCSRA |= (1<<ADEN);    //Enable ADC, costs ~230uA
  ADCSRA &= ~(1<<ADEN);   //Disable ADC, saves ~230uA
  
  setup_watchdog(6); //Wake up after 1 sec (6)
}

void loop() {
  static int rdg = 0;
  static int n = 0;
  
  digitalWrite(XBS,HIGH);  // sleep the XBee
  sleep_mode();            // sleep the trinket

  if(watchdog_counter > 0){
    // trinket awake, so take a reading
    ADCSRA |= (1<<ADEN);    //Enable ADC, costs ~230uA
    delay(WT);
    rdg += analogRead(TMP);
    n++;
    ADCSRA &= ~(1<<ADEN);   //Disable ADC, saves ~230uA

    if(watchdog_counter > 9){         // wake the XBee every 10 counts
      digitalWrite(BLNK,HIGH);        // LED on  
      digitalWrite(XBS,LOW);          // wake the XBee
      delay(WT);
      mySerial.print("Awakened... ");
      delay(WT);
      digitalWrite(BLNK,LOW);        // LED off
      long int itemp = rdg;          // temperature in tenths of a degree C
      itemp = (itemp * 3300 / 1024) / n - 500;
      mySerial.print(itemp);
      mySerial.println(" tenths of a degree C.     ZZZ...");
      delay(WT);
      // rest the accumulator and counters
      watchdog_counter = 0;
      rdg = 0;
      n = 0;
    }
  }
}


// 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
// 6=1sec, 7=2sec, 8=4sec, 9=8sec
// From: http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void setup_watchdog(int timerPrescaler) {
  if (timerPrescaler > 9 ) timerPrescaler = 9; //Correct incoming amount if need be
  byte bb = timerPrescaler & 7; 
  if (timerPrescaler > 7) bb |= (1<<5);        //Set the special 5th bit if necessary

  //This order of commands is important and cannot be combined
  MCUSR &= ~(1<<WDRF);                   //Clear the watch dog reset
  WDTCR |= (1<<WDCE) | (1<<WDE);         //Set WD_change enable, set WD enable
  WDTCR = bb;                            //Set new watchdog timeout value
  WDTCR |= _BV(WDIE);                    //Set the interrupt enable, this will keep unit from resetting after each int
}

Thursday, 6 February 2014

Next Steps: Arduino Workshop 2

In this second workshop you will: 
  • select a transducer to measure something physical like temperature or illumination
  • download and install libraries to support components
  • connect neopixel smart RGB LEDs to your Arduino and change their colour and intensity under program control (some soldering required)
  • Use the neopixels to respond to the measured quantity, and more as time permits

or so I promised in the advertising. The simplest way to get some data would be following this lesson with a photocell. (Ignore all the parts about the LEDs for now and just make sure you can read an analog value that changes with the light. Take note of the extremes values for bright and dark. You can adapt the code at the bottom of this post.)

Adafruit NeoPixels are smart RGB LEDs that let you control a whole lot of LEDs with a single data line from the Arduino, and you don't have to worry about all those little current limiting resistors (although, if you are playing with more than a couple of neopixels, you should pay close attention to the capacitor and power supply comments in the uberguide). The complicated part is you need to control that one data line in a fairly complicated way. Fortunately somebody else has already done the work and there is a software library to make it easy. Download the zip file of the library and expand it, then install it in the libraries folder of the Arduino IDE. (You may have to create the libraries folder -- it goes in the same place as your Arduino sketchbook folder.) 

Be sure to remove the "-master" from the library folder name so it matches the name of the library. Then restart the Arduino IDE so it can find the library.

Put together a string of 2 or more NeoPixels (this will probably involve some soldering, either for the Flora or Breadboard versions), then hook them up to +5, Ground and pin 6 for a signal. Open the "strandtest" example in the NeoPixel library and set the number of NeoPixels you have in this line:
Adafruit_NeoPixel strip = Adafruit_NeoPixel(2, PIN, NEO_GRB + NEO_KHZ800);
When you run it you should see the pixels continuously changing colour and intensity independently of each other.

Modify the code to have the pixels respond to the analog input reading from from the photocell.


Other Sensors and Responses

You could measure temperature, or temperature and humidity, or colour, or orientation, with one of these sensors and use that measurement to control the colours and intensity of the NeoPixels. Download and install the library for your sensor, test that you can read it with the example programs, then combine the code from multiple examples to read the sensor, then control the NeoPixels based on what you read.

Take it further and get your sensor inputs to control a servo-motor, maybe opening and closing a greenhouse vent in response to changes in temperature or humidity.

Coding Hints

Pick one of the examples as your starting place and save it with a new name so you don't break the example.

Copy the header code from the top of all the files with the #include and variable declarations.

Copy any functions other than setup() and loop()

Copy and paste code from each of the setup() functions to make sure everything gets started properly.

Copy and paste code from the loop() functions to do the individual things you want.

This code will read analog values and report them:

//// ArduinoDAQ
// Kevin Hughes 2012
// Modified Rick Sellens July 2013

//// Constants
int d = 1;

void setup() {
  
  // All pins to input
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  pinMode(A4, INPUT);
  pinMode(A5, INPUT);
  
  // Init Serial
  Serial.begin(57600);      // 57600 is highest I can sustain over X-Bee and FTDI
  
}// end setup

void loop() {
  
      //start line with time in ms, number of channels, full scale, then the values 
      Serial.print( millis() );          Serial.print(", 6, 1023, ");
      Serial.print( analogRead(A0) );    Serial.print(", ");
      Serial.print( analogRead(A0) );    Serial.print(", ");
      Serial.print( analogRead(A1) );    Serial.print(", ");
      Serial.print( analogRead(A2) );    Serial.print(", ");
      Serial.print( analogRead(A3) );    Serial.print(", ");
      Serial.print( analogRead(A4) );    Serial.print(", ");
      Serial.println( analogRead(A5) );
      while(millis()%100 != 0);            // repeat every 100 ms      

}