通过WiFi将arduino传感器数据发送到MySQL服务器

时间:2020-06-24 16:32:31

标签: arduino

我知道这个问题可能已经问过很多遍了,但是我正在拔头发。

我正在尝试从arduino到MySQL服务器获取传感器数据。我已经检查了apache访问日志,请求在那里。但是它只是没有被插入数据库中。使用浏览器手动添加数据是可行的,因此php代码看起来不错。我已经允许apache通过防火墙并更新了权限。下面的代码:

Arduino主要代码:

#include "thingProperties.h"
#include <Arduino_MKRENV.h>
#include <WiFi.h>


WiFiClient client;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);
  
  //Connect to WiFi network
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID);
    status = WiFi.begin(SSID, PASS);
    delay(10000);
  }
  Serial.println("This is connected.");

  if (!ENV.begin()) {
  Serial.println("Failed to initialize MKR ENV shield!");
  while(1);
  }
  pinMode(2, INPUT);
}

void loop() {
 relativeHumidity = int(ENV.readHumidity());
 lightIntensity = (ENV.readIlluminance());
 airPressure = int(ENV.readPressure(MILLIBAR));
 temperature = int(ENV.readTemperature());
 if(digitalRead(2) == LOW){
   rain = 1;
 }else if(digitalRead(2) == HIGH){
   rain = 0;
 }
 Serial.println("httpRequest");
 httpRequest();
 delay(10000);
}

void httpRequest(){
  // if there's a successful connection:
  if (client.connect(SERVER, 80)) {
    Serial.println("Connecting to server...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    Serial.println("GET /weather_data.php?);
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.print(" Host: ");
    client.println(SERVER);
    client.println();
    Serial.println("Added.");
  } else {
    Serial.println("Not connected.");
  }
  if (client.connected()){
    client.stop();
  }
} 

thingProperties.h:

#include <WiFi.h>
#include <SPI.h>
 
const char THING_ID[] = "c942a18f-7696-4431-952c-76eaea3214ea";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const char SERVER[]   = SECRET_IP;      // Server IP Address

int airPressure;
float lightIntensity;
float relativeHumidity;
bool rain;
float temperature;

0 个答案:

没有答案
相关问题