Arduino Polska Forum

Pełna wersja: problem z kodem
Aktualnie przeglądasz uproszczoną wersję forum. Kliknij tutaj, by zobaczyć wersję z pełnym formatowaniem.
Witam stworzyłem kod który to ma odczytywać dane z odbiornika i przesyłać je do mysqla, lecz coś nie działa. Oto kod:

Kod:
#include <Wire.h>
#include <Streaming.h>  // http://arduiniana.org/libraries/streaming/
#include <SPI.h>
#include "RTClib.h"
#include <Ethernet.h>
#include <SoftwareSerial.h>
#include "I2C.h" //I2C Library can be downloaded below
RTC_DS1307 RTC;
const byte numChars = 40;
char receivedChars[numChars];
char tempChars[numChars];
String fTemp, fPress, fwil, fpomiar, iilosc;
boolean newData = false;
static unsigned long NowMillis = 0;
static unsigned long LastMillis = 0;
static unsigned long LoopMillis = 0;
int mies;
String data;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL
   SoftwareSerial HC12(53, 54); // HC-12 TX Pin, HC-12 RX Pin
 

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192,168,0,107";
IPAddress ip(192,168,0,177);
   EthernetClient client;
   void setup() {
if (client.connect(server, 80)) {
   Serial.println("connected");


  Serial.begin(9600);             // Serial port to computer
     HC12.begin(9600);    
      Wire.begin();
   RTC.begin();
 // Check to see if the RTC is keeping time.  If it is, load the time from your computer.
 if (! RTC.isrunning()) {
   Serial.println("RTC is NOT running!");
   // This will reflect the time that your sketch was compiled
   RTC.adjust(DateTime(__DATE__, __TIME__));
   
 }  
   }
   }
void loop() {
      recvWithStartEndMarkers();
 if (newData == true) {
   strcpy(tempChars, receivedChars);  // this temporary copy is necessary to protect the original data
                                          // because strtok() used in parseData() replaces the commas with \0
   parseData();  // Strip required data out of received string
   
 
   showParsedData();
   newData = false;

 }
}
void recvWithStartEndMarkers() {
 static boolean recvInProgress = false;
 static byte ndx = 0;
 char startMarker = '<';
 char endMarker = '>';
 char rc;

 while (HC12.available() > 0 && newData == false) {
   rc = HC12.read();
   if (recvInProgress == true) {
     if (rc != endMarker) {
       receivedChars[ndx] = rc;
       ndx++;
       if (ndx >= numChars) {
         ndx = numChars - 1;
       }
     }
     else {
       receivedChars[ndx] = '\0';
       recvInProgress = false;
       ndx = 0;
       newData = true;
     }
   }
   else if (rc == startMarker) {
     recvInProgress = true;
   }
 }
}

void parseData() {  // split the data into its parts

 char * strtokIndx;  // this is used by strtok() as an index

 strtokIndx = strtok(tempChars,",");  // Get the first part of the data
 fTemp = atof(strtokIndx);

 strtokIndx = strtok(NULL, ",");  // this continues where the previous call left off
 fPress = atof(strtokIndx);

 strtokIndx = strtok(NULL, ",");
 fwil = atof(strtokIndx);

 strtokIndx = strtok(NULL, ",");
 fpomiar = atof(strtokIndx);

 strtokIndx = strtok(NULL, ",");
 iilosc = atol(strtokIndx);
 }
 void showParsedData() {

   DateTime now = RTC.now();
   
   
 
    Serial.print(now.month(), DEC);
   
   Serial.print('/');
   Serial.print(now.day(), DEC);
   Serial.print('/');
   Serial.print(now.year(), DEC);
   Serial.print(' ');
     Serial.print(now.hour(), DEC);
   Serial.print(':');
   Serial.print(now.minute()-23, DEC);
   Serial.print(':');
   Serial.print(now.second(), DEC);
   Serial.print(" : T ");
 Serial.print(fTemp);
 Serial.print(" : Pr ");
 Serial.print(fPress);
 Serial.print(" : wil ");
 Serial.print(fwil);
 Serial.print(" : pomiar ");
 Serial.print(fpomiar);
 Serial.print(" : ilosc ");
 Serial.print(iilosc);
Serial.print('/t');
LastMillis = NowMillis;
 NowMillis = millis();
 LoopMillis = NowMillis - LastMillis;
   Serial.print(" : LoopTime ");
   Serial.println(LoopMillis);
   delay(500);
//-------------------------------------------------

data = "temp=" + fTemp + "|" + fwil + "|" + fPress;
  if (client.connect(server, 8080)) {
   client.print("GET /add.php?"); // This
   client.print("value="); // This
client.print(data); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
   client.println(" HTTP/1.1");
   client.println("Host: 192.168.0.107");
   client.println("Connection: close");
  client.println(); // Empty line
   client.println(); // Empty line
   client.stop();    // Closing connection to server

  }else {
   // If Arduino can't connect to the server (your computer or web page)
   Serial.println("--> connection failed\n");
 }
//--------------------------------------------------

 }
 
