Java, C#, Symfony, Laravel, Android, Xcode, Arduino Please Donate: https://streamlabs.com/georgesqhk
Friday, June 27, 2014
George's Blog (Software Development): Temperature and Humidity Sensor DHT11 in Arduino w...
George's Blog (Software Development): Temperature and Humidity Sensor DHT11 in Arduino w...: Temperature and Humidity Sensor DHT11 in Arduino with Java and JfreeChart 1. Problem Statement In this tutorial we will learn how use te...
Temperature and Humidity Sensor DHT11 in Arduino with Java and Jfreechart
Temperature and Humidity Sensor DHT11 in Arduino with Java and JfreeChart
1. Problem Statement
In this tutorial we will learn how use temperature and humidity sensor from the environment using DHT11 in Arduino and process the information in Java via serial Port. We will show the temperature in Celsius degree and Humidity in percentage using JFreeChart open source library.2. JFreeChart
JFreeChart is an open-source framework library for the programming language Java, which allows the creation of a wide variety of both interactive and non-interactive charts. A free Java chart library. JFreeChart supports pie charts (2D and 3D), bar charts (horizontal and vertical, regular and stacked), line charts, scatter plots, time series charts, high-low-open-close charts, candlestick plots, Gantt charts, combined plots, thermometers, dials and more. JFreeChart can be used in applications, applets, servlets, JSP and JSF. You can download from the official web site jfreechart3. Temperature and Humidity Sensor DHT11
The DHT11 is a basic, ultra low cost digital temperature and humidity sensor. It uses a capacitive humidity sensor and a thermostat to measure the surrounding air, and spits out a digital signal on the data pin. It's fairly simple to use, but requires careful timing to grab data. The only real downside of this sensor is you can only get new data from it once every 2 seconds. In the market you will find many models, some of them have 3 or 4 pins, so be carefully and read the technical specifications.The technical specification of DHT11 are:
- 3 to 5V power and I/O
- 2.5mA max current use during conversion (while requesting data)
- Good for 20-80% humidity readings with 5% accuracy
- Good for 0-50°C temperature readings ±2°C accuracy
- No more than 1 Hz sampling rate (once every second)
- Body size 15.5mm x 12mm x 5.5mm
- 3 pins with 0.1" spacing

4. Sketch for this project
For implement this project we will required the following materials:- DHT11 temperature and humidity sensor
- Wires
- Arduino UNO R3

