วัตถุประสงค์ ต้องการรับข้อมูลที่เป็นตัวเลขจุดทศนิยมจากพอร์ทอนุกรม
วิธีการ
ตัวส่งข้อมูลต้องทำดังนี้
ตัวเลขที่ต้องการรับ เป็นเลขทศนิยม 1 ตำแหน่ง N ที่มีค่าอยู่ในช่วง 0 ถึง 899.9 เช่น N = 25.6
นำเลขนั้นมาคูณด้วย 10 N = Nx10 = 256
บวกค่า N ด้วย 1000 เพื่อทำให้เป็นเลขจำนวนเต็ม 4 หลัก เช่น N = N+1000 = 256+1000 = 1256
ส่งออกทางพอร์ทอนุกรมแบบตัวหนังสือ เช่นใช้คำสั่ง println
จะเห็นได้ว่า ไม่ว่า N จะมีค่าเท่าไร (ตามย่านที่กำหนด) การส่งจะเป็นตัวอักขร 4 ตัวเสมอ
ด้าน Arduino ที่เป็นฝ่ายรับ จะทำดังนี้
รับข้อมูลจากพอร์ทอนุกรม มาเก็บเป็นอะเรย์ของตัวอักขระ
นำอักขระ 4 ตัวมาแปลงเป็นเลขจำนวนเต็มด้วยฟังก์ชั่น atoi()
ลบค่าตัวเลขนั้นด้วย 1000
แปลงตัวเลขเป็นค่า Floating point แล้วหารด้วย 10 จะได้ค่าเดิมคืนมา
เช่นรับอะเรย์ของตัวอักขระได้เป็น inString = "1256"
แปลงเป็นเลขจำนวนเต็ม number = atoi(inString);
ลบค่าตัวเลขนั้นด้วย 1000
แปลงตัวเลขเป็นค่า Floating point แล้วหารด้วย 10
fnum = (float)(number-1000)/10;
-------------------------------------------------------------------------------------------------
โปรแกรม
// Read a text received on serial arduino port
// text = number*10+1000
// text length = 4
// and convert tex to number
#define INLENGTH 4
#define lf 10
#define cr 13
char inString[16];
int inCount;
int incomingByte = 0;
int number;
float fnum;
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH); // set the LED on
}
void loop()
{
}
void serialEvent()
{
inCount = 0;
do
{
while (!Serial.available()); // wait for input
inString[inCount] = Serial.read(); // get it
if ((inString [inCount] == cr)||(inString [inCount] == lf)) break;
++inCount;
} while(inCount < INLENGTH);
inString[inCount] = 0; // null terminate the string
number = atoi(inString);
fnum = (float)(number-1000)/10;
Serial.println(inString);
Serial.println(fnum);
}
ตัวอย่าง ป้อน 8953 รับและแสดงผลเป็น 795.30