開始前的測試
首先,下載這個簡單的程式,你可以透過它和 ThingSpeak.com 從事簡單的聯繫:
https://drive.google.com/file/d/0B2ZbLCPalrgEZWZjNWMxYjYtZTZmYS00YTExLThkNWYtYzI0ZjYxYWY4YzRm/view?ddrp=1&hl=en#
你可以用鍵盤隨便打幾個數字,這些數字將會被上傳到 ThingSpeak.com,如果出現下列畫面表示可以正常工作。
上傳光線感測數據
在這兒我們會使用 LDR 去偵測光線的強度,請依照下列電路圖在麵包板上插妥零件與接線。
底下這個程式很簡單,它單純地只是把 A0 腳位的值透過序列埠傳送出去,程式如下:
void setup(){ Serial.begin(9600); } void loop(){ Serial.println(analogRead(0)); delay(2000); }
請您將上述程式複製並貼到 Arduino IDE 裡,並上傳到板子。
接收數據
我們要用 Processing 來接收這些數據,需要變更一些程式碼,如下:
/**
* Tests the thinkspeak channel by sending any numeric
* keypress using the specified APIKEY and FIELD
*/
import processing.serial.*;
import processing.net.*;
//CONFIGURATION
String APIKEY = "YOURAPI"; //your api key
String FIELD = "field1";
int PORTNUM = 0; //port number of your arduino
//END CONFIGURATION
Serial arduino;
Client c;
String data;
int number; //read from arduino
void setup() {
size(600, 400);
//setup the serial port
// List all the available serial ports:
println(Serial.list());
//Init the Serial object
arduino = new Serial(this, Serial.list()[PORTNUM], 9600);
// The font must be located in the sketch's
// "data" directory to load successfully
PFont font;
font = loadFont("Monaco-12.vlw");
textFont(font);
}
void draw() {
background(50);
fill(255);
text("ThinkSpeak Processor", 10, 20);
fill(0, 255, 0);
text("Light Value Read: " + number, 10, 40);
if( data != null ) {
fill(0, 255, 0);
text("Server Response:", 10, 60);
fill(200);
text(data, 10, 80);
}
if(c != null) {
if (c.available() > 0) { // If there's incoming data from the client...
data = c.readString(); // ...then grab it
println(data);
}
}
//if we have a new line from our arduino, then send it to the server
String ln;
if( (ln = arduino.readStringUntil('\n')) != null) {
try {
number = new Integer(trim(ln));
if(number < 1025) {
println("Writing " + number);
sendNumber(number);
}
}
catch(Exception ex) {
}
}
}
void sendNumber(float num) {
c = new Client(this, "api.thingspeak.com", 80); // Connect to server on port 80
c.write("GET /update?key="+APIKEY+"&"+FIELD+"=" + num + " HTTP/1.1\n");
c.write("Host: my_domain_name.com\n\n"); // Be polite and say who we are
}
如果你看到下列畫面,其中 Light Value Read:的值每 2 秒跳動一次,那麼恭喜你,你成功了。
沒有留言:
張貼留言