In the next figure we can see the first pin is connected to pin digital 2 in arduino board, the middle one to 5v and the last one is connected to GND.
5. Arduino Source Code to get Temperature and Humidity from DHT11
The source code in arduino is not so complicated, as we can see first you need to add the library dht11.h to start to use DHT11 temperature and humidity sensor and then define the digital pin you will use to read the information from the sensor and finally read the information from dht11 sensor (temperature and humidity) and print in the serial port for further reading from C#.
#include <dht11.h>
//Declare objects
dht11 DHT11;
//Pin Numbers
#define DHT11PIN 2
void setup()
{
Serial.begin(9600);
}
void loop()
{
int chk = DHT11.read(DHT11PIN);
//read temperature in celsius degree and print in the serial port
Serial.print(DHT11.humidity);
Serial.print(",");
//read humidity and print in the serial port
Serial.print(DHT11.temperature);
Serial.println();
delay(2000);
}
6. Designing Project in Java to Show Temperature and Humidity using JFreeChart
First create a java project in Netbeans, in your project go to Libraries folder, right click choose Add JAR/Folder and add the following libraries. Please replace the version numbers with the version you are using.- jcommon-1.0.21.jar
- jfreechart-1.0.17.jar
Java Source Code
In this part we need to create a Class for manage serial Port in Java, for this you can see in this link the java class provide by arduino web site, where also you find the explanation, I modified a little bit that class according to what I want to do, the source code of my class is the following.
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
/**
*
* @author george serrano, develop for http://georgehk.blogspot.com
*/
public class SerialPortCommunication {
//SerialPort
public SerialPort serialPort;
//The port we're normally going to use.
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM4", // Windows
};
//input and output Stream
private BufferedReader input;
private OutputStream output;
//Milliseconds to block while waiting for port open
public static final int TIME_OUT = 1000;
//Default bits per second for COM port.
public static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier)
portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams for reading and writing in the serial port
input = new BufferedReader(new
InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
} catch (Exception e) {
System.err.println(e.toString());
}
}
public void writeData(String data) {
try {
//write data in the serial port
output.write(data.getBytes());
} catch (Exception e) {
System.out.println("could not write to port");
}
}
public String getData() {
String data = null;
try {
//read data from the serial port
data = input.readLine();
} catch (Exception e) {
return e.getMessage();
}
return data;
}
}
Also we need to instantiate an object of this class in JFrame's constructor
public frmTemperatureArduinoUNO() {
initComponents();
//initialize serial Port
serialPortCommunication = new SerialPortCommunication();
serialPortCommunication.initialize();
}
The last steep is implement the source code for Get Temperature Humidity Button
private void jbtnShowTemperatureHumidityActionPerformed
(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jtxtHumidity.setText(null);
jtxtTemperature.setText(null);
//set temperature in 0
datasetTemperature.setValue(0);
//set humidity in 0
datasetHumidity.setValue(0);
try {
int temperature, humidity;
//get temperature and humidity from serial port
//sent by arduino and save in temporal string
String temperatureHumidityArduino =
serialPortCommunication.getData();
//split temperature and humidity
//divided by commas and save in array
String[] temperatureHumidity =
temperatureHumidityArduino.split(",");
//get temperature from array and convert to integer
temperature = Integer.parseInt(temperatureHumidity[0]);
//get humidity from array and convert to integer
humidity = Integer.parseInt(temperatureHumidity[1]);
//show temperature and humidity in JTextBoxes
jtxtTemperature.setText(String.valueOf(temperature) + " °C");
jtxtHumidity.setText(String.valueOf(humidity) + " %");
//draw temperature
drawDataSetJfreeChart(temperature, datasetTemperature,
jSliderTemperature);
//draw humidity
drawDataSetJfreeChart(humidity, datasetHumidity,
jSlideHumidity);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Once you run the project it will show the next window, where we can see two thermometers, one of them for showing the temperature and another to show humidity, also two extra JSliders to probe the right measurement of those thermometers, and finally two JTextBoxes for showing the temperature and humidity in numbers.

7. Running Project
Before run the project make sure the Arduino in writing the temperature and humidity to serial port. Just press F6 to run the project and you will see the program start to looking for serial port open. After press Get Temperature Humidity Button, our program will read temperature and humidity from serial port and draw them in thermometer and humidity chart like depicted in the next figure.
video tutorial in youtube
Friday, May 16, 2014
Temperature and Humidity Sensor DHT11 in Arduino with C#
Temperature and Humidity Sensor DHT11 in Arduino with C#
1. Problem Statement
In this tutorial we will learn how use sensor to get temperature and humidity from the environment using DHT11 Sensor in Arduino and process the information in C# via the serial Port. We will show the temperature in Celsius and Humidity.2. Temperature and Humidity Sensor DHT11
The DHT11 is a basic, ultra low cost digital temperature and humidity sensor. It uses a capacitive humidity sensor and a thermostat to measure the surrounding air, and spits out a digital signal on the data pin. It's fairly simple to use, but requires careful timing to grab data. The only real downside of this sensor is you can only get new data from it once every 2 seconds. In the market you will find many models, some of them have 3 or 4 pins, so be carefully and read the technical specifications. The technical specification of DHT11 are:- 3 to 5V power and I/O
- 2.5mA max current use during conversion (while requesting data)
- Good for 20-80% humidity readings with 5% accuracy
- Good for 0-50°C temperature readings ±2°C accuracy
- No more than 1 Hz sampling rate (once every second)
- Body size 15.5mm x 12mm x 5.5mm
- 3 pins with 0.1" spacing
3. Sketch for this project
For implement this project we will required the following materials:- DHT11 temperature and humidity sensor
- Wires
- Arduino UNO R3

In the next figure we can see the first pin is connected to pin digital 2 in arduino board, the middle one to 5v and the last one is connected to GND.

4. Arduino Source Code to get Temperature and Humidity from DHT11
The source code in arduino is not so complicated, as we can see first you need to add the library dht11.h to start to use DHT11 temperature and humidity sensor and then define the digital pin you will use to read the information from the sensor and finally read the information from dht11 sensor (temperature and humidity) and print in the serial port for further reading from C#.
#include <dht11.h>
//Declare objects
dht11 DHT11;
//Pin Numbers
#define DHT11PIN 2
void setup()
{
Serial.begin(9600);
}
void loop()
{
int chk = DHT11.read(DHT11PIN);
//read temperature in celsius degree and print in the serial port
Serial.print((float)DHT11.humidity, 2);
Serial.print(",");
//read humidity and print in the serial port
Serial.print((float)DHT11.temperature, 2);
Serial.println();
delay(2000);
}
5. Designing Project in C# to Show the Temperature and Humidity
To implement this project using C# we require to draw a gauge control and a needle, in my case I draw them using photoshop for displaying temperature and put the gauge picture in a PictureBox control and for movement of the needle we will make programmatically. Also we need a couple of TextBox to show the temperature, humidity and time. Every 10 seconds we will update the temperature and humidity so we need to use Timer controls and finally we will need a SerialPort control to read the information from the serial port. The design of the interface is shown in the next figure.
C# Source Code
As we can see this is the main part of the c# source code for this project, we split the information we get from arduino separate by commas into temperature and humidity and then draw that temperature in the gauge control.
private void timer1_Tick(object sender, EventArgs e)
{
//read temperature and humidity every 10 seconds
timer1.Interval = 10000;
//read information from the serial port
String dataFromArduino = serialPort1.ReadLine().ToString();
//separete temperature and humidity and save in array
String[] dataTempHumid = dataFromArduino.Split(',');
//get temperature and humidity
int Humidity =
(int)(Math.Round(Convert.ToDecimal(dataTempHumid[0]),0));
int Temperature =
(int)(Math.Round(Convert.ToDecimal(dataTempHumid[1]),0));
//draw temperature in the graphic
drawTemperature(Temperature);
txtHumidity.Text = Humidity.ToString()+" %";
txtTemperatureCelsius.Text = Temperature.ToString()+" °C";
}
private void timer2_Tick(object sender, EventArgs e)
{
txtTime.Text = DateTime.Now.ToLongTimeString();
}
private void frmTemperatureHumidity_Load(object sender, EventArgs e)
{
needle = Image.FromFile("needle2.png");
serialPort1.Open();
}
6. Running Project
Just press F5 to run the project and you will see the program start to read from the serial port and show in the gauge control, and every 10 seconds it will update with the new information getting from the DHT11 sensor.
you could see all the implementation in youtube here
Wednesday, May 7, 2014
George's Blog (Software Development): Temperature Sensor LM35 in Arduino with C#
George's Blog (Software Development): Temperature Sensor LM35 in Arduino with C#: Temperature sensor LM35 in Arduino with CSharp 1. Problem Statement In this tutorial we will learn how use temperature sensor LM35 to ge...
Temperature Sensor LM35 in Arduino with C#
Temperature sensor LM35 in Arduino with CSharp
1. Problem Statement
In this tutorial we will learn how use temperature sensor LM35 to get temperature from the environment in Arduino and process the information in C# via the serial Port, Also we will show the temperature in Celsius and Fahrenheit degrees.2. LM35 Precision Centigrade Temperature Sensors
The LM35 is integrated-circuit temperature sensor, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in ° Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient Centigrade scaling. The LM35 does not require any external calibration or trimming to provide typical accuracies of ±1⁄4°C at room temperature and ±3⁄4°C over a full −55 to +150°C temperature range. Low cost is assured by trimming and calibration at the wafer level.. The LM35 is rated to operate over a −55° to +150°C temperature range.Previously we need to understand couple of things, so to connect it to Arduino, you must connect VCC to Arduino 5V, GND to Arduino GND, and the middle pin you must connect to an Analog Pin, in my case we will use A0(Analog pin). This projects doesn't need any resistor or capacitor between the Arduino and the Sensor, but you need to know that Arduino ADC has a precision of 10 bits. This means:
5V / 2^10 = 5V / 1024, so 0.0049 is our factor. To get the temperature in Celsius from LM35, we calculate like this: Temperature Celsius = (pinA0 * 0.0049)*100
3. Sketch for this project
For implement this project we will required the following materials:- LM35 temperature sensor
- Couple of Wires
- Arduino UNO R3

4. Source code to Get Temperature from LM35 in Arduino
Go to Arduino text Area and type de following code, first we define the analog Pin, sensorValue and temperature in Celsius, second we start to open communication for serial, third we get the voltage from LM35 and convert to celsius degree and write in the serial port and get the information from C# and show the temperature.
#define sensorPin 0 //A0 Pin
int sensorValue = 0;
float celsius = 0;
void setup() {
Serial.begin(9600); //start Serial Port
}
void loop() {
getTemperature();
//send celsious value to Port and read from C#
Serial.println(celsius);
delay(1000);
}
void getTemperature(){
//get sensorPin voltage
sensorValue = analogRead(sensorPin);
//convert voltage to celsius degree
celsius = (sensorValue * 0.0049) *100;
}
5. Design Project in C# to show temperature in Celsius and Fahrenheit
Design an interface like depicted in next figure, for design the thermometer I used the Old GDI+, also we will add a TextBox to show the temperature get from serial Port and finally one Button to show the temperature in the thermometer.
The next code is for button Show temperature, first we verify if the port is open and after get the temperature from serial port which was send by arduino and round this value and send that value to a function which is in charge to draw the current temperature in the thermometer.
private void btnShowTemperature_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
//get Temperature from serial port sent by Arduino
int temperature = (int)(Math.Round(Convert.ToDecimal(
serialPort1.ReadLine()), 0));
txtTemperature.Text = temperature.ToString();
//draw temperature in the thermometer
DrawTemperatureLevel(temperature);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
6. Running the project
First in arduino UNO R3 press the button Upload and then go to visual studio and run the project, second press the button Show Temperature and then it will show the temperature in the thermometer as shown next figure.
you can watch the video tutorial on youtube.
Monday, May 5, 2014
Turn ON and Turn OFF LED in Arduino using Visual Studio C#
Turn ON/OFF LED in Arduino Using Visual Studio
1. Problem Statement
In this tutorial we will learn how to Turn ON and Turn OFF a LED in arduino, but this time using Visual Studio using the serial Port and C# programming language.2. What is a serial interface?
A serial interface is used for information exchange between computers and peripheral devices. When using a serial communication, the information is sent bit by bit (serial) over a cable. Modern serial interfaces are Ethernet, Firewire, USB, RS-485, etc. For our project we will use the USB port.Visual Studio provide a serialPort control which we will use for this project.
3. Sketch for this project
We are going to use the sketch used in our first tutorial, which just need a LED, 100ohm resistors and wires to connect them with Arduino board, the next picture show the connections.
4. Source Code for Arduino
The source code for this project is simple to understand, but in this case we will get the information from the serial port dispatched by C# program and then we will verify to turn ON(1) or turn OFF(0), Type the following code in the text area of arduino the code is explained line by line.
#define BaudRate 9600
#define LEDPin 10
char incomingOption;
void setup()
{
pinMode(LEDPin, OUTPUT);
// serial communication
Serial.begin(BaudRate);
}
void loop()
{
//read from serial port getting information from VS 2013
incomingOption = Serial.read();
//verify incomingOption
switch(incomingOption){
case '1':
// Turn ON LED
digitalWrite(LEDPin, HIGH);
break;
case '0':
// Turn OFF LED
digitalWrite(LEDPin, LOW);
break;
}
}
5. Design the Interface in Visual Studio for communicate with Arduino
Design a interface with 3 buttons, the first one will turn ON the LED, the second one will turn OFF the LED and finally the third button will close the serial port.
You need to drag and drop a serialPort control to the design area and set properties BaudRate to 9600 and PortName to COM4 and that's all for the design part.
Next we need to write the code for turning ON and Turning OFF.
public partial class frmTurnONTurnOFFLED : Form
{
public frmTurnONTurnOFFLED()
{
InitializeComponent();
}
private void btnTurnON_Click(object sender, EventArgs e)
{
try
{
serialPort1.Write("1"); //send 1 to Arduino
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnTurnOFF_Click(object sender, EventArgs e)
{
try
{
serialPort1.Write("0"); //send 0 to Arduino
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void frmTurnONTurnOFFLED_Load(object sender, EventArgs e)
{
serialPort1.Open(); //open serialPort
}
private void btnClosePort_Click(object sender, EventArgs e)
{
serialPort1.Close(); //close serialPort
}
}
Wednesday, April 30, 2014
Traffic Light Arduino UNO R3
1. Problem Statement
In this tutorial we are going to create a project to simulate a traffic light using arduino UNO R3 where the system will change from red to green, via amber and repeat this process again and again.2. What is a LED
A light-emitting diode (LED) is a two-lead semiconductor light source that resembles a basic pn-junction diode, except that an LED also emits light.An LED is a diode that also emits light. LEDs come in different colors and brightnesses, and can also emit light in the ultraviolet and infrared parts of the spectrum (as in the LEDs in your TV remote control). If you look carefully at an LED, you will notice two things. One is that the legs are of different lengths, and also, that on one side of the LED it is flattened rather than cylindrical (see Figure). These are indicators to show you which leg is the anode (positive) and which is the cathode (negative). The longer leg (anode) gets connected to the positive supply (3.3V) and the leg with the flattened side (cathode) goes to ground.

There is another LED called RGB LED which has a red, green, and blue one package. The LED has four legs: one will be a common anode or cathode, common to all three LEDs and the other three will then go to the anode or cathode of the individual red, green and blue LEDs. You can get any color you want just adjusting the brightness values of the R, G and B channels of the RGB LED.
3. Parts Required for Traffic Light
for implement this project we will need the following materials, breadboard, 3 LEDs(Red, Yellow and Green), 150ohm resistors(3) and jumpers wires to connect.
4. Sketch for Traffic Light
Using Fritzing we draw the following sketch for traffic light project, we just need to make some simple connection as we can see in the next figure.
5. Coding traffic light
In this section we need to write some code for making run our traffic light project just type the following code in the text area of arduino editor. Make sure your arduino is not connected to computer while you assemble the project to avoid damage to the board.
//Traffic light in arduino UNO R3
int ledDelay = 10000; // delay in between changes
int redPin = 10;
int yellowPin = 9;
int bluePin = 8;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
digitalWrite(redPin, HIGH); // turn the red light on
delay(ledDelay); // wait 5 seconds
digitalWrite(yellowPin, HIGH); // turn on yellow
delay(2000); // wait 2 seconds
digitalWrite(bluePin, HIGH); // turn green on
digitalWrite(redPin, LOW); // turn red off
digitalWrite(yellowPin, LOW); // turn yellow off
delay(ledDelay); // wait ledDelay milliseconds
digitalWrite(yellowPin, HIGH); // turn yellow on
digitalWrite(bluePin, LOW); // turn green off
delay(2000); // wait 2 seconds
digitalWrite(yellowPin, LOW); // turn yellow off
// now our loop repeats
}
Finally verify if there is not error and connect the arduino USB to your computer and then press in Upload Icon to run.You can see video demonstration on YouTube.
Subscribe to:
Posts (Atom)