我一直在尝试将我的 Arduino 成功连接到我的 phpMyAdmin 服务器,但我无法做到。Arduino 连接了一些超声波传感器(用于测量距离),由于某种原因,并非所有值都被发送到服务器。我不应该这么复杂。
因此,每个传感器都有自己的 id、测量距离和传感器所在的级别。
id 是为了识别传感器(duh!),但由于某种原因,我得到的只是这个值的 0,我认为这是因为它只读取第一个传感器的值(id 为 0)。
所以让我给你看我的代码,这是重复的方法,我认为我的错误是无法多次发送信息,比如将信息与每个传感器分开,它只发送前 4 个值,就是这样显示在数据库中。
void loop(){
int distance;
//=======
for (uint8_t i = 0; i < SONAR_NUM; i++) {
if( cm[i] > 10 || cm[i]==0){
distance = cm [i];//delete if no
}
else{
distance = cm[i];
//Serial.println(distance);
}
}
for (uint8_t i = 0; i < SONAR_NUM; i++) {
if (millis() >= pingTimer[i]) {
pingTimer[i] += PING_INTERVAL * SONAR_NUM;
if (i == 0 && currentSensor == SONAR_NUM - 1)
sonar[currentSensor].timer_stop();
currentSensor = i;
cm[currentSensor] = 0;
sonar[currentSensor].ping_timer(echoCheck);
}
//client.stop();
}
//===================================================
if(client.connect(serverName, 80) )
{
//Serial.println("Connected");
if (client.connected()){
delay(100);
//Serial.println("Client is available, CONNECTED!");
//client.print( "GET /add.php?distance=");
//////////////
int lvl = 0;
for (uint8_t i = 0; i < SONAR_NUM; i++) {
if(i<2)
lvl = 1;
else if (i>1 && i<3)
lvl =2;
else
lvl = 3;
Serial.print("SPOT: ");
client.print( "GET /sendfromarduino.php?sensorID=");
Serial.print(i);
client.print (i);
Serial.print(" DISTANCE: ");
Serial.print(cm[i]);
distance = cm[i];
client.print( "&value=");
client.print(distance);
Serial.print("cm ");
Serial.print(" LEVEL: ");
client.print( "&level=");
Serial.print (lvl);
client.print (lvl);
}
Serial.println();
//////////////////////////////////////
// Serial.print("Distance: ");
// client.print(distance);
// Serial.println(distance);
client.println( "HTTP/1.1");
client.println( "Host: test.testserver.com" );
client.println( "Content-Type: application/x-www-form-urlencoded" );
client.println();
client.println();
client.stop();
}
else
{
//Serial.println(distance);
Serial.println("Connection Failed");
}
}
delay(100);
}
然后这里是PHP文件的代码,根据我的知识和过去的经验应该是完全可以的:
<?php
$db = new PDO('mysql:host=localhost;dbname=test_alpha;charset=UTF-8', 'test_alpha', 'testtest');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sensorID = intval($_GET['i']);
//$time = CURRENT_TIMESTAMP;
$value = intval($_GET['distance']);
$level = intval($_GET['lvl']);
$sql = "INSERT INTO `pspace`(`sensorID`, `time`, `value`, `level`) VALUES ('$sensorID',CURRENT_TIMESTAMP,'$value','$level')";
$stmt = $db->query($sql);
//echo json_encode(array('spaces'=>$stmt->fetchAll(PDO::FETCH_ASSOC)));
?>
任何帮助是极大的赞赏!