Permalink
Browse files

first commit

  • Loading branch information...
1 parent 373021c commit dca775ff634a25b99173c72622daaef65279a939 @ejgertz committed Sep 17, 2011
View
143 chapter-3/4Char
@@ -0,0 +1,143 @@
+/*
+ 4Char Test
+ Sketch in Programming to test a scrolling 4-character display.
+ This example code is in the public domain.
+*/
+
+#include <SoftwareSerial.h>[a]
+#define SerialIn 2
+#define SerialOut 3[b]
+#define 4Delay 600
+
+
+SoftwareSerial mySerialPort(SerialIn, SerialOut);[c]
+
+
+void setup()
+{
+pinMode(SerialOut, OUTPUT);
+pinMode(SerialIn, INPUT);[d]
+
+
+mySerialPort.begin(9600);
+mySerialPort.print("v");[e]
+
+
+
+
+}
+
+
+void loop()
+{
+
+
+mySerialPort.print("xxxx")[f];
+delay(4Delay);
+mySerialPort.print("xxx1");
+delay(4Delay);
+mySerialPort.print("xx12");
+delay(4Delay);
+mySerialPort.print("x123");
+delay(4Delay);
+
+
+mySerialPort.print("1234"[g])[h];
+delay(4Delay);
+
+
+mySerialPort.print("2345");
+delay(4Delay);
+
+
+mySerialPort.print("3456");
+delay(4Delay);
+mySerialPort.print("4567");
+delay(4Delay);
+mySerialPort.print("5678");
+delay(4Delay);
+ mySerialPort.print("6789");
+delay(4Delay);
+mySerialPort.print("7890");
+delay(4Delay);
+mySerialPort.print("8900");
+delay(4Delay);
+mySerialPort.print("9000");
+delay(4Delay);
+mySerialPort.print("0000");
+delay(4Delay);
+
+
+for (int i = 0; i <250; i++)
+ {
+ mySerialPort.print(0x77);
+ mySerialPort.print(itoa(i,););
+ }
+
+
+
+
+mySerialPort.print("----");
+delay(4Delay);
+mySerialPort.print("8888");
+delay(4Delay);
+
+
+mySerialPort.print("----");
+delay(4Delay);
+mySerialPort.print("xxxx");
+delay(4Delay);
+
+
+mySerialPort.print("xxxH");
+delay(4Delay);
+mySerialPort.print("xxHE");
+delay(4Delay);
+mySerialPort.print("xHEL")[i];
+delay(4Delay);
+
+
+
+
+mySerialPort.print("HELL");
+delay(4Delay);
+
+
+mySerialPort.print("ELLO");
+delay(4Delay);
+ mySerialPort.print("LLOx");
+delay(4Delay);
+
+
+
+
+
+
+mySerialPort.print("LOxt");
+delay(4Delay);
+mySerialPort.print("Lxth");
+delay(4Delay);
+mySerialPort.print("xthE");
+delay(4Delay);
+mySerialPort.print("thEr");
+delay(4Delay);
+
+
+mySerialPort.print("hErE");
+delay(4Delay);
+mySerialPort.print("ErEx");
+delay(4Delay);
+mySerialPort.print("rExx");
+delay(4Delay);
+mySerialPort.print("Exxx");
+delay(4Delay);
+mySerialPort.print("xxxx");[j]
+delay(4Delay);
+
+
+delay(4Delay);
+delay(4Delay);
+delay(4Delay);
+
+
+}
View
238 chapter-4/EMFDetector
@@ -0,0 +1,238 @@
+// Arduino Electromagnetic Interference Detector
+// Code modified by Patrick Di Justo, based on
+// Aaron ALAI EMF Detector April 22nd 2009 VERSION 1.0
+// aaronalai1@gmail.com
+
+
+int inPin = 5;
+int val = 0;
+
+
+void setup()
+{
+ // So simple there's nothing to set up!
+}
+
+void loop()
+{
+
+ val = analogRead(inPin);
+
+ Serial.println(val);
+ val = map(val, 1, 100, 1, 2048);
+ tone(9,val,10);
+
+}
+
+If you want to get a more precise type of reading, make this simple change to the circuit at Step 6: Connect GND pin on the 4char to Arduino GND, and RX pin to Arduino digital pin 8
+
+
+And load the following code:
+// Arduino Electromagnetic interference detector
+// Code modified by PAtrick Di Justo, based on
+// Aaron ALAI EMF Detector April 22nd 2009 VERSION 1.0
+// aaronalai1@gmail.com
+
+
+#include <SoftwareSerial.h>
+#define SerialIn 2
+#define SerialOut 7
+
+
+#define wDelay 900
+
+
+byte thou=0;
+byte hund=0;
+byte tens=0;
+byte ones=0;
+
+
+int inPin = 5;
+int val = 0;
+
+SoftwareSerial mySerialPort(SerialIn, SerialOut);
+
+
+void setup()
+{
+
+
+ pinMode(SerialOut, OUTPUT);
+ pinMode(SerialIn, INPUT);
+
+
+ mySerialPort.begin(19200);
+ mySerialPort.print("vv");
+
+
+
+
+ mySerialPort.print("xxxx");
+ delay(wDelay);
+ mySerialPort.print("----");
+ delay(wDelay);
+ mySerialPort.print("8888");
+ delay(wDelay);
+ mySerialPort.print("xxxx");
+ delay(wDelay);
+
+
+
+
+ Serial.begin(9600);
+
+}
+
+
+void loop()
+{
+
+ val = analogRead(inPin);
+
+ Serial.println(val);
+ dispData(val);
+ val = map(val, 1, 100, 1, 2048);
+ tone(9,val,10);
+
+}
+
+
+
+
+void dispData(int i)
+{
+
+
+ char c = ' ';
+
+ ones=0;
+ tens=0;
+ hund=0;
+ thou=0;
+
+
+
+if((i<-999) || (i>9999))
+ {
+ mySerialPort.print("ERRx");
+ return;
+ }
+
+
+mySerialPort.print("w");
+
+ int sign = i;
+ i = abs(i);
+
+ ones = i%10;
+ if(i>=10) tens = ((i%100)-ones)/10;
+ if(i>=100) hund = ((i%1000)-(tens*10)-ones)/100;
+ if(i>=1000) thou = ((i%10000)-(hund*100)-(tens*10)-ones)/1000;
+
+
+
+
+ if (thou>0)
+ {
+ mySerialPort.print(thou);
+ mySerialPort.print(hund);
+ mySerialPort.print(tens);
+ mySerialPort.print(ones);
+ return;
+ }
+
+
+ if ((hund>0)&& (sign<0))
+ {
+ mySerialPort.print("-");
+ mySerialPort.print(hund);
+ mySerialPort.print(tens);
+ mySerialPort.print(ones);
+ Serial.print((int)hund);
+ Serial.print((int)tens);
+ Serial.print((int)ones);
+ Serial.print(c);
+ return;
+ }
+
+
+
+ if (hund>0)
+ {
+ mySerialPort.print(hund);
+ mySerialPort.print(tens);
+ mySerialPort.print(ones);
+ mySerialPort.print(c);
+ Serial.print((int)hund);
+ Serial.print((int)tens);
+ Serial.print((int)ones);
+ Serial.print(c);
+ return;
+ }
+
+
+ if ((tens>0) && (sign<0))
+ {
+ mySerialPort.print("-");
+ mySerialPort.print(tens);
+ mySerialPort.print(ones);
+ mySerialPort.print(c);
+ Serial.print("-");
+ Serial.print((int)tens);
+ Serial.print((int)ones);
+ Serial.print(c);
+
+
+
+
+ return;
+ }
+
+
+ if (tens>0)
+ {
+ mySerialPort.print(tens);
+ mySerialPort.print(ones);
+ mySerialPort.print("x");
+ mySerialPort.print(c);
+ Serial.print((int)tens);
+ Serial.print((int)ones);
+ Serial.print("x");
+ Serial.print(c);
+
+
+
+
+ return;
+ }
+
+
+ if((ones>0) && (sign<0))
+ {
+ mySerialPort.print("-");
+ mySerialPort.print(ones);
+ mySerialPort.print("x");
+ mySerialPort.print(c);
+ Serial.print("-");
+ Serial.print((int)ones);
+ Serial.print("x");
+ Serial.print(c);
+ return;
+ }
+
+
+
+ if(ones>0)
+ {
+ mySerialPort.print("x");
+ mySerialPort.print(ones);
+ mySerialPort.print("x");
+ mySerialPort.print(c);
+ Serial.print("x");
+ Serial.print((int)ones);
+ Serial.print("x");
+ Serial.print(c);
+ return;
+ }
+}
View
69 chapter-5/WaterConductivity
@@ -0,0 +1,69 @@
+/*
+ Water Conductivity Monitor
+ Sketch for an Arduino gadget that measures the electrical conductivity of water.
+ This example code is in the public domain.
+*/
+
+const float ArduinoVoltage = 5.00; // CHANGE THIS FOR 3.3v Arduinos
+
+
+const float ArduinoResolution = ArduinoVoltage / 1024;
+
+
+const float resistorValue = 10000.0;
+int threshold = 3;
+
+
+int inputPin = A0;
+int ouputPin = A5;
+
+void setup()
+{
+Serial.begin(9600);
+pinMode(ouputPin, OUTPUT);
+pinMode(inputPin, INPUT);
+}
+
+void loop()
+{
+int analogValue=0;
+int oldAnalogValue=1000;
+float returnVoltage=0.0;
+float resistance=0.0;
+double Siemens;
+float TDS=0.0;
+
+while(((oldAnalogValue-analogValue)>threshold) || (oldAnalogValue<50))
+{
+ oldAnalogValue = analogValue;
+ digitalWrite( ouputPin, HIGH );
+ delay(10); // allow ringing to stop
+ analogValue = analogRead( inputPin );
+ digitalWrite( ouputPin, LOW );
+}
+
+Serial.print("Return voltage = ");
+returnVoltage = analogValue *ArduinoResolution;
+Serial.print(returnVoltage);
+Serial.println(" volts");
+
+
+Serial.print("That works out to a resistance of ");
+resistance = ((5.00 * resistorValue) / returnVoltage) - resistorValue;
+Serial.print(resistance);
+Serial.println(" Ohms.");
+
+
+Serial.print("Which works out to a conductivity of ");
+Siemens = 1.0/(resistance/1000000);
+Serial.print(Siemens);
+Serial.println(" microSiemens.");
+Serial.print("We can estimate Total Dissolved Solids to be on the order of ");
+TDS = 500 * (Siemens/1000);
+Serial.print(TDS);
+Serial.println(" PPM.");
+if(returnVoltage>4.9) Serial.println("Are you sure this isn't metal?");
+
+
+delay(5000);
+}
View
80 chapter-6/SDCardReadWrite
@@ -0,0 +1,80 @@
+/*
+ SD Card Read/Write
+
+ This example shows how to read and write data to and from an SD card file
+ The circuit:
+ * SD card attached to SPI bus as follows:
+ ** MOSI - pin 11
+ ** MISO - pin 12
+ ** CLK - pin 13
+ ** CS - pin 4
+
+ created Nov 2010
+ by David A. Mellis
+ updated 2 Dec 2010
+ by Tom Igoe
+
+ This example code is in the public domain.
+
+ */
+
+#include <SD.h>
+
+
+File myFile;
+
+
+void setup()
+{
+ Serial.begin(9600);
+ Serial.print("Initializing SD card...");
+ // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
+ // Note that even if it's not used as the CS pin, the hardware SS pin
+ // (10 on most Arduino boards, 53 on the Mega) must be left as an output
+ // or the SD library functions will not work.
+ pinMode(10, OUTPUT);
+
+ if (!SD.begin(4)) {
+ Serial.println("initialization failed!");
+ return;
+ }
+ Serial.println("initialization done.");
+
+ // open the file. note that only one file can be open at a time,
+ // so you have to close this one before opening another.
+ myFile = SD.open("test.txt", FILE_WRITE);
+
+ // if the file opened okay, write to it:
+ if (myFile) {
+ Serial.print("Writing to test.txt...");
+ myFile.println("testing 1, 2, 3.");
+ // close the file:
+ myFile.close();
+ Serial.println("done.");
+ } else {
+ // if the file didn't open, print an error:
+ Serial.println("error opening test.txt");
+ }
+
+ // re-open the file for reading:
+ myFile = SD.open("test.txt");
+ if (myFile) {
+ Serial.println("test.txt:");
+
+ // read from the file until there's nothing else in it:
+ while (myFile.available()) {
+ Serial.write(myFile.read());
+ }
+ // close the file:
+ myFile.close();
+ } else {
+ // if the file didn't open, print an error:
+ Serial.println("error opening test.txt");
+ }
+}
+
+
+void loop()
+{
+ // nothing happens after setup
+}
View
88 chapter-6/WebServer
@@ -0,0 +1,88 @@
+/*
+ Web Server
+
+ A simple web server that shows the value of the analog input pins.
+ using an Arduino Wiznet Ethernet shield.
+
+ Circuit:
+ * Ethernet shield attached to pins 10, 11, 12, 13
+ * Analog inputs attached to pins A0 through A5 (optional)
+
+ created 18 Dec 2009
+ by David A. Mellis
+ modified 4 Sep 2010
+ by Tom Igoe
+
+ */
+
+
+#include <SPI.h>
+#include <Ethernet.h>
+
+
+// Enter a MAC address and IP address for your controller below.
+// The IP address will be dependent on your local network:
+byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };[a]
+byte ip[] = { 192,168,1, 177 };[b]
+
+
+// Initialize the Ethernet server library
+// with the IP address and port you want to use
+// (port 80 is default for HTTP):
+Server server(80);
+
+
+void setup()
+{
+ // start the Ethernet connection and the server:
+ Ethernet.begin(mac, ip);
+ server.begin();
+}
+
+
+void loop()
+{
+ // listen for incoming clients
+ Client client = server.available();
+ if (client) {
+ // an http request ends with a blank line
+ boolean currentLineIsBlank = true;
+ while (client.connected()) {
+ if (client.available()) {
+ char c = client.read();
+ // if you've gotten to the end of the line (received a newline
+ // character) and the line is blank, the http request has ended,
+ // so you can send a reply
+ if (c == '\n' && currentLineIsBlank) {
+ // send a standard http response header
+ client.println("HTTP/1.1 200 OK");
+ client.println("Content-Type: text/html");
+ client.println();
+
+
+ // output the value of each analog input pin
+ for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
+ client.print("analog input ");
+ client.print(analogChannel);
+ client.print(" is ");
+ client.print(analogRead(analogChannel));
+ client.println("<br />");
+ }
+ break;
+ }
+ if (c == '\n') {
+ // you're starting a new line
+ currentLineIsBlank = true;
+ }
+ else if (c != '\r') {
+ // you've gotten a character on the current line
+ currentLineIsBlank = false;
+ }
+ }
+ }
+ // give the web browser time to receive the data
+ delay(1);
+ // close the connection:
+ client.stop();
+ }
+}
View
76 chapter-7/TempSketchSnippets
@@ -0,0 +1,76 @@
+/* The following code snippets should be added
+to SDCardReadWrite, in order to store temperature data the SD card.
+*/
+
+//Add the following line to the very top of the sketch.
+//This adds the set of library functions that tell
+// Arduino how to talk to the SD card.
+
+
+#include<SD.h>
+
+
+
+
+//Add the following lines to the bottom of the
+//_setup( )_ function in the sketch:
+
+Serial.print("Initializing SD card...");
+ // make sure that the default chip select pin is set to
+ // output, even if you don't use it:
+ pinMode(10, OUTPUT);
+
+
+ // see if the card is present and can be initialized:
+ if (!SD.begin(chipSelect)) {
+ Serial.println("Card failed, or not present");
+ // don't do anything more:
+ return;
+ }
+ Serial.println("card initialized.");
+
+
+
+//Add the following lines at the bottom of the _loop( )_ function:
+
+ String dataString = "";
+ dataString = String(millis());
+ dataString += " Temperature: ";
+ dataString += String((int)temperature);
+ dataString +=" degrees C Humidity: ";
+ dataString += String((int)humidity);
+ dataString +=" %";
+
+ Serial.println(dataString);
+
+ writeDataToSD(dataString);
+
+// Add the following function to the bottom of the sketch:
+
+
+void writeDataToSD(String dataString)
+{
+
+
+ // open the file. note that only one file can be open at a time,
+ // so you have to close this one before opening another.
+ Serial.print("opeining file...");
+ File dataFile = SD.open("datalog.txt", FILE_WRITE);
+
+
+ Serial.print("file open...");
+
+
+ // if the file is available, write to it:
+ if (dataFile) {
+ dataFile.println(dataString);
+ dataFile.close();
+ // print to the serial port too:
+ Serial.println(dataString);
+ }
+ // if the file isn't open, pop up an error:
+ else {
+ Serial.println("error opening datalog.txt");
+ }
+}
+
View
79 chapter-7/WebPageSketchSnippets
@@ -0,0 +1,79 @@
+/* Make a Temperature/Humidity Web Page */
+
+//Add the following code snippets should be added
+// to your basic temperature/humidity sketch:
+
+----
+#include <Ethernet.h>
+// the sensor communicates using SPI, so include the library:
+#include <SPI.h>
+
+
+byte mac[] = {0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX};
+// assign an IP address for the controller:
+byte ip[] = { 192,168,1,20 };
+
+
+
+//Insert these lines of code at the top of the _setup()_ function:
+
+
+ Ethernet.begin(mac, ip);
+ server.begin();
+
+
+
+//Add this line of code to the bottom of the loop() function:
+
+
+ listenForClients();
+
+
+//Add the following function to the bottom of the sketch:
+
+
+void listenForClients() {
+ // listen for incoming clients
+ Client client = server.available();
+ if (client) {
+ Serial.println("Got a client");
+ // an http request ends with a blank line
+ boolean currentLineIsBlank = true;
+ while (client.connected()) {
+ if (client.available()) {
+ char c = client.read();
+ // if you've gotten to the end of the line (received a newline
+ // character) and the line is blank, the http request has ended,
+ // so you can send a reply
+ if (c == '\n' && currentLineIsBlank) {
+ // send a standard http response header
+ client.println("HTTP/1.1 200 OK");
+ client.println("Content-Type: text/html");
+ client.println();
+ // print the current readings, in HTML format:
+ client.print("Temperature: ");
+ client.print(temperature);
+ client.print(" degrees C");
+ client.println("<br />");
+ client.print("Humidity: " );
+ client.print(humidity);
+ client.print(" %");
+ client.println("<br />");
+ break;
+ }
+ if (c == '\n') {
+ // you're starting a new line
+ currentLineIsBlank = true;
+ }
+ else if (c != '\r') {
+ // you've gotten a character on the current line
+ currentLineIsBlank = false;
+ }
+ }
+ }
+ // give the web browser time to receive the data
+ delay(1);
+ // close the connection:
+ client.stop();
+ }
+}
View
156 chapter-8/PachubeSensorClient
@@ -0,0 +1,156 @@
+/*
+ Pachube Sensor Client
+
+ This sketch connects an analog sensor to Pachube (http://www.pachube.com)
+ using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
+ the Adafruit Ethernet shield, either one will work, as long as it's got
+ a Wiznet Ethernet module on board.
+
+ Circuit:
+ * Analog sensor attached to analog in 0
+ * Ethernet shield attached to pins 10, 11, 12, 13
+
+ created 15 March 2010
+ updated 4 Sep 2010
+ by Tom Igoe
+
+ http://www.tigoe.net/pcomp/code/category/arduinowiring/873
+ This code is in the public domain.
+
+ */
+
+
+#include <SPI.h>
+#include <Ethernet.h>
+
+
+// assign a MAC address for the ethernet controller.
+// fill in your address here:
+byte mac[] = {
+ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};[a]
+// assign an IP address for the controller:
+byte ip[] = {
+ 192,169,1,20 };
+byte gateway[] = {
+ 192,168,1,1};
+byte subnet[] = {
+ 255, 255, 255, 0 };
+
+
+// The address of the server you want to connect to (pachube.com):
+byte server[] = {
+ 209,40,205,190 };
+
+
+// initialize the library instance:
+Client client(server, 80);
+
+
+long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
+boolean lastConnected = false; // state of the connection last time through the main loop
+const int postingInterval = 10000; //delay between updates to Pachube.com
+
+
+void setup() {
+ // start the ethernet connection and serial port:
+ Ethernet.begin(mac, ip);
+ Serial.begin(9600);
+ // give the ethernet module time to boot up:
+ delay(1000);
+}
+
+
+void loop() {
+ // read the analog sensor:
+ int sensorReading = analogRead(A0);
+
+
+ // if there's incoming data from the net connection.
+ // send it out the serial port. This is for debugging
+ // purposes only:
+ if (client.available()) {
+ char c = client.read();
+ Serial.print(c);
+ }
+
+
+ // if there's no net connection, but there was one last time
+ // through the loop, then stop the client:
+ if (!client.connected() && lastConnected) {
+ Serial.println();
+ Serial.println("disconnecting.");
+ client.stop();
+ }
+
+
+ // if you're not connected, and ten seconds have passed since
+ // your last connection, then connect again and send data:
+ if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
+ sendData(sensorReading);
+ }
+ // store the state of the connection for next time through
+ // the loop:
+ lastConnected = client.connected();
+}
+
+
+// this method makes a HTTP connection to the server:
+void sendData(int thisData) {
+ // if there's a successful connection:
+ if (client.connect()) {
+ Serial.println("connecting...");
+ // send the HTTP PUT request.
+ // fill in your feed address here:
+ client.print("PUT /api/YOUR_FEED_HERE.csv HTTP/1.1\n");[b]
+ client.print("Host: www.pachube.com\n");
+ // fill in your Pachube API key here:
+ client.print("X-PachubeApiKey: YOUR_KEY_HERE\[c]n");
+ client.print("Content-Length: ");
+
+
+ // calculate the length of the sensor reading in bytes:
+ int thisLength = getLength(thisData);
+ client.println(thisLength, DEC);
+
+
+ // last pieces of the HTTP PUT request:
+ client.print("Content-Type: text/csv\n");
+ client.println("Connection: close\n");
+
+
+ // here's the actual content of the PUT request:
+ client.println(thisData, DEC);
+
+
+ // note the time that the connection was made:
+ lastConnectionTime = millis();
+ }
+ else {
+ // if you couldn't make a connection:
+ Serial.println("connection failed");
+ }
+}
+
+
+
+
+// This method calculates the number of digits in the
+// sensor reading. Since each digit of the ASCII decimal
+// representation is a byte, the number of digits equals
+// the number of bytes:
+
+
+int getLength(int someValue) {
+ // there's at least one byte:
+ int digits = 1;
+ // continually divide the value by ten,
+ // adding one to the digit count for each
+ // time you divide, until you're at 0:
+ int dividend = someValue /10;
+ while (dividend > 0) {
+ dividend = dividend /10;
+ digits++;
+ }
+ // return the number of digits:
+ return digits;
+}
View
344 chapter-9/radiation-pachube-sketch
@@ -0,0 +1,344 @@
+/* ==============================
+ * This code, which assumes you're using the official Arduino Ethernet shield,
+ * updates a Pachube feed with your analog-in values and grabs values from a Pachube
+ * feed - basically it enables you to have both "local" and "remote" sensors.
+ *
+ * Tested with Arduino 14
+ *
+ * Pachube is www.pachube.com - connect, tag and share real time sensor data
+ * code by usman (www.haque.co.uk), may 2009
+ * copy, distribute, whatever, as you like.
+ *
+ * v1.1 - added User-Agent & fixed HTTP parser for new Pachube headers
+ * and check millis() for when it wraps around
+ *
+ * =============================== */
+
+
+//#include <spi.h>
+#include <Ethernet.h>
+#include <string.h>
+#include <SPI.h> // Add this through the menu -- Sketch | Import Library | SPI
+
+#undef int() // needed by arduino 0011 to allow use of stdio
+#include <stdio.h> // for function sprintf
+
+
+#define SHARE_FEED_ID 34225 // this is your Pachube feed ID that you want to share to
+#define REMOTE_FEED_ID 000 // this is the ID of the remote Pachube feed that you want to connect to
+#define REMOTE_FEED_DATASTREAMS 0 // make sure that remoteSensor array is big enough to fit all the remote data streams
+#define UPDATE_INTERVAL 60000 // if the connection is good wait 10 seconds before updating again - should not be less than 5
+#define RESET_INTERVAL 60000 // if connection fails/resets wait 10 seconds before trying again - should not be less than 5
+
+
+#define PACHUBE_API_KEY "2u6FT54p15flDVlRUCug9ncKcvM8jiVcNQ2THI8gK-Y" // fill in your API key
+
+
+byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x4A, 0xE9 }; // make sure this is unique on your network
+byte ip[] = { 192, 168, 1, 110 };
+byte subnet[] = {255, 255, 254,0};
+byte gateway[]={208,120,198,153 }; // no DHCP so we set our own IP address
+byte remoteServer[] = { 173,203,98,29 }; // pachube.com
+
+
+float remoteSensor[REMOTE_FEED_DATASTREAMS]; // we know that feed 256 has floats - this might need changing for feeds without floats
+
+
+int geiger_input = 2;
+long count = 0;
+long countPerMinute = 0;
+long timePrevious = 0;
+long timePreviousMeassure = 0;
+long time = 0;
+long countPrevious = 0;
+float radiationValue = 0.0;
+
+
+#define CONV_FACTOR 0.0057
+
+
+
+
+void setup()
+{
+ Serial.begin(57600);
+ setupEthernet();
+ pinMode(geiger_input, INPUT);
+ digitalWrite(geiger_input,HIGH);
+
+ attachInterrupt(0,countPulse,FALLING);
+}
+
+
+void loop()
+{
+ if (millis()-timePreviousMeassure > 10000)
+ {
+
+ //count = random(2,200);
+ countPerMinute = count;
+ radiationValue = countPerMinute * CONV_FACTOR;
+ timePreviousMeassure = millis();
+ Serial.print("cpm = ");
+ Serial.print(countPerMinute,DEC);
+ Serial.print(" - ");
+ Serial.print("uSv/h = ");
+ Serial.println(radiationValue,4);
+
+ count = 0;
+
+
+ }
+
+
+ pachube_in_out();
+
+
+
+
+}
+
+
+
+
+void countPulse()
+{
+ detachInterrupt(0);
+ count++;
+ digitalWrite(13,HIGH);
+ while(digitalRead(2)==0){}
+ digitalWrite(13,LOW);
+ attachInterrupt(0,countPulse,FALLING);
+}
+
+
+
+
+Client localClient(remoteServer, 80);
+unsigned int interval;
+
+
+char buff[64];
+int pointer = 0;
+
+
+void setupEthernet(){
+ resetEthernetShield();
+ Client remoteClient(255);
+ delay(500);
+ interval = UPDATE_INTERVAL;
+ Serial.println("setup complete");
+}
+
+
+void clean_buffer() {
+ pointer = 0;
+ memset(buff,0,sizeof(buff));
+}
+
+
+void resetEthernetShield(){
+ Serial.println("reset ethernet");
+ Ethernet.begin(mac, ip, gateway, subnet);
+}
+
+
+char pachube_data[70];
+
+
+boolean found_status_200 = false;
+boolean found_session_id = false;
+boolean found_CSV = false;
+char *found;
+unsigned int successes = 0;
+unsigned int failures = 0;
+boolean ready_to_update = true;
+boolean reading_pachube = false;
+
+
+boolean request_pause = false;
+boolean found_content = false;
+
+
+unsigned long last_connect;
+
+
+int content_length;
+
+
+void pachube_in_out()
+{
+
+
+ if (millis() < last_connect) last_connect = millis();
+
+
+ if (request_pause){
+ if ((millis() - last_connect) > interval){
+ ready_to_update = true;
+ reading_pachube = false;
+ request_pause = false;
+ found_status_200 = false;
+ found_session_id = false;
+ found_CSV = false;
+
+
+ //Serial.print("Ready to connect: ");
+ //Serial.println(millis());
+ }
+ }
+
+
+ if (ready_to_update){
+ Serial.println("Connecting...");
+ if (localClient.connect()) {
+
+
+ // here we assign comma-separated values to 'data', which will update Pachube datastreams
+ // we use all the analog-in values, but could of course use anything else millis(), digital
+ // inputs, etc. . i also like to keep track of successful and failed connection
+ // attempts, sometimes useful for determining whether there are major problems.
+
+
+ sprintf(pachube_data,"%d,%d", countPerMinute, radiationValue);
+ content_length = strlen(pachube_data);
+ Serial.println("We're connected to Pachube!");
+
+
+ localClient.print("PUT /api/");
+ localClient.print(SHARE_FEED_ID);
+ localClient.print(".csv HTTP/1.1\nHost: pachube.com\nX-PachubeApiKey: ");
+ localClient.print(PACHUBE_API_KEY);
+
+
+ localClient.print("\nUser-Agent: Arduino (Pachube In Out v1.1)");
+ localClient.print("\nContent-Type: text/csv\nContent-Length: ");
+ localClient.print(content_length);
+ localClient.print("\nConnection: close\n\n");
+ localClient.print(pachube_data);
+ localClient.print("\n");
+
+ Serial.print("We've sent ");
+ Serial.print(pachube_data);
+ Serial.println("to Pachube.");
+
+
+ ready_to_update = false;
+ reading_pachube = true;
+ request_pause = false;
+ interval = UPDATE_INTERVAL;
+
+
+ // Serial.print("finished PUT: ");
+ // Serial.println(millis());
+
+
+ }
+ else {
+ Serial.print("connection failed!");
+ Serial.print(++failures);
+ found_status_200 = false;
+ found_session_id = false;
+ found_CSV = false;
+ ready_to_update = false;
+ reading_pachube = false;
+ request_pause = true;
+ last_connect = millis();
+ interval = RESET_INTERVAL;
+ setupEthernet();
+ }
+ }
+
+
+ while (reading_pachube){
+ while (localClient.available()) {
+ checkForResponse();
+ }
+
+
+ if (!localClient.connected()) {
+ disconnect_pachube();
+ }
+ }
+}
+
+
+void disconnect_pachube(){
+ Serial.println("disconnecting.\n=====\n\n");
+ localClient.stop();
+ ready_to_update = false;
+ reading_pachube = false;
+ request_pause = true;
+ last_connect = millis();
+ found_content = false;
+ resetEthernetShield();
+}
+
+
+
+
+void checkForResponse(){
+ char c = localClient.read();
+ //Serial.print(c);
+ buff[pointer] = c;
+ if (pointer < 64) pointer++;
+ if (c == '\n') {
+ found = strstr(buff, "200 OK");
+ if (found != 0){
+ found_status_200 = true;
+ //Serial.println("Status 200");
+ }
+ buff[pointer]=0;
+ found_content = true;
+ clean_buffer();
+ }
+
+
+ if ((found_session_id) && (!found_CSV)){
+ found = strstr(buff, "HTTP/1.1");
+ if (found != 0){
+ char csvLine[strlen(buff)-9];
+ strncpy (csvLine,buff,strlen(buff)-9);
+
+
+ //Serial.println("This is the retrieved CSV:");
+ //Serial.println("---");
+ //Serial.println(csvLine);
+ //Serial.println("---");
+ Serial.println("\n--- updated: ");
+ Serial.println(pachube_data);
+ Serial.println("\n--- retrieved: ");
+ char delims[] = ",";
+ char *result = NULL;
+ char * ptr;
+ result = strtok_r( buff, delims, &ptr );
+ int counter = 0;
+ while( result != NULL ) {
+ remoteSensor[counter++] = atof(result);
+ result = strtok_r( NULL, delims, &ptr );
+ }
+ for (int i = 0; i < REMOTE_FEED_DATASTREAMS; i++){
+ Serial.print( (int)remoteSensor[i]); // because we can't print floats
+ Serial.print("\t");
+ }
+
+
+ found_CSV = true;
+
+
+ Serial.print("\nsuccessful updates=");
+ Serial.println(++successes);
+
+
+ }
+ }
+
+
+ if (found_status_200){
+ found = strstr(buff, "_id=");
+ if (found != 0){
+ clean_buffer();
+ found_session_id = true;
+ }
+ }
+}

0 comments on commit dca775f

Please sign in to comment.