Raspberry PI 2 with Windows IOT talking to Arduino Network

This session is the start of a full IOT device. It could be used for Home automation or just sensor data that gets transfered to a database. Future versions of this will be sending the data to a Azure IOT Hub and then I want to report data from IOT Hub. I am looking at attaching a SQL database to this and storing the data that way.I see huge potential in being able to save the data for reporting.

Parts Needed

The following code is used on the Arduino side. The only difference I did with this version is that instead of building a HTML page when the Arduino sends data back I built a JSON string. When you look at the code for Visual Studio you will see that I parse the JSON and determine what to do with it. I feel you could have many different sensors sending data and based on the type of sensor know what type of data you are looking at and what to do with the data. For example in my sample I used a temp sensor and a tilt sensor. The temp sensor you would take the data and display it. 72 Degrees. For the tilt sensor the data to the end user does not make sense. 700-800 in one direction and 0 in the other. So what does that tell anyone. Who knows if the device is tilted or not based on that. So we have to do something with the data and display Tilted or Not Tilted.

Make sure you set a correct IP address to match the network you are plugging into. Also it is recommended to make sure you are not in the DHCP address range. If you are not sure of the range of your network. Usually the highest numbers are not taken. 200 and above.

#include "SPI.h"
#include "Ethernet.h"
#include "math.h"


double Thermister(int RawADC) {  //Function to perform the fancy math of the Steinhart-Hart equation
 double Temp;
 Temp = log(((10240000/RawADC) - 10000));
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;              // Convert Kelvin to Celsius
 Temp = (Temp * 9.0)/ 5.0 + 32.0; // Celsius to Fahrenheit - comment out this line if you need Celsius
 return Temp;
}


// 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 };
IPAddress ip(10,0,1,177);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);

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
  }

pinMode(A11, INPUT);//Only needed for temp sensor
pinMode(A13, INPUT);//Only needed for tilt switch sensor
pinMode(21, OUTPUT); //red light

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {
  //Check Temp sensor and light led if to high
  double testtemp = Thermister(analogRead(A11));
  //Serial.println(testtemp);
  if(testtemp < 85)
  {
    digitalWrite(21, HIGH);
  }else
  {
    digitalWrite(21, LOW);
  }
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    int currentcount = 0;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        currentcount ++;
         if (currentcount == 6) {
           Serial.write(c);
           if(c == '1')
           {
             Serial.println("Led On"); 
           }

   }
        //Serial.write(c);
        // 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) {

          String stringTwo = "{'sensors':["; 
          stringTwo += "{'type':'temp', 'serial':'185679', 'reading':'";
          char tempval[10]; 
          dtostrf(Thermister(analogRead(A11)),4,2,tempval);
          stringTwo += tempval;
          stringTwo += "'},";
          stringTwo += "{'type':'tilt', 'serial':'254658', 'reading':'";
          stringTwo += String(analogRead(A13));
          stringTwo += "'}";
          stringTwo += "]}";
          client.println(stringTwo);
          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();
    Serial.println("client disonnected");
  }
}

You need to download the Visual Studio code here HomeIOT VS2015. I have a preiew of the main part of the code below. You will see how I am parsing the JSON file and using the data to determine what to do next. I used an IF statement in this for now just because. But you could have a nice CASE statement that will give you cleaner code. Once I have this to a database, I would use the serial number in the Arduino code as the main ID. Then I could call report how often we get an overheat error. I will also start making the touch screen have buttons to do things automated coming soon.

 public async Task gatherdata()

        {

            using (var client = new HttpClient(new HttpClientHandler(), true))

            {
                //this is the IP of the Arduino. We could call many Arduinos and do things based on that.
                string siteaddress = string.Format("http://10.0.1.177"); 

                var SensorData = await client.GetStringAsync(siteaddress);


                // Parse JSON into dynamic object, convenient!
                JObject results = JObject.Parse(SensorData);

                // Process each employee
                foreach (var result in results["sensors"])
                {
                    // this can be a string or null
                    string type = (string)result["type"];
                    string serial = (string)result["serial"];
                    string reading = (string)result["reading"];

                    //I added the code so we can check what type of sensor it is and change what we do. 
                    //I will convert this to a case statement but I only added these 2
                    if (type == "temp")
                    {
                        TempReading.Text = reading;
                        Double temp = Convert.ToDouble(reading);
                        if(temp < 85)
                        {
                            pinValue = GpioPinValue.High;
                            pin.Write(pinValue);
                            LED.Fill = grayBrush;
                        }
                        else
                        {
                            pinValue = GpioPinValue.Low;
                            pin.Write(pinValue);
                            LED.Fill = redBrush;
                        }
                    }
                    if (type == "tilt")
                    {
                        TiltReading.Text = reading;
                        Double tilt = Convert.ToDouble(reading);
                        if (tilt > 500)
                        {
                            pinValue = GpioPinValue.High;
                            pin.Write(pinValue);
                            TiltLED.Fill = grayBrush;
                        }
                        else
                        {
                            pinValue = GpioPinValue.Low;
                            pin.Write(pinValue);
                            TiltLED.Fill = redBrush;
                        }
                    }

                }
            }

        }

Leave a Reply

Your email address will not be published. Required fields are marked *