水的結冰溫度實驗
[材料]
[材料]
Arduino主板 x 1
麵包板 x 1
DS18B20防水型溫度感測器 x 1
wifi ESP8266 x 1
步驟一:僅有溫度感測器
[DS18B20防水型溫度感測器 腳位]
[DS18B20防水型溫度感測器 腳位]
紅色線VCC --> arduino 5V
黑色線GND --> arduino GND
藍色線data --> arduino pin2
藍色線data --> 47KΩ的電阻(也可用兩個100KΩ的電阻並聯取代) --> arduino 5V
[DS18B20防水型溫度感測器 函式庫]
[DS18B20防水型溫度感測器 函式庫]
https://github.com/milesburton/Arduino-Temperature-Control-Library
程式碼1 (僅有溫度感測器,數據顯在電腦上)
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature watersensor(&oneWire);
float watertemp;
void setup()
{
Serial.begin(9600);
watersensor.begin();
}
void loop() {
watersensor.requestTemperatures();
watertemp = watersensor.getTempCByIndex(0);
Serial.print("Temperature is: ");
Serial.print(watertemp);
Serial.println(" *C");
delay(100);
}
步驟二、溫度感測器 + WIFI模組
注意:WIFI模組要接到3.3V,以免燒壞。
程式碼2 (透過wifi上傳至ThingSpeak)
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature watersensor(&oneWire);
float watertemp;
#include <SoftwareSerial.h>
SoftwareSerial esp8266(4,5);
String apiKey = ""; // ""內輸入ThingSpeak的Write API Key
String ssid = ""; // ""內輸入wifi基地台的名稱
String password = ""; // ""內輸入wifi基地台的密碼
boolean DEBUG = true;
void showResponse(int waitTime){
long t=millis();
char c;
while (t+waitTime>millis()){
if (esp8266.available()){
c=esp8266.read();
if (DEBUG) Serial.print(c);
}
}
}
boolean thingSpeakWrite(float value1){ //自己增加或減少要上傳的數據項目
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "184.106.153.149";
cmd += "\",80";
esp8266.println(cmd);
if (DEBUG) Serial.println(cmd);
if(esp8266.find("Error")){
if (DEBUG) Serial.println("AT+CIPSTART error");
return false;
}
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr +="&field1=";
getStr += String(value1);
getStr += "\r\n\r\n";
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
esp8266.println(cmd);
if (DEBUG) Serial.println(cmd);
delay(100);
esp8266.print(getStr);
if (DEBUG) Serial.print(getStr);
else{
esp8266.println("AT+CIPCLOSE");
if (DEBUG) Serial.println("AT+CIPCLOSE");
return false;
}
return true;
}
void setup()
{
Serial.begin(9600);
Serial.println("Arduino...OK");
esp8266.begin(115200);
esp8266.write("AT+UART_DEF=9600,8,1,0,0\r\n");
delay(1500);
esp8266.begin(9600);
Serial.println("ESP8266...OK");
esp8266.println("AT+CWMODE=1"); // set esp8266 as client
showResponse(1000);
esp8266.println("AT+CWJAP=\""+ssid+"\",\""+password+"\"");
showResponse(10000); //顯示並等待wifi完成連線
watersensor.begin();
}
void loop() {
watersensor.requestTemperatures();
watertemp = watersensor.getTempCByIndex(0);
Serial.print("Temperature is: ");
Serial.print(watertemp);
Serial.println(" *C");
thingSpeakWrite(watertemp);
delay(20000);
}