Introduction: Save Data of Temperature and Humidity on MySQL With Arduino Uno and Wifly

Picture of Save Data of Temperature and Humidity on MySQL With Arduino Uno and Wifly

Hello guys, i make this instructable for the people that  liked the electronics and the botanic, with this you have the data about  the temperatura and the humidity of your orchard and register this in a data base MySQL.

For this proyect you need some knowledge of programing in PHP and MySQL, we will make three archive .php, but this I'll explain in the following steps.

Step 1: You Need This

Picture of You Need This

For this project, you need:

Arduino UNO or similar board  ($29.95)

WiFly Shield ($89.95)

Grove - Moisture sensor ($4.99)

Six Jumper Wires ($4.50)

DS18B20 Temperature Sensor with metal tip ($10.59)

If only  need, One protoboar ($9.58)


you need a server WEB, with PHP and database MySQL. I used the NAS of QNAP TS-110, is perfect for this project.

Step 2: Setting the Temperature Sensor and Humidity

Picture of Setting the Temperature Sensor and Humidity

DS18B20 sensor is connected as follows. The position pin of the sensor Grove

Step 3: Connecting All in Arduino

Picture of Connecting All in Arduino

Now, we will connect the two sensors on the Arduino shield Wifly:

-For the temperature sensor, the pin order is: GND-VCC in 5v power - SIG in digital pin 3.

-For the Moisture sensor, the pin order is: GND - 3.3V VCC in power - SIG in the analog pin 0.

Step 4: Preparing the Database Mysql

In the query of NySQL you need put this code:

CREATE TABLE `your_database`.`tempmoi` (
`temp1` VARCHAR( 255 ) NOT NULL ,
`moi1` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )

Step 5: Preparing for PHP Files

You make three files:

In this file will connect to our database


