目标:我想从串行监视器中输入一个整数。这些值稍后将用作delay(value)命令的一部分。延迟的目的是使两个振动电机稍微不同步。
问题:我正在尝试从命令行获取诸如60或400之类的值。当前值与输入值不匹配。
我的直觉说这是数据格式问题。我希望有人能帮助我理解为什么每个数字都打印为数字。
提示子例程代码:
while (!Serial.available()) { //this holds until we see a serial prompt
}
if (Serial.available() > 0) {
uint8_t inChar = Serial.read();
Serial.println(inChar);
// convert the incoming byte to a char and add it to the string:
if (isDigit(inChar)) {
receivedChar += (char)inChar;
}
// if you get a newline, print the string, then the string's value:
if (inChar == '\n') {
Serial.print("Delay Value:");
Serial.println(receivedChar.toInt());
Serial.print("String: ");
Serial.println(receivedChar);
// clear the string for new input:
}
newData = true;
prompthold = false;
}
}
循环代码:
void loop(){
while (prompthold == false) {
prompthold = true;
Serial.println("Please enter delay");
receivedChar = "";
srl_prompt();
apparentmotion();
}
delay(500);
}
诊断信息: 输入1234567890
返回:
16:28:13.079 -> 49
16:28:13.079 -> Please enter delay
16:28:13.079 -> 50
16:28:13.079 -> Please enter delay
16:28:13.079 -> 51
16:28:13.079 -> Please enter delay
16:28:13.079 -> 52
16:28:13.079 -> Please enter delay
16:28:13.079 -> 53
16:28:13.113 -> Please enter delay
16:28:13.113 -> 54
16:28:13.113 -> Please enter delay
16:28:13.113 -> 55
16:28:13.113 -> Please enter delay
16:28:13.113 -> 56
16:28:13.147 -> Please enter delay
16:28:13.147 -> 57
16:28:13.147 -> Please enter delay
16:28:13.147 -> 48
16:28:13.147 -> Please enter delay
16:28:13.147 -> 10
16:28:13.147 -> Delay Value:0
16:28:13.147 -> String:
16:28:13.147 -> Please enter delay
输入200
16:29:06.082 -> Please enter delay
16:34:02.121 -> 50
16:34:02.121 -> Please enter delay
16:34:02.121 -> 48
16:34:02.155 -> Please enter delay
16:34:02.155 -> 48
16:34:02.155 -> Please enter delay
16:34:02.155 -> 10
16:34:02.155 -> Delay Value:0
16:34:02.155 -> String:
16:34:02.155 -> Please enter delay
答案 0 :(得分:0)
好的,我已经解决了。如果使用Serial.read(),则将获得字符串/ ASCII。如果使用Serial.parseInt(),则会获得一个值。更新的代码如下:
void srl_prompt() {
while (!Serial.available()) { //this holds until we see a serial prompt
}
if (Serial.available() > 0) {
uint8_t inChar = Serial.parseInt();
Serial.println(inChar);
// convert the incoming byte to a char and add it to the string:
if (isDigit(inChar)) {
receivedChar += (char)inChar;
}
// if you get a newline, print the string, then the string's value:
if (inChar == '\n') {
Serial.print("Delay Value:");
Serial.println(receivedChar.toInt());
Serial.print("String: ");
Serial.println(receivedChar);
// clear the string for new input:
}
newData = true;
prompthold = false;
}
}