Witam
Przesłanie czegoś do MySQL składa się z trzech części - kod Arduino, skrypt PHP, odpowiednia baza MySQL. Pokazujesz 1/3 i to nadziubdziane wiele niepotrzebnych rzeczy na okazję samego MySQL. Napisz sobie jakikolwiek minimalny szkic wysyłający coś do Twojej bazy, nie musisz przecież wysyłać rzeczywistych rzeczy, jak to zadziała to rozbudowuj sobie dalej od strony tego co chcesz mierzyć i archiwizować w bazie. A w szczególności jak to jest serwer to znacznik czasu możesz wstawiać automatycznie w bazie danych. Na razie zgraj Arduino/PHP/MySQL. Samo wysłanie do MySQL to 1 linijka: client.print();
Przykład działający na ESP8266:
Kod:
#include <ESP8266WiFi.h>
const char* ssid= "SSID";
const char* password = "HASLO";
const int httpPort = 80;
const char* host = "IP"; //IP serwera z MySQL
float temp=22.26, humidity=35.33;
 

void setup() {
 Serial.begin(115200);
 WiFi.begin(ssid, password);  
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
Serial.println(WiFi.localIP());
}
void loop() {
 Serial.println(temp);  
 
 temp+=1.02; //zmieniamy wartości do bazy danych dla lipy
 humidity+=1.05;  
 if(temp>40)
 {
   temp=21.26;
   humidity=34.33;
 }

  WiFiClient client; //wysylanie do PHP i MySQL
  if (!client.connect(host, httpPort)) {
   Serial.println("connection failed");
   
 }
 else
 {
String url = "/esp.php?";
   url += "id=1";
   url += "&t=";
   url += temp;
   url += "&h=";
   url += humidity;
 client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");  
 }
 delay(5000);              
}

Do tego musi być skrypt na serwerze esp.php z:
Kod:
<?php
define ('DBHOST', 'localhost:3306)');
define ('DBNAME', 'esp'); // nazwa bazy danych
define ('DBUSER', 'USER'); // nazwa usera ustawic w PHPMYADMIN
define ('DBPASS', 'HASLO'); // haslo usera ustawic w PHPMYADMIN
/* Laczenie z baza danych */
mysql_connect(DBHOST, DBUSER, DBPASS) or die('Nie polaczono!');
mysql_select_db(DBNAME) or die ('Brak polaczenia z baza danych!');
mysql_query('SET NAMES utf8');

$id = ($_GET['id']);
$temp = ($_GET['t']);
$hum = ($_GET['h']);

if ($id == '1') {
    $total = mysql_result(mysql_query("SELECT count(*) FROM `esp1`"),0);
    mysql_query("INSERT INTO `esp1` (temp,hum) values ('".$temp."','".$hum."') ");
}
echo 'Ок';
?>
I baza danych  MySQL powinna już być z polami jak w skrypcie, baza esp z tabelą esp1, a w tabeli ID, temp, hum + ewentualnie znacznik czasu. Tutaj to małe id==1 to po to, bo można w jednym skrypcie PHP ładować dane do kilku tabel (np. trzy ESP ładują każde do swojej tabeli tym skryptem, a potem inny skrypt pokazuje łącznie wszystkie dane na stronie WWW).
 Milej zabawy.