Displaying Sensor Data in an App

Introduction

So, you learned how to control LEDs, use push buttons, and read data from temperature sensors on your Arduino, now what? Well, let’s do something with the data you are reading! Let’s create an Arduino project to read from a temperature sensor and write the information to the serial bus. Then, we will create a VB.NET project to read from the serial bus and display the temperature data on the screen.

This is a simple project to get started with communicating between your Arduino and a Windows Program. Once you are able to get the data streaming to VB.NET, the possibilities are endless.

Arduino Circuitry

The circuitry for this temperature sensor is very simple. All you will need is the following items:

  • 1 Arduino
  • 1 Breadboard
  • 1 USB Cable
  • 5 Jumper Wires
  • 1 4.7K Resistor
  • 1 DS18B20 Digital thermometer sensor

Look at Figure 1 for making all the connections. The Arduino should have jumper wires connected to 5v, GND, and Digital Pin 8. Once all the connections are made, connect the Arduino to your computer using the USB cable.

Arduino1
Figure 1: Wiring the Arduino

Arduino Code

Programming the Arduino to read from the temperature sensor is simple. The code might look a little daunting once it gets down to the getTemperature() function, but that code is provided with the DallasTemperature OneWire library. We will break down the entire file and explain what is happening.

Install OneWire

First things first. You will need to download the OneWire library for Arduino from the Arduino Playground: http://playground.arduino.cc/Learning/OneWire. Place the downloaded files into the Arduino library folder (typically found in Documents/Arduino/library). To confirm that the library was installed correctly: open the Arduino IDE, click the “File” menu, hover over “Examples” menu, and confirm that the “OneWire” menu is showing. Congratulations; you installed your first Arduino library!

I added comments throughout the script to explain everything that is happening.

Setup

The first thing we have to do is include the OneWire library into our script. Next, there are a few variables that need to be reserved and set aside for use later in the script.

#include <OneWire.h>

// OneWire Variables
int tempSensor = 8;   // Pin number
byte i;   // Used in getTemperature()
byte present = 0;   // Used in getTemperature()
byte type_s;   // Used in getTemperature()
byte data[12];   // Used in getTemperature()
byte addr[8];   // Used in getTemperature()
float celsius, fahrenheit;    // Used in getTemperature()
OneWire ds(tempSensor);   // Set up the OneWire class

void setup() {
   // Start Serial Connection
   Serial.begin(9600);
}

Loop Function

void loop() {
   // Get The Temperature
   float temp = getTemperature();
   // Print Temperature to Serial
   Serial.println(temp);
   // Wait 500 milliseconds before continuing
   delay(500);
}

getTemperature() Function

This function may look a little confusing, but reading the comments should help. Parts of this section were provided by the Arduino Playground.

// Get Temperature Function
float getTemperature () {
   // Search for a OneWire Device
   if ( !ds.search(addr)) {
      ds.reset_search();
      delay(250);
   }
   ds.reset();
   ds.select(addr);
   ds.write(0x44, 1);

   delay(500);   // Wait 500 milliseconds...

   // Read from OneWire, expecting 9 bytes
   present = ds.reset();
   ds.select(addr);
   ds.write(0xBE);

   for ( i = 0; i < 9; i++) {
      data[i] = ds.read();
   }

   // Convert the data to real temperature
   int16_t raw = (data[1] << 8) | data[0];
   if (type_s) {
      raw = raw << 3;
      if (data[7] == 0x10) {
         raw = (raw & 0xFFF0) + 12 - data[6];
      }
   } else {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;
      else if (cfg == 0x20) raw = raw & ~3;
      else if (cfg == 0x40) raw = raw & ~1;
   }

   // We are left with celsius
   celsius = (float)raw / 16.0;

   // Convert celsius to fahrenheit
   fahrenheit = celsius * 1.8 + 32.0;

   // Switch "fahrenheit" to "celsius" if you prefer
   return fahrenheit;
}

Upload and Test the Arduino Code

It’s now time to upload and test the code! Make sure the right board is selected from Tools menu > Board (see Figure 2) and make sure the correct serial port is select under Tools menu > Serial Port.

Arduino2
Figure 2: Selecting the correct serial port and board

After confirming the correct port and board, click the arrow button to upload your script the Arduino. Once the script is uploaded, click the magnifying glass near the top right of the IDE. This will open the serial monitor. Every time the Arduino gets the temperature, it will print to this monitor window.

Adruino3
Figure 3: Printing to the monitor window

If you see something similar what’s shown in Figure 3, great job! If you are seeing a constant reading of 32.00, there is something wrong with your circuitry and the sensor is not properly reading. Let’s move on to the Visual Basic part of the project now.

Visual Basic Program

The Visual Basic program is going to connect to the selected Serial Port and process the incoming serial information. In our case, it will only be a decimal temperature reading coming in about every second. The form is pretty generic and includes the following elements:

  • Serial Port Selection (combobox)
  • Baud Rate (textbox)
  • Connect Button (button)
  • Disconnect Button (button)
  • Temperature Display (textbox)
  • History List (listbox)
  • High / Average / Low Temperatures (textbox)
  • Serial Port (serialport)

I have attached all the project files to this article for you to use.

Arduino4
Figure 4: The completed temperature display

The VB.NET Code

I will explain the major parts of the Visual Basic code; however, I won’t explain everything. I have commented every part of the code in the project file to make it very easy to understand what is happening.

Function DoConnect()

DoConnect() makes the initial connection to the selected serial port.

Public Sub DoConnect()
   'Set up the serial port connection
   With SerialPort1
      'Selected Port
      .PortName = cmbPorts.Text
      'Baud Rate. 9600 is default.
      .BaudRate = CInt(txtBaudRate.Text)
      .Parity = IO.Ports.Parity.None
      .DataBits = 8
      .StopBits = IO.Ports.StopBits.One
      .Handshake = IO.Ports.Handshake.None
      .RtsEnable = False
      .ReceivedBytesThreshold = 1
      .NewLine = vbCr
      .ReadTimeout = 10000
   End With

   'Try to open the selected port...
   Try
      SerialPort1.Open()
      comOpen = SerialPort1.IsOpen
   Catch ex As Exception
      'Couldn't open it... show error
      comOpen = False
      MsgBox("Error Open: " & ex.Message)
   End Try

   btnDisconnect.Enabled = True
   btnConnect.Enabled = False
   txtBaudRate.Enabled = False
   cmbPorts.Enabled = False
End Sub

Function DoDisconnect()

DoDisconnect() is called by the disconnect button as well as the form close event. It closes the serial connection and enables the form elements.

Public Sub DoDisconnect()
   'Graceful disconnect if port is open
   If comOpen Then
      SerialPort1.DiscardInBuffer()
      SerialPort1.Close()

      'Reset our flag and controls
      comOpen = False
      btnDisconnect.Enabled = False
      btnConnect.Enabled = True
      txtBaudRate.Enabled = True
      cmbPorts.Enabled = True
   End If
End Sub

Serial Port Received Event

This is where the magic happens. Okay, it’s not really magic, but this is where the program is receiving the data from the Arduino. The data is received and sent to a new thread to handle processing.

Private Sub SerialPort1_DataReceived(ByVal sender _
   As System.Object, _
   ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
   Handles SerialPort1.DataReceived
   If comOpen Then

      Try
         'Send data to a new thread to update the
         'temperature display
         readbuffer = SerialPort1.ReadLine()
         Me.Invoke(New EventHandler(AddressOf updateTemp))
      Catch ex As Exception
         'Otherwise show error. Will display when
         'disconnecting.
         'MsgBox(ex.Message)
      End Try
   End If
End Sub

Function updateTemp()

This function is what actually handles processing the data. The temperature display is updated, the new temperature is added to the history list, the low and high temperature are compared, and the average temperate is calculated and updated.

Public Sub updateTemp(ByVal sender As Object, ByVal e _
   sAs System.EventArgs)
   'Update temperature display as it comes in
   Dim read As Decimal
   read = readbuffer.Replace(vbCr, "").Replace(vbLf, "")
   txtTemp.Text = read
   lstHistory.Items.Insert(0, read)

   'Check Highest Temp
   If txtHigh.Text < read Then
      txtHigh.Text = read
   End If

   'Check Lowest Temp
   If txtLow.Text > read Then
      txtLow.Text = read
   End If

   'Calculate Average
   Dim total As Decimal
   Dim count As Integer
   For Each temperature In lstHistory.Items
      total += temperature
      count = count + 1
   Next

   txtAverage.Text = total / count

   'Running count of temperature reads.
   GroupBox2.Text = "History [" & count & "]"
   'Reset total
   'Reset count
End Sub

Running the Program

Open up the project files in Visual Studio and start the program. Everything should work right out of the box. If you get the error “There are no com ports available!”, make sure you have connected the Arduino to the computer.

Select the correct com port from the combobox. There is no need to change the baud rate unless you have altered it in the Arduino source as well. Click Connect and you will start seeing the Arduino temperature data displayed in the temperature display textbox. The program will also keep a running log of all temperatures received in the history listbox to the right.

To disconnect from the Arduino, press the Disconnect button or close the form. Congratulations! You got your Arduino talking to a VB.NET program!

Make the Program Work for You!

So great, you can see the temperature in your room or office… Now what? The data is processed in the updateTemp() function. You can process the information any way you want from that function. Perhaps you want the program to alert you every time the temperature rises above 90 degrees; you would do something like this in that function:

If read > "90" Then
   MsgBox("Alert! High temperature in room!")
End If

Sure, this is a simple example, but the possibilities are endless with this project! Learn how to interface with your air conditioning unit from another Arduino board and have your program turn on and off the AC unit depending on the temperatures. Maybe you are trying to save money. Create an Arduino to control misters on the outside of your home to turn on and off when the temperature gets too hot.

Although this article covers the use of a temperature sensor, the code can be altered to accommodate almost any type of sensor available! Alter it to detect light with a light detecting resistor (LDR), sound with a microphone, humidity, distance with an infrared proximity sensor, or any other physical element with the vast array of sensors available.

Conclusion

Arduino boards are fun and exciting boards on their own, but pairing them up with a powerful language such as Visual Baic .NET can take a project to the next level! Once you pair the Arduino with something powerful like VB.NET, you can take your project to bigger and better places. The Arduino only has so much processing power on its own.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read