loading

Save data of temperature and humidity on MySQL with Arduino Uno and Wifly

Featured
Picture of Save data of temperature and humidity on MySQL with Arduino Uno and Wifly
P1010025.JPG
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.
 
Remove these adsRemove these ads by Signing Up

Step 1: You need this

For this project, you need:

Arduino UNO or similar board  ($29.95)

http://www.sparkfun.com/products/11021

WiFly Shield ($89.95)
http://www.sparkfun.com/products/9954

Grove - Moisture sensor ($4.99)
http://www.seeedstudio.com/depot/grove-moisture-sensor-p-955.html?cPath=144_147

Six Jumper Wires ($4.50)
http://www.sparkfun.com/products/9387

DS18B20 Temperature Sensor with metal tip ($10.59)
http://www.olimex.cl/product_info.php?cPath=21_138&products_id=872&product__name=Breadborad_jumper_wire_pack

If only  need, One protoboar ($9.58)
http://www.olimex.cl/product_info.php?currency=USD&products_id=170&product__name=Proto_Board_Bread_board


AND....

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
P1010044.JPG
P1010046.JPG
P1010050.JPG
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
P1010064.JPG
P1010053.JPG
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` (
`id` INT( 255 ) NOT NULL AUTO_INCREMENT ,
`temp1` VARCHAR( 255 ) NOT NULL ,
`moi1` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;
-------------------------------------------------------------------

Step 5: Preparing for PHP files

You make three files:

conec.php 
In this file will connect to our database

CODE:

<?php
function Conection(){
   if (!($link=mysql_connect("your_ipserver","your_user","your_pass")))  {
      exit();
   }
   if (!mysql_select_db("your_database",$link)){
      exit();
   }
   return $link;
}
?>

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

add.php
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.

CODE:

<?php
   include("conec.php");
   $link=Conection();
$Sql="insert into tempmoi (temp1,moi1)  values ('".$_GET["temp1"]."', '".$_GET["moi1"]."')";     
   mysql_query($Sql,$link);
   header("Location: insertareg.php");
?>

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

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.

CODE:

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

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

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
#endif

#include
#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 );
WiFly.begin();

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 );
Serial.println(sensorValue);

client.print( "GET /add.php?");
client.print("temp1=");
client.print( temp );
client.print("&&");
client.print("moi1=");
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" );
client.println();
client.println();
client.stop();
}
delay( 5000 );
}

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

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

if ( !ds.search(addr)) {
//no more sensors on chain, reset search
ds.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.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end

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


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

ds.reset_search();

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 !!
fin.png
P1010066.JPG
P1010071.JPG
P1010076.JPG

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

1-40 of 59Next »
Amirul929 months ago

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

camilo.n1012 (author)  Amirul929 months ago
Hi, "your_ip server" is the address where you host the server MySQL. In this case, is "127.0.0.1", to connect the localhost.

which one in it?

w313123.PNG
camilo.n1012 (author)  JitendraR8 days ago

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.

Captura de pantalla 2015-07-22 a las 11.37.33.png

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

Capture3.PNG
camilo.n1012 (author)  Amirul928 months ago

This error is because you have not included the OneWire library, I recommend you download the version 2.0 from here: http://www.pjrc.com/teensy/td_libs_OneWire.html

akokate12 days ago

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

PramodK423 days ago
ExclusiveT2 months ago

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)  ExclusiveT1 month ago

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 camilo.nunez@cnf.cl

Regards and good luck !

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?

camilo.n1012 (author)  Victor ManuelR1 month ago

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 AqilahM5 months ago

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

camilo.n1012 (author)  Nurul AqilahM5 months ago
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!

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

how to that?im really newbie...

deepikaaa3 months ago

hi,can we implement this using arduino ethernet shield

Nurul AqilahM5 months ago

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

KingEverest6 months ago

Hello,

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)  KingEverest6 months ago
Hi !
Yes, you can, I recommend use this tutorial to get the sensor code: http://goo.gl/HBoZyr

Good luck !
fherchotron6 months ago

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)  fherchotron6 months ago
Hola Eddie. Si te refieres al Front-end de una señal digital, debe ser por medio del Arduino. Saludos !
Mrcalleman6 months ago

Hi

I tried the link goo.gl/g1lbSm but the page could not be found. Any idea?

Best regards Carl

dappelboom6 months ago

Thanks for the great instructions!

one small error/typo found in the arduino code:

client.print("tempt1=");
should be:
client.print("temp1=");

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)  dappelboom6 months ago

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

ivanvarella7 months ago

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

Thanks. :)

camilo.n1012 (author)  ivanvarella7 months ago
Hi Ivan ! This is the link where you can download the files : http://goo.gl/D20rsE

Good lucky !

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?

camilo.n1012 (author)  oscar.r.gallardo.377 months ago
Hi Oscar, well, for your case, I recommend you read this Instructables:

http://goo.gl/g1IbSm

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!
OmkarD1 year ago

Hi Camilo,

Nice tutorial !!

I am trying to upload temperature from temperature sensor. I am using temperature sensor, arduino uno, arduino ethernet shield and RJ 45 cable. I am using Xampp(https://www.apachefriends.org/index.html) database running on my PC. I have created a table(temp) in this database(temp_database). I have saved php files in my computer at C:xampp/htdocs/temp_database. I have hooked up Ethernet Shield to one of internet ports in my home. After all this i don't find table getting updated by temperature values. Is there any mistake? Please guide me.Here is the source code for Arduino:

#include "SPI.h"

#include "Ethernet.h"

const int temperaturePin = A0;

byte mac[] = { 0x90, 0xA2, 0xDB, 0x0F, 0x3A, 0xDF };

byte ip[] = { 131, 247, 19, 140 }; this is the ip address for Ethernet Shield

byte gateway[] = { 131, 225, 3, 254 };

byte subnet[] = { 255, 255, 252, 0 };

EthernetClient client ;

char server[] = "www.localhost.com";

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

}

// start the Ethernet connection:

if (Ethernet.begin(mac) == 0) {

Serial.println("Failed to configure Ethernet using DHCP");

// no point in carrying on, so do nothing forevermore:

// try to congifure using IP address instead of DHCP:

Ethernet.begin(mac, ip);

}

// give the Ethernet shield a second to initialize:

delay(1000);

Serial.println("connecting...");

}

void loop()

{

if( client.connect(server, 80))

{

float tem = getTemp();

Serial.println( tem );

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

client.print("tempt1=");

client.print( tem );

client.println( " HTTP/1.1");

client.println( "Host: localhost" );

client.println( "Content-Type: application/x-www-form-urlencoded" );

client.println( "Connection: close" );

client.println();

client.println();

client.stop();

}

delay( 5000 );

}

float getTemp() {

float voltage, V,t ;

voltage = analogRead(temperaturePin) ;

V = voltage * 0.004882814 ;

t = (V - 0.5) * 100.0;

return t;

}

Here is the conec.php file

<?php

function Conection(){

if (!($link=mysql_connect("localhost","root","8282"))) {

exit();

}

if (!mysql_select_db("temp_database",$link)){

exit();

}

return $link;

}

?>

Here is the add.php file:

<?php

include("conec.php");

$link=Conection();

$Sql="INSERT INTO 'temp'('temp1') VALUE ('".$_GET["temp1"]."')";

mysql_query($Sql,$link);

header("Location: insertareg.php");

?>

Here is the insertareg.php file:

<html>

<head>

<title>Data of Sensor</title>

</head>

<body>

<h1>Data from the temperature sensor</h1>

<form action="add.php" method="get">

<TABLE>

<tr>

<td>Temperature </td>

<td><input type="text" name="temp1" size="20" maxlength="30"></td>

</tr>

</TABLE>

<input type="submit" name="accion" value="Grabar">

</FORM>

<hr>

<?php

include("conec.php");

$link=Conection();

$result=mysql_query("select * from temp order by id desc",$link);

?>

<table border="1" cellspacing="1" cellpadding="1">

<tr>

<td> Temperature  </td>

</tr>

<?php

while($row = mysql_fetch_array($result)) {

printf("<tr><td>  %s </td></tr>", $row["temp1"]);

}

mysql_free_result($result);

?>

</table>

</body>

</html>

jbuenaseda1 year ago

Hi! I'm having an error in instareg.php It says

Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\xampp\htdocs\WEB2\php_files\conec.php on line 9

Can\'t use sensordata :

what should I do in here? anyone help?

err.jpg
jbuenaseda1 year ago

Hi! What will I write in this? Can you provide an example?

if (!($link=mysql_connect("your_ipserver","your_user","your_pass")))

fabmsg1 year ago

Hi! very nice tutorial. thanks!

is there any Ethernet version?

Hi! Nice tutorial!


I have a question

Where specifically are suppose to be the add.php, conec.php, insertareg.php???

Thanks for your time! :)

camilo.n1012 (author)  thernandez colon1 year ago

Hi ! These files must be hosted on your serve to be consulted for the database.

Much success and regards !
Camilo

Hi Camilo! Thanks for your answer.

Can I know what library for the WiFly Antenna did you used in this project?

I have try with two and the program and I get errors such as:

"byte has not been declared"

"Client has not been declared"

I think that must be a problem with the library I am using :)

Thanks a lot for your help! ;)

camilo.n1012 (author)  thernandez colon1 year ago

Hi ! c:

I recommend that you download it from Github, this link: https://github.com/jcrouchley/WiFly-Shield

In all modes, being very honest, it is recommended that if you work with Arduino and Wifi, you better have your the Arduino YUN.

If you have further questions do not hesitate to say them c:

Regards !!

Hi Camilo,

Did you have the problem "Client has not been declared"?

I am using the same library that you used and im getting this problem. Please if you solve it help me :)

Thanks for your help ;)

I bought the Arduino UNO R3 Recently :(

Did the Arduino UNO gave you some problem in this project?

Hello I have a project of home automation and I am trying to program the wifly, I have configured this module .I want to actually insert the sensor values from the arduino and display it in a web interface and save them in the database mysql I have tested this example but the table is still empty.Also, i dont understand why the instruction of GET is shown in the serial !!! , Can you help me please?

I'am using arduino uno + WIFLY RN-171 + XBEE shield
http://cooking-hacks.com/wp/wp-content/uploads/2012/03/DSC_0405.jpg
this is the execution of the code :

Sans titre.png
1-40 of 59Next »