以下是Arduino用于从串口中的格式化文本一次提取两个整数的代码。格式为两个数字。每个后跟一个逗号,例如51,7,在读完后,它应该用它们做东西,然后循环回去再去,除非没有数据,那么它应该跳过if和do使用当前int值的东西。
void setup() {
Serial.begin(9600);
}
char rx_byte = 0;
String rx_str[2] = {""};
int nums[2] = {0}, a;
int PIN = 13;
boolean not_read = true;
void loop() {
if (Serial.available() > 0) { // is a character available?
memset(nums, 0, sizeof(nums));
rx_str[0] = "";
rx_str[1] = "";
a = 0;
while( a < 2 ){
not_read = true;
while(not_read){
rx_byte = Serial.read(); // get the character
if ((rx_byte >= '0') && (rx_byte <= '9')) {
rx_str[a] += rx_byte;
} // if ((rx_byte >= '0') && (rx_byte <= '9'))
else if (rx_byte == ',') {
not_read = false;
a++;
} // else if (rx_byte == ',')
} // while(not_read)
} // while(int a < 2)
nums[0] = rx_str[0].toInt();
nums[1] = rx_str[1].toInt();
} // if (Serial.available() > 0)
// do stuff with ints
} // void loop
当Arduino插入USB并且正确的数据输入串行监视器时,此工作正常。问题是,当数据是由c中的另一个程序写入时,使用带有HC-05-1模块的蓝牙,当没有数据时,arduino会挂在等待串行输入的if语句,而不是跳过并执行操作。下面是用于写入数据的C ++代码。
void right( double times[3] ) {
nums[0] = (int) times[0];
nums[1] = (int) times[1];
int bytes_written = 0; // bytes_read = 0;
printf( "\n nums[0]: %d ", nums[0]);
printf( "\n nums[1]: %d ", nums[1]);
sprintf( buf, "%d,%d,", nums[0],nums[1] );
printf( "\n writing ");
puts(buf);
bytes_written = write(s, buf, sizeof(buf));
printf("\n %d Bytes written to bluetooth", bytes_written);
printf("\n +----------------------------------+\n\n");
}
这是函数right()
nums[0]: 4
nums[1]: 2
writing 4,2,
15 Bytes written to bluetooth
+----------------------------------+
我不知道这是多么相关,但是当蓝牙和电路板没有上电时,这里有一些函数right()
的输出。
nums[0]: 16
nums[1]: 5
writing 16,5,
16,5,
15 Bytes written to bluetooth
+----------------------------------+
不确定额外的输出线来自何处。上周它曾经输出0 Bytes written to bluetooth
而没有额外的行,但从那以后已经做了改变。
编辑.... Patrick Trentin的诊断是正确的。
sprintf( buf, "%d,%d,", nums[0],nums[1] );
需要更改为
int str_len = sprintf( buf, "%d,%d,", nums[0],nums[1] );
和
bytes_written = write(s, buf, sizeof(buf));
需要更改为
bytes_written = write(s, buf, str_len);
读取过程耗时有点令人失望,因此需要进行一些非常严肃的优化,但它似乎确实做了最终目的......