function Conection(){
   if (!($link=mysql_connect("your_ipserver","your_user","your_pass")))  {
   if (!mysql_select_db("your_database",$link)){
   return $link;


This file allows us to send the data to our table "tempmoi" located in our database, where "temp1" is equivalent to the temperature data and "moi1" is equivalent to the humidity data. This file also allows us to Arduino send data to the base.


$Sql="insert into tempmoi (temp1,moi1)  values ('".$_GET["temp1"]."', '".$_GET["moi1"]."')";     
   header("Location: insertareg.php");


In this file we can see all the data collected by the sensors and put into the database, in addition to add some data of moisture and temperature if necessary.


   <title>Data of Sensor</title>
<h1>Data from the temperature and moisture sensors</h1>
<form action="add.php" method="get">
   <td>Temperature 1</td>
   <td><input type="text" name="temp1" size="20" maxlength="30"></td>
   <td>Moisture 1</td>
   <td><input type="text" name="moi1" size="20" maxlength="30"></td>
<input type="submit" name="accion" value="Grabar">
   $result=mysql_query("select * from tempmoi order by id desc",$link);
<table border="1" cellspacing="1" cellpadding="1">
         <td>&nbsp;Temperature 1&nbsp;</td>
         <td>&nbsp;Moisture 1&nbsp;</td>
   while($row = mysql_fetch_array($result)) {
printf("<tr><td> &nbsp;%s </td><td> &nbsp;%s&nbsp; </td></tr>", $row["temp1"], $row["moi1"]);


Step 6: Codes for the Arduino

To use this code requires the following libraries:

- OneWire librarie

- Wifly librarie

Well, i will briefly explain the code for the arduino, use the client that offers us the shield Wifly to send the data entering the digital pin 3 and pin analogue 0, these are sent as a sentences to file "agregar.php" for this we use the client.print.

I must remember to modify the data written in bold in the code:


#ifndef __CREDENTIALS_H__
#define __CREDENTIALS_H__
char passphrase[] = "pass_WIFI"; //password Wi-Fi
char ssid[] = "name_WIFI"; //name Wi-Fi

#include "WiFly.h"

int sensorPin = A0;
int sensorValue = 0;

int DS18S20_Pin = 3;
OneWire ds(DS18S20_Pin);

Client client( "your_server_web", 80 );

int looped = 1;

void setup()
Serial.begin( 9600 );

if( !WiFly.join( ssid, passphrase ) )
Serial.println( "Association failed." );

while( 1 )
// Hang on failure.

void loop()

if( client.connect() )
sensorValue = analogRead(sensorPin);
float temp = getTemp();
Serial.println( temp );

client.print( "GET /add.php?");
client.print( temp );
client.print( sensorValue );
client.println( " HTTP/1.1");
client.println( "Host: your_server_web" );
client.println( "Content-Type: application/x-www-form-urlencoded" );
client.println( "Connection: close" );
delay( 5000 );

float getTemp(){
//returns the temperature from one DS18S20 in DEG Celsius

byte data[12];
byte addr[8];

if ( ! {
//no more sensors on chain, reset search
return -1000;

if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return -1000;

if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial.print("Device is not recognized");
return -1000;

ds.write(0x44,1); // start conversion, with parasite power on at the end

byte present = ds.reset();;
ds.write(0xBE); // Read Scratchpad

for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] =;


byte MSB = data[1];
byte LSB = data[0];

float tempRead = ((MSB << 8) | LSB); //using two's compliment
float TemperatureSum = tempRead / 16;

return TemperatureSum;



Step 7: And Now ... to Prove It !!

Picture of And Now ... to Prove It !!

Now we will check in "insertareg.php" data sent over Wi-Fi to your Mysql database PHP THROUGH.

This project can use on your crops, it is easy to use and manipulate, with the background light.

Hope you liked this instructable, if they have questions do not hesitate to make.

Good luck : D


BeldiA made it! (author)2017-08-12

i have this problem with the php connec file please help i'm using wamp server

hokletrain (author)BeldiA2017-09-03

Change all mysql to mysqli perhaps or you have the connection info wrong.

MehmetK59 (author)2017-05-16

Hello! First of all, thank you for sharing this instructable! It is very useful and nice for starters such me.

However, can you please help me doing the same things with ESP8266, instead of WiFly?
Thank you in advance!

robot1972 (author)2017-04-20

How to change the PHP code to work with an Access Database?


Pavisindhu (author)2017-02-18

please help me how to store data from arduino to database in ultrasonic sensor

Sovatna (author)2016-12-02


It does not work with my code. I meant it does not send the data to my local Mysql. Please kindly help. The code is here below:

#include <SPI.h>

#include <Ethernet.h>

#include <String.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

byte ip[] = {192,168,1,110}; //address of arduino

byte server[] = {192,168,1,1};//address of rooter

EthernetClient client;

float sensor = 0;

void setup() {


Ethernet.begin(mac, ip);


void loop() {

char comend =;

if(comend == 'a'){



sensor = sensor + 5;

client.print("GET /arduino/tempTest/templogin.php?");



Serial.print("Sensor = ");




}else {

Serial.println("Not connected...");





Amirul92 (author)2014-10-19

hello. I just want to asking about the connect.php. What do you mean by "your_ipserver" ?

camilo.n1012 (author)Amirul922014-10-20

Hi, "your_ip server" is the address where you host the server MySQL. In this case, is "", to connect the localhost.

will you help me to use ethernet shield to do the same task...

JitendraR (author)camilo.n10122015-07-21

which one in it?

camilo.n1012 (author)JitendraR2015-07-22

None of these data will be used , if you are using phpMyAdmin , go to the tab " Estado Actual" ( as from image ) and in the section of server, have the direction of you need.

Amirul92 (author)camilo.n10122014-11-02

hai. I'm having a problem with the arduino coding. It said as shown in the image:

camilo.n1012 (author)Amirul922014-11-02

This error is because you have not included the OneWire library, I recommend you download the version 2.0 from here:

shanthS made it! (author)2016-08-15

can i do this without WiFly Shield? (using cable in serial connection)

Johnson Selva (author)shanthS2016-08-23

Use Arduino.h or arduino.h instead of Wprogram.h hope it works for you too...

shanthS (author)Johnson Selva2016-08-23

thnx i will try

RinaldiA2 (author)2016-08-19

Hi Camilo i got some problem, i got some error with ur arduino codes. Here the message :

Arduino: 1.6.6 (Windows 10), Board: "Arduino Nano, ATmega328"

In file included from C:\Program Files\Arduino\libraries\WiFly/SpiUart.h:7:0,

from C:\Program Files\Arduino\libraries\WiFly/WiFly.h:4,

from C:\Users\Documents\Arduino\Coba\Coba.ino:8:

C:\Program Files\Arduino\libraries\WiFly/_Spi.h:8:22: fatal error: WProgram.h: No such file or directory

#include <WProgram.h>


compilation terminated.

exit status 1

Error compiling.

This report would have more information with

"Show verbose output during compilation"

enabled in File > Preferences.

HugoM59 (author)2016-05-12

Hi XiongL. I think you need to set IP Address of your PHP Server (Web server + PHP + MySQL). In short means, in your ardunio, you will build a link address like this Obviously, vars "temp" and "sensorValue" will contain measured values from sensors. In the file add.php you will catch this data and then run code PHP to insert them in MySQL.

XiongL (author)2016-05-04

hi can tell me

Client client( "your_website", 80 );

your_website what should i put ?

XiongL (author)2016-05-04

i`m using arduino yun via wifi can use the same code as yours ?

dnb.dinusha (author)2016-04-30

Hi ,i use this code in arduino but nothin works

client.print(" GET / add.php?value=");

client.println( " HTTP/1.1");
client.println( "Host:" );
client.println( "Content-Type: application/x-www-form-urlencoded" );
client.println( "Connection: close" );


Ayeza (author)2016-03-29

I need help regarding sending my sensor's values to database. I am unable to send the values instead variable to which i am passing these values is showing me zero at database.

GabrielC91 (author)2016-02-18

I love u..., I'm many grateful! :D

kashif.mushtaq07 (author)2015-12-12

hi i am using cc3000 wifishield so i have to send sensor data to phpserver how to modify code and where plzz help me in this


zalsalm (author)2015-09-28

Hello again, I did the same steps which you were did till I reached to show the content of database in the website, but it seems there is a problem between add php and arduino. the arduino sends the data but it is not shown in the website can have a look at it thanks

camilo.n1012 (author)zalsalm2015-09-28

Hi! Send me the code for review and test to see what is going wrong . My email is

zalsalm (author)2015-09-25

thanks for your efforts. can I use the blue WiFi shield instead of the red one that you use it. what is the example you suggest to use it.

camilo.n1012 (author)zalsalm2015-09-26

If you mean the original Shield Arduino WiFi , you need to read the page of the project :

Good luck !

akokate (author)2015-07-18

Nice Tutorial.
Can I Add a LCD to display the temperature on it and also save it in the database.

ExclusiveT (author)2015-05-30

Hello camilo.
thanks for your nice post which was very helpful.

i want to make a data storage and monitoring using Arduino uno & Arduino ethernet shield W5100. please help me by PHP & Arduino code.

Thanks and waiting for replay.

camilo.n1012 (author)ExclusiveT2015-06-01

Hi ! In the case for the Ethernet Shiel, you only need modify the data of the Shield, then, you work with the variables "temp" and "sensorValue". If you have more doubts, write me to my email

Regards and good luck !

Victor ManuelR (author)2015-05-22

Hola Camilo:

Muy buen tutorial, felicidades.

Que tendria que cambiar en el script de arduino, estoy utilizando un Wifi Shield cc3000 de Adafruit en lugar del WiiFly?

Hola Victor ! Bueno para serte honesto, no he trabajado nunca con ese modulo, pero como el programa es genérico en sus variables, lo que te debe importar al momento de trabajar con otros módulos, es que tus variables "temp" y "sensorValue" no cambien cuando manipules el Script. Si tienes más dudas me avisas ! Exito y muchas gracias !

Nurul AqilahM (author)2015-02-05

hye.. nice posting..can you help me?because im beginner in this programming. where to put all of the code for database mysql?

Hi ! For the use of MySQL you must have a server that hosted on same hosting or plan, then you only need to upload the .sql file to import the table. Greetings!

UplifitingT (author)camilo.n10122015-04-23

Is it possible to do the same with Ultrasonic sensor and what code is necessary to do?

how to that?im really newbie...

deepikaaa (author)2015-04-08

hi,can we implement this using arduino ethernet shield

Nurul AqilahM (author)2015-02-08

hye..where i have to put all this files?i just manually added?

KingEverest (author)2015-01-29


Can this work with water flow sensor? I need to create a similar project but to measure the flow rate of water. The sensor type i'm intending to use is SKU: POW110D3B.

Thanks and awaiting for your reply

camilo.n1012 (author)KingEverest2015-01-29

Hi !
Yes, you can, I recommend use this tutorial to get the sensor code:

Good luck !

fherchotron (author)2015-01-26

Hola... excelente trabajo... por lo que he visto envias datos desde tu arduino a una base de datos en SQL, y la visualizas en un browser.... pero en el caso que quieras activar una señal digital, lo haces desde tu front por medio del SQL o desde tu front directamente hacia Arduino?

camilo.n1012 (author)fherchotron2015-01-27

Hola Eddie. Si te refieres al Front-end de una señal digital, debe ser por medio del Arduino. Saludos !

Mrcalleman (author)2015-01-13


I tried the link but the page could not be found. Any idea?

Best regards Carl

dappelboom (author)2015-01-07

Thanks for the great instructions!

one small error/typo found in the arduino code:

should be:

Being dyslectic it took my 20 minutes to figure this out (-:

But once I found the error, ot worked like a charm and was easily adjusted for my needs.

camilo.n1012 (author)dappelboom2015-01-07

Hi ! Thanks for correct the mistake, not pass without noticing. I've already changed the page. Thank you very much!

ivanvarella (author)2014-12-25

Hey guys, I am new here. How can I download the files (.php and .ino)?

Thanks. :)

camilo.n1012 (author)ivanvarella2014-12-27

Hi Ivan ! This is the link where you can download the files :

Good lucky !

oscar.r.gallardo.37 (author)2014-12-21

Hello. I'm doing a project that is based on receiving data of temperature, wind speed and things like that. But I'm using Arduino Yún in case of Arduino Uno+Wifly.

Which differences will be having the code?

Hi Oscar, well, for your case, I recommend you read this Instructables:

The difference lies in Bridge and in which language you want to work with to the database, if PHO or Python. It will depend on your project.

If you need more information about working with databases Arduino YUN, please tell me to help.

Many luck!

About This Instructable




More by camilo.n1012:Control Access of Arduino YÚN with MySQL, PHP5 and PythonAccess control with Arduino + Keypad 4x4 + Servo (UPDATE)Save data of temperature and humidity on MySQL with Arduino Uno and Wifly
Add instructable to: