DS18B20->PHP-> MySQL / what is wrong with my code?

Hey Folks,
I´m trying to store temperature data in a MySQl-Database on my kitchen-server. It works now with one Sensor but the Code is a real Frankensteins Monster because i´m new to programming and don´t really understand what i´m doing :wink:
At least i managed ist to get a LAMP System working on my kitchensever and to store the data from zero in about 2 months :wink:
It works fine with this code for one sensor( attention, a real mess):

#include <EthernetDNS.h>
#include <Client.h>
#include <Ethernet.h>
#include <Server.h>

#include <OneWire.h>
#include <DallasTemperature.h>
bool connected = false;
//--------------------------------------------------------------//
// ethernet section//

//mac-adress of arduino board
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// IP-adress of arduino board
byte ip [] = {192, 168, 0, 17};
//IP-adress of router
byte gateway[] = {192, 168, 0, 1};
//subnet-mask (optional)
byte subnet[] = {255, 255, 255, 0};

byte serverIP[] = {192, 168, 0, 4};

Client client(serverIP,80);

//--------------------------------------------------------------//
//OneWire-Section//

// Data wire is plugged into port 7 on the Arduino
#define ONE_WIRE_BUS 7
#define TEMPERATURE_PRECISION 9

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;

void setup(void)
{
  //start ethernet
  Ethernet. begin(mac, ip);
  
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");

  // report parasite power requirements
  Serial.print("Parasite power is: "); 
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  // assign address manually.  the addresses below will beed to be changed
  // to valid device addresses on your bus.  device address can be retrieved
  // by using either oneWire.search(deviceAddress) or individually via
  // sensors.getAddress(deviceAddress, index)
  //insideThermometer = { 0x28, 0x1D, 0x39, 0x31, 0x2, 0x0, 0x0, 0xF0 };
  //outsideThermometer   = { 0x28, 0x3F, 0x1C, 0x31, 0x2, 0x0, 0x0, 0x2 };

  // search for devices on the bus and assign based on an index.  ideally,
  // you would do this to initially discover addresses on the bus and then 
  // use those addresses and manually assign them (see above) once you know 
  // the devices on your bus (and assuming they don't change).
  // 
  // method 1: by index
  if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0"); 
  if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1"); 

  // method 2: search()
  // search() looks for the next device. Returns 1 if a new address has been
  // returned. A zero might mean that the bus is shorted, there are no devices, 
  // or you have already retrieved all of them.  It might be a good idea to 
  // check the CRC to make sure you didn't get garbage.  The order is 
  // deterministic. You will always get the same devices in the same order
  //
  // Must be called before search()
  //oneWire.reset_search();
  // assigns the first address found to insideThermometer
  //if (!oneWire.search(insideThermometer)) Serial.println("Unable to find address for insideThermometer");
  // assigns the seconds address found to outsideThermometer
  //if (!oneWire.search(outsideThermometer)) Serial.println("Unable to find address for outsideThermometer");


  // show the addresses we found on the bus
  Serial.print("Device 0 Address: ");
  printAddress(insideThermometer);
  Serial.println();

  Serial.print("Device 1 Address: ");
  printAddress(outsideThermometer);
  Serial.println();
  

  // set the resolution to 9 bit
  sensors.setResolution(insideThermometer, 10);
  sensors.setResolution(outsideThermometer, 10);

  Serial.print("Device 0 Resolution: ");
  Serial.print(sensors.getResolution(insideThermometer), DEC); 
  Serial.println();

  Serial.print("Device 1 Resolution: ");
  Serial.print(sensors.getResolution(outsideThermometer), DEC); 
  Serial.println();
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  Serial.print("Temp C: ");
  Serial.print(tempC);
   Serial.println("Entered loop");
if (!connected){ 
   Serial.println("Not connected");
  if (client.connect()){
      connected = true;
      Serial.println("Connected to Server");
      Serial.println("Sending request to server");
      client.print("GET /writetemplocalserv.php?t1=");
      client.print(tempC);
      client.println(" HTTP/1.1");
      client.println("Host: ");
      client.println("User-Agent: Arduino");
      client.println("Accept: text/html");
      client.println();
     } else {
        Serial.println("Cannot connect to server");
      }
    }   
  else {
    delay(500);
    while (client.connected() && client.available()) {
        char c = client.read();
        Serial.print(c);
      }
      Serial.println();
       client.stop(); 
       connected=false;
}
 
  Serial.println("Done now");
  delay(300000);

}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();    
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println(" ");
}

void loop(void)
{ 
  // call sensors.requestTemperatures() to issue a global temperature 
  // request to all devices on the bus
  //Serial.print("Requesting temperatures...");
  sensors.requestTemperatures();
  //Serial.println("DONE");

  // print the device information
  printData(insideThermometer);
  printData(outsideThermometer);
  Serial.println(" ");
  


  //delay(100);
}

I now would like to understand everything i write and tried to write a very simple code for multiple sensors. It´s looking like that:

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

#define one_wire_bus 7
#define temp_precision 9

//------------------------------------------------------//
// ethernet section//

//mac-adress of arduino board
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// IP-adress of arduino board
byte ip [] = {192, 168, 0, 17};
//IP-adress of router
byte gateway[] = {192, 168, 0, 1};
//subnet-mask (optional)
byte subnet[] = {255, 255, 255, 0};
//IP-adress of server to call .php-script
byte serverIP[] = {192, 168, 0, 4};

Client client(serverIP,80);


OneWire oneWire(one_wire_bus);
DallasTemperature sensors(&oneWire);

bool connected = false;

float temp=0;
int i;

void setup()
{
  Ethernet.begin(mac, ip);            
  Serial.begin(9600);
  sensors.begin();
}


void loop()
{
if (!connected) 
      {
            Serial.println("Not connected");

      if      (client.connect()){
            connected = true;
            Serial.println("connected to server");
            Serial.println("sending request to server");
            
      
 
  for (i=0; i<2; i++){
    sensors.requestTemperatures();
    temp=sensors.getTempCByIndex(i);
    client.print("GET /writetemplocalserv.php?t");
    client.print(i);
    client.print("=");
    client.print(temp);
    client.println(" HTTP/1.1");
    client.println("Host: www.jfkreuter.com");
    client.println("User-Agent: Arduino");
    client.println("Accept: text/html");
                    }
                                 }
  else {
        Serial.println("cannot connect to server");
       }      
  }
}

The code compiles and i can upload it, but there are no new temps in the table…

Serial console says :

“Not connected
connected to server
sending request to server”

the PHP code:

<?php
header('Content-type: text/plain');
echo date("d.m.Y-H:i:s") . " Temperatur= " . $_GET['t1'];
 
$link = mysql_connect("localhost", "login", "password") or die("Keine Verbindung möglich: " . mysql_error());
mysql_select_db("table1") or die("Auswahl der Datenbank fehlgeschlagen");
$query = "INSERT INTO table1(`temp1`) values(" . $_GET['t1'] . ")";
$result = mysql_query($query) or die("Anfrage fehlgeschlagen: " . mysql_error());
 
mysql_close($link);
?>
mysql_select_db("table1")

"table1" should not be a table, but a data*b*ase :)

I suppose his database could be named "table1" - but that would be odd...

:)

Hey Guys, thanks for the replies. It posted the wrong php-script. The name of the database is “tempdb”. To name a database with “table1” would be strange :wink:
The script is :

<?php
header('Content-type: text/plain');
echo date("d.m.Y-H:i:s") . " Temperatur1 = " . $_GET['t1'];
//echo date("d.m.Y-H:i:s") . " Temperatur2 = " . $_GET['t2'];
 
$link = mysql_connect("localhost", "user", "password") or die("Keine Verbindung möglich: " . mysql_error());
mysql_select_db("tempdb") or die("Auswahl der Datenbank fehlgeschlagen");
$query = "INSERT INTO table1(`temp1`) values(" . $_GET['t1'] . ")";
//$query = "INSERT INTO table1(`temp2`) values(" . $_GET['t2'] . ")";
$result = mysql_query($query) or die("Anfrage fehlgeschlagen: " . mysql_error());
 
mysql_close($link);
?>

The php works somehow…I just wanted to get a “not so messy” arduino-code to work to read and send data from multiple sensors. Maybe i have to refine the php after but i want to start with the arduino-code. Anyway thx for the answers. Maybe someone managed it to get the setup i want to have to run and i just didn´t found it on the Web…If somebody has a link, i wolud be happy also. I´m ready to put some work in it :wink:

Hey folks, its Jean Herbes ;) I changed my name so that my "web personality" becomes more consistent.

I somehow figured out how everything should be coded an wrote an article about my project. It Works Now!

You can see the blogpost here: http://blog.jfkreuter.com/

Feel free to ask via PN or Mail.

Greetings

jfkreuter aka Jean Herbes

Nice project jfkreuter!

I didn't realise that you didn't have to print the url in one statement. Stupid of me really, but it's given me an idea of how to do something far easier than I'd imagined.

Hey Folks,

Just wanted everybody to know that i have updated the code so it will work with more than just one sensor. The website is the same (blog.jfkreuter.com)

have a nice evening!

Jan

Hi there. I’m trying to build a prototype of a system that allows users to move library books around a building, and register where they are by swiping them on RFID readers. I have the LAMP stack down, and also the code for reading RFID tags with the Parallax RFID reader, and accessing the internet with the Ethernet Shield.

I’ve been trying to adapt your code to be able to send GET requests to the internet only when the RFID reader reads a novel tag (until my hosting company sorts me out a dedicated IP this is the best I can do for getting this code to work), but I cannot seem to get the ethernet and RFID code to work together.

It just outputs “Cannot connect to server”, and only once (when it should say that every time it reads a novel tag and goes through the IF/ELSE of trying to send that tag’s data to the internet.

Sorry! Code is below:

// adapted from jfkreuter.com/?p=80#more-80 - 2010/07/30

#include <Ethernet.h>           //library for ethernet functions
#include <Client.h>             //library for client functions

// RFID settings
int val = 0;
char lastValue[10];
char tagValue[10]; 
int bytesread = 0; 
// Ethernet settings
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xBA, 0xBE}; // mac-adress of arduino
byte ip[] = { 192, 168, 0, 2 };                     // IP-adress of arduino
byte server[] = { 209, 85, 135, 105 };              // Google

Client client(server, 80);         

void setup()                                  
{
  Serial.begin(2400);                               // start the serial port
  delay(1000);
  Serial.println("connecting...");

  Ethernet.begin(mac, ip);                  // start up ethernet
  pinMode(2,OUTPUT);                        // pin 2 is the output to the reader
  digitalWrite(2,LOW);                      // ... and now the reader has been actived

  if (client.connect()) 
  {
    Serial.println("connected");
    //client.println("GET /search?q=arduino HTTP/1.0");
    client.println();
  } 
  else 
  {
    Serial.println("connection failed");
  }
}
//----------------------------------------------------------------------------------------------------------
void loop(void)                     // loop function (runs over and over again)
{
  if(Serial.available() > 0)                // if data available from reader 
  {
    if((val = Serial.read()) == 10)         // check for header 
    {
      bytesread = 0; 
      while(bytesread<10)                   // read 10 digit code 
      {
        if( Serial.available() > 0) 
        {
          val = Serial.read(); 
          if((val == 10)||(val == 13))       // if header or stop bytes before the 10 digit reading 
          {
            break;                           // stop reading 
          }  
          tagValue[bytesread] = val;         // add the digit           
          bytesread++;                       // ready to read next digit  
        } 
      } 
      if(bytesread == 10)                    // if 10 digit read is complete 
      {
        if ((tagValue[0] == lastValue[0]) && 
          (tagValue[1] == lastValue[1]) && 
          (tagValue[2] == lastValue[2]) && 
          (tagValue[3] == lastValue[3]) && 
          (tagValue[4] == lastValue[4]) && 
          (tagValue[5] == lastValue[5]) && 
          (tagValue[6] == lastValue[6]) && 
          (tagValue[7] == lastValue[7]) && 
          (tagValue[8] == lastValue[8]) && 
          (tagValue[9] == lastValue[9]))
        {
          /* do... nothing                       this tests for a non-novel tag */
        }
        else
        {
          if (client.connect())
          {
            client.print("GET /search?q=arduino HTTP/1.0");
            Serial.print("GET /search?q=arduino HTTP/1.0");
            /*
            client.print("GET /changeTagLocation.php?targetLocation=2&targetTag=");
            Serial.print("GET /changeTagLocation.php?targetLocation=2&targetTag=");
            client.print(tagValue);
            Serial.print(tagValue);
            client.println(" HTTP/1.0");
            Serial.println(" HTTP/1.0");
            client.println("Host: www.thisishere.net");
            Serial.println("Host: www.thisishere.net");
            client.println("User-Agent: Arduino");
            Serial.println("User-Agent: Arduino");
            client.println("Accept: text/html");
            Serial.println("Accept: text/html");
            client.println("Connection: close");
            Serial.println("Connection: close");
            */
            client.println();
            Serial.println();
          }
          else
          {
            Serial.println("Cannot connect to Server");         //  else block if the server connection fails (debugging)
          }
          Serial.println();
          client.stop();                                              //  stop the connection and set
          delay(598400);
        }
      }
    }
  }
}

You are comparing the tag that was just read to lastValue, which never seems to be assigned (or reassigned) a value.

If there is no match, you try to connect to the database (using Google's IP address, according to the comments). Is the server and ip address actually reachable?

After that succeeds or fails, you disconnect and delay for nearly 10 minutes. Why?