這年頭, 不管是哪種專案 都應要跟cloud 扯上關係. 那自動化也要跟雲搭上邊囉 ...
這篇要簡單介紹如何多一塊板子在便宜的Arduino 上就可以有網路服務
筆者手邊有的主板是 arduino leonardo
PS: 這款沒有支援網路功能
要讓這主板能夠上網, 最快的方式就是連接一塊有上網功能的擴充板
PS: 筆者使用的擴充板是W5100
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEC };
IPAddress ip(192,168,50,177);
// Initialize the Ethernet server library
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;
}
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server IP: ");
Serial.println(Ethernet.localIP());
}
void loop() {
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
引用自 demo source code
server IP: 192.168.50.177
結論:
現在要把資料自動上傳到雲端做後處理是非常容易的, 使用Arduino 擴充板把資料上傳雲端需要注意網路模組是否會容易當掉. 筆者之前接的案子中就有遇過, 因為firmware寫太糟導致擴充板的網路模組會常態性當掉, 必須要人為去按下Reset 重置後才能使用
有些擴充板上面是有EEPROM 可以存一些網路層的資訊在裏頭, 這篇沒有實作出來. 有興趣的朋友可以另行研究
參考資料: