Home ArduinoArduino Tutorials Arduino to C# temperature example

Arduino to C# temperature example

This time we will  create a more practical example of connecting an Arduino to a PC and then writing an app to read data via the com port. In this example we use a DS18B20 temperature sensor, we will take a reading and display this in our app. In this example the app is a windows form application and it only contains a text box.

You can see an image of this below in action, Arduino code with the app running

serial temp out

serial temp out

This comprises of 2 parts so lets look at the first which is the Arduino code, we use a DS18B20 breakout board and connect its data out pin to Arduino digital pin 2, you can use another but remember and update the #define at the start.

Arduino Code

#include <OneWire.h>
#include <DallasTemperature.h>

//the pin you connect the ds18b20 to
#define DS18B20 3

OneWire ourWire(DS18B20);
DallasTemperature sensors(&ourWire);

void setup()
//start reading

void loop()
//read temperature and output via serial


Now we move on to the C# code, this is the form.cs code

C# Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ArduinoSerialTemp
public partial class Form1 : Form
public Form1()
serialPort1.BaudRate = 9600;
serialPort1.PortName = “COM5″;
serialPort1.DataReceived += serialPort1_DataReceived;

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
string line = serialPort1.ReadLine();
this.BeginInvoke(new LineReceivedEvent(LineReceived), line);

private delegate void LineReceivedEvent(string line);
private void LineReceived(string line)
textBox1.Text = line + ” celsius”;

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
if (serialPort1.IsOpen) serialPort1.Close();

private void serialPort1_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)




We also have this available from GITHUB, you can get the project here


You may also like