如標題所述我使用millis()來計時,我是打算用來計算設備開啟的時間,我的作法是如果設備開啟就抓取當前的millis(),設備關閉時在抓取一次millis(),之後再用關閉的millis()減掉開啟時的millis()來算出開啟多久,可是我測試不管開多少秒開啟前的millis()跟開啟後的millis()都只相差一點多秒,請問這個可能是甚麼原因?
硬體是使用esp32
以下是我的程式碼,這裡只有把抓到前後的millis()送到資料庫,計算的部分在其他程式,不過重點是上傳到資料表的數值都只差一秒多,有問題的部分是在Motor==on或off判斷的地方
#include <WiFi.h>
#include <ArduinoJson.h>
//#include <analogWrite.h>
#define light 35 //光敏電阻
//#define water_sensor 36 // 水位感測器
#define soil_sensor 33 //土壤濕度感測器
#define fannow 14 //通風風扇
#define watervalmotor 26 //抽水馬達(容器加水)
#define motornow 27 //抽水馬達(澆水)
/**************超音波測距模組*****************/
#define trigPin 5 //超音波測距模組
#define echoPin 18 //超音波測距模組
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
//float distanceCm;
float watervalue;
float distanceInch;
/*******************************************/
String Motor; //抽水馬達(澆水)變數
String WaterValMotor; //抽水馬達(容器加水)變數
String fan_cool; //通風風扇 變數
int Soilhumidity;//土壤濕度
int soilValue;
int soilMoisture;//定義土壤濕度
int watervalueint;
unsigned long MotorOpenTime=0; //澆水時間計算
unsigned long MotorOFFTime=0;
unsigned long MotorTime=0;
float opentimeF=0;
float timewatervalue=0; //秒數X水量
int MotorOff;
HardwareSerial myHardwareSerial(1);
static unsigned int co2 = 0;
static unsigned int ucRxBuffer[10];
const unsigned long HTTP_TIMEOUT = 10000;
const char* ssid = "myssid";
const char* password = "mypassword";
const char* host = "192.168.0.17";
const char* webpage= "sensor_control/Status_field2.php";
const char* webpageupdate= "sensor_control/AddData2.php?";
WiFiClient client;
void setup(){
pinMode(fannow, OUTPUT);
digitalWrite(fannow, HIGH);
pinMode(watervalmotor, OUTPUT);
digitalWrite(watervalmotor, HIGH);
pinMode(motornow, OUTPUT);
digitalWrite(motornow, HIGH);
pinMode(light, INPUT);
pinMode(soil_sensor,INPUT);
//pinMode(water_sensor,INPUT); //設置water_sensor對應的腳GPIO36為輸入
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(115200);
delay(500);
Serial1.begin(115200);
myHardwareSerial.begin(9600, SERIAL_8N1, 12, 13); //DS-Co2-20 GPIO Serial的TX,RX
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
delay(500);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
}
void loop(){
/***********************DS-CO2-20 Sensor**********************/
static uint32_t lasttime=millis();
byte request[] = {0x42, 0x4d, 0xe3, 0x00, 0x00, 0x01, 0x72};
Serial1.write(request, 7);
delay(500);
while (Serial1.available()){
for(int i=0; i<12; i=i+1){
ucRxBuffer[i]=Serial1.read();
}
co2 = ucRxBuffer[4]*256+ucRxBuffer[5];
Serial.print("ppm:");
Serial.println(co2);
}
/********************** 光敏電阻 ********************************/
int Light=analogRead(light); // 0 ~ 4096
//Serial.println(Light);
int LightVal = map(Light,0,4096,0,100); //換算 0~4096 成0~100
Serial.print("光照:");
Serial.println(LightVal);
delay(100);
/************************** 土壤感測器 ********************************/
soilValue = analogRead(soil_sensor); //讀取土壤感測器上的電壓值
Serial.print("土壤濕度:");
Serial.println(soilValue);
soilMoisture = map(soilValue,0,4096,100,0);//把電壓值按照[0,1023]映射到[100,0]
/******************************* 超音波測距模組(水位感測) ************************************/
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
//distanceCm = duration * SOUND_SPEED/2;
watervalue = duration * SOUND_SPEED/2;
// Convert to inches
//distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("watervalue (cm): ");
Serial.println(watervalue);
//Serial.print("Distance (inch): ");
//Serial.println(distanceInch);
/*********************************************************************************/
if (client.connect(host, 80)){
Serial.println("[Host connected]");
//Get the LED color
Serial.println("[Sending a request as:]");
client.print(String("GET /") + webpage + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n" +
"\r\n"
);
Serial.println(String("GET /") + webpage + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n" +
"\r\n");
int timeoutcnt=0;
while((!client.available()) && (timeoutcnt < 50)){
delay(200); //Use this with time out
timeoutcnt++;
}
//https://circuits4you.com/2017/12/09/thing-speak-esp8266/
//---------------------------------------------------------------------
//If data is available before time out read it.
if(timeoutcnt < 50){ // Check HTTP status
char status[32] = {0};
Serial.print(client);
client.readBytesUntil('\r', status, sizeof(status));
for (int i=0;i<32;i++)
Serial.print((char)status[i]);
Serial.println();
// It should be "HTTP/1.0 200 OK" or "HTTP/1.1 200 OK"
if (strcmp(status + 9, "200 OK") != 0){
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
// Skip HTTP headers
char endOfHeaders[] = "\r\n\r\n";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
// Allocate the JSON document
// Use arduinojson.org/v6/assistant to compute the capacity.
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(10) + 314;
DynamicJsonDocument jsondoc(capacity);
// Parse JSON object
DeserializationError error = deserializeJson(jsondoc, client);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
client.stop();
Serial.println("[Disconnected]");
// Extract value
String temperature = jsondoc[0]["Temp"];
Serial.print("Temperature = ");
Serial.println(temperature.toFloat());
String humidity = jsondoc[0]["Humidity"];
Serial.print("Humidity = ");
Serial.println(humidity.toFloat());
String Soilhumidity = jsondoc[0]["Soilhumidity"];
Serial.print("Soilhumidity = ");
Serial.print(Soilhumidity.toInt());
Serial.println("%");
String Motor = jsondoc[0]["Motor"];
Serial.print("Motor = ");
Serial.println(Motor);
String Co2 = jsondoc[0]["Co2"];
Serial.print("Co2 = ");
Serial.println(Co2);
String fan_cool = jsondoc[0]["fan_cool"];
Serial.print("fan_cool = ");
Serial.println(fan_cool);
String WaterValMotor = jsondoc[0]["WaterValMotor"];
Serial.print("WaterValMotor = ");
Serial.println(WaterValMotor);
String WaterValueHigh = jsondoc[0]["WaterValueHigh"];
Serial.print("WaterValueHigh = ");
Serial.println(WaterValueHigh);
/***********************************/
watervalueint = WaterValueHigh.toInt();
watervalue = watervalueint - watervalue;
Serial.print("水位高度 = ");
Serial.println(watervalue);
/****************************************設備開關判斷****************************************/
//timewatervalue = 0.0;
MotorOpenTime = 0;
if(Motor=="on"){
digitalWrite(motornow, LOW);
MotorOpenTime = millis();
Motor = "standby";
}else if(Motor=="off"){
digitalWrite(motornow, HIGH);
MotorOFFTime = 0;
MotorOFFTime = millis();
Motor = "end";
}
if(fan_cool == "on"){
digitalWrite(fannow, LOW);
//fan_cool = "on";
}else if(fan_cool == "off"){
digitalWrite(fannow, HIGH);
//fan_cool = "off";
}
delay(900);
/********************************************/
if (client.connect(host, 80)){
String dbserver = host;
String getStr = "GET /sensor_control/AddData2.php?";
getStr +="Co2=";
getStr += String(co2);
getStr +="&LightVal=";
getStr += String(LightVal);
getStr +="&Soilhumidity=";
getStr += String(soilMoisture);
if(Motor == "off" or Motor == "end"){
getStr +="&Motor=";
getStr += String("standby");
}
getStr +="&MotorOpenTime=";
getStr += String(MotorOpenTime);
getStr +="&MotorOFFTime=";
getStr += String(MotorOFFTime);
getStr +="&WaterValue=";
getStr += String(watervalue);
/*getStr +="&TimeWaterValue=";
getStr += String(timewatervalue);*/
getStr += " HTTP/1.1\r\n";
getStr += "Host: " + String(dbserver) \
+ "\r\n"+ "Connection: close\r\n\r\n";
Serial.println(getStr);
client.print(getStr);
delay(10);
client.stop();
}
/*******************************************/
/***********************************************************************************/
}else{
Serial.println("Request timeout..");
client.stop();
return;
}
}
else{
Serial.println("connection failed!]");
client.stop();
}
//delay(5000);
}