串行消息在Arduino的整数 [英] Serial message to integer on arduino
问题描述
我希望我的Arduino通过串口通信接收一个整数。你能不能帮我?
这应该是在一个格式如:
int值= strtoint(Serial.read());
有几种方法来读取一个整数串口
,很大程度上取决于数据是如何连接codeD时,它被发送。 Serial.read()
只能用于读取单个字节,这样发送数据需要从这些字节重建。
以下code可为你工作。它假定串行连接已被配置为9600波特,该数据被发送为ASCII文本,每个整数由一个换行符分隔( \\ n
)
// 12是一个32位整数的小数重presentation的最大长度,
//包括负号的空间和终止空字节
字节intBuffer [12];
串intData =;
INT分隔符=(INT)的'\\ n';无效设置(){
Serial.begin(9600);
}空隙环(){
而(Serial.available()){
INT CH = Serial.read();
如果(CH == -1){
//处理错误
}
否则,如果(CH ==分隔符){
打破;
}
其他{
intData + =(char)的CH;
}
} //复制数据读入一个char数组用于通过的atoi
//包括客房为空终止
INT intLength = intData.length()+ 1;
intData.toCharArray(intBuffer,intLength); //重新初始化intData用于下一次围绕循环
intData =; //转换为int ASCII-CN codeD整数
INT I =的atoi(intBuffer);
}
I want my arduino to receive an integer through the serial communication. Can you help me with this?
It should be in a form like:
int value = strtoint(Serial.read());
There are several ways to read an integer from Serial
, largely depending on how the data is encoded when it is sent. Serial.read()
can only be used to read individual bytes so the data that is sent needs to be reconstructed from these bytes.
The following code may work for you. It assumes that serial connection has been configured to 9600 baud, that data is being sent as ASCII text and that each integer is delimited by a newline character (\n
):
// 12 is the maximum length of a decimal representation of a 32-bit integer,
// including space for a leading minus sign and terminating null byte
byte intBuffer[12];
String intData = "";
int delimiter = (int) '\n';
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()) {
int ch = Serial.read();
if (ch == -1) {
// Handle error
}
else if (ch == delimiter) {
break;
}
else {
intData += (char) ch;
}
}
// Copy read data into a char array for use by atoi
// Include room for the null terminator
int intLength = intData.length() + 1;
intData.toCharArray(intBuffer, intLength);
// Reinitialize intData for use next time around the loop
intData = "";
// Convert ASCII-encoded integer to an int
int i = atoi(intBuffer);
}
这篇关于串行消息在Arduino的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!