17.serial read write 1
ตัวอย่างการให้ Arduino ส่งข้อมูลออกทางพอร์ทอนุกรมตามขำขอ
การทำงาน
1. Arduino จะตรวจสอบว่ามีข้อมูลเข้ามาทางพอร์ทอนุกรมหรือไม่มีก็อยู่ที่ข้อ 1 ถ้ามีไปข้อ 2
2. ตรวจว่าข้อมูลเข้ามาเป็นตัวอักษร '1' หรือไม่ ถ้าไม่ใช้กลับไปข้อ 1 ถ้าใช้ไปข้อ 3
3. อ่านข้อมูลจากพอร์ทอนาลอก แล้วส่งออกทางพอร์ทอนุกรม เสร็จแล้วกลับไปข้อ 1
โปรแกรม
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
int incomingByte = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 0)
{
incomingByte = Serial.read();
if(incomingByte=='1')
{
sensorValue = analogRead(sensorPin); // read the value from the sensor:
Serial.println(sensorValue);
}
}
}
เมื่อ run โปรแกรม
เมื่อพิมพ์เลข 1 ลงในช่อง send ฤพกีืน จะตอบกลับ
ตัวอย่างถัดไป ดูการประยุกต์ใช้กับ Processing ที่ Serial to graph 3