25-รับส่งข้อมูลแบบ int ระหว่าง arduino กับ Processing
การส่งข้อมูลมากกว่า 8 บิต วิธีหนึ่ง ใช้การรับ-ส่งข้อมูลเป็น string
โดยทางฝั่ง Arduino ส่งข้อมูลด้วยคำสั่ง println
ทางฝั่ง processing รับด้วยคำสั่ง readStringUntil(lf);
แล้วค่อยแปลงเป็นเลข floating point
หลังจากนั้นก็แปลงจาก floating point เป็น int ก็ได้
ดูตัวอย่าง
====================================
โปรแกรมของ Arduino
int analogPin = 0;
int x;
int val = 2460;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
for (int i = 1000;i<1024;i++)
{
Serial.println(i);
delay(1000);
}
}
ตัวอย่างนี้ให้ Arduino ส่งเลข 1000 ถึง 1024 ด้วยคำสั่ง println
---------------------------
โปรแกรมของ Processing
import processing.serial.*;
int lf = 10; // Linefeed in ASCII
String myString = null;
Serial myPort; // The serial port:
float f;
void setup() {
println(Serial.list()); // List all the available serial ports:
myPort = new Serial(this, Serial.list()[1], 9600);
}
void draw(){
while (myPort.available() > 0) {
myString = myPort.readStringUntil(lf);
if (myString != null) {
f = Float.parseFloat(myString);
println(f); // f = floating
println(int(f)); // แปลง float เป็น int ด้วย int( )
}
}
}
ตามตัวอย่างนี้จะได้ f เป็นตัวเลข floating นำไปใช้งานได้
หรือถ้าจะแปลงเป็น int ก็ใช้ int(f)
แบบนี้มีข้อดีคือใช้ serial monitor ดูการทำงานได้ เพราะข้อมูลที่สื่อสารกันเป็น string