将 ASCII dec 转换为字符时出现问题
Problems translating ASCII dec to character
在这个
函数中,我希望用户能够选择他/她想要重复测试的次数。我用char(incomingByte)翻译ASCII dec(从serial.read
),但是一旦我进入for循环,数字就会改回其dec值...你能解释一下为什么吗?
Serial.println("Choose number of times (max 10) to repeat test : ");
while(Serial.available() == 0) {
delay(10);
}
int incomingByte = Serial.read();
// Number of times to repeat test chosen by user.
nRepeat = char(incomingByte);
Serial.print("You chose : ");
Serial.println(char(nRepeat));
for(int i=0; i<nRepeat; i++) {
randomSeed(A1);
// Assigning a random seed for the random function.
timer = random(2000, 5000);
// Sets the random timer to vary between 2000 and 5000 ms
delay(timer);
// The delay is now random between 2000 and 5000 ms
digitalWrite(LED, HIGH);
// Turn on the LED (pin 13)
startTid = millis();
// Saves the current time the Arduino has been powered.
while(digitalRead(Buttom) == HIGH) {
// Loop until buttom is pressed
}
stopTid = millis();
// Saves current time since arduino got powered
digitalWrite(LED, LOW);
// Turns LED off
Serial.print("Your time was: ");
Serial.print(stopTid-startTid);
// Prints the time between the exercise started and finished
Serial.println(" milli seconds");
person[cc].reacTime[i] = stopTid-startTid;
Serial.print(i);
Serial.print(" out of ");
Serial.println(nRepeat);
delay(1000);
}
正如@iharob所指出的,C 中的 char() 不是用于翻译的函数。 在 C 中执行您正在寻找的 ASCII 转换的最简单方法是从输入的值中减去"0"。 这依赖于数字在 ASCII 表中按顺序排列的事实。 但是,您需要确保用户的输入实际上是数字。 您的代码也只允许从 0 到 9 的重复。
nRepeat = incomingByte - '0';
if (nRepeat >= 0 && nRepeat <= 9) {
// Valid digit entered, proceed
//...
}
当你Serial.read()
时,你会得到用户写入的数字的 ASCII 值,即 0 (zero) = 49
.如果要获取写入数字的int
值,可以使用Serial.parseInt()
。然后,您可以进行if
语句,以确保数字介于 0 和 10 之间。
更多关于Serial.parseInt()
的文档:http://arduino.cc/en/Reference/ParseInt
相关文章:
- 从矢量C++读取字符时出现问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- C++理解计算字符变量的问题
- 将十六进制值设置为用于填充的字符变量时出现问题
- 编写 cin.get() 以接收字符数组时出现问题
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 字符 * 未从重载运算符或内存管理问题正确返回
- 将utf16宽std::wstring转换为utf8窄std::string以获得罕见字符时出现问题
- 我在使用字符的函数时遇到了一些问题
- 用wchar_t处理 unicode 字符好吗?它不会引起任何问题吗?
- 将 c++ 字符串转换为常量字符 * 时出现问题
- C++程序,将整数输入转换为字符的问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- C++ 初级面试问题:仅使用字符指针压缩字符序列的功能
- 通过比较字符设置字符串时出现问题
- 我的编辑距离递归代码中的字符类型有问题
- 获取“boost::文件系统::p ath”字符指针时出现问题
- C Unicode UTF-8解码字符的问题
- 类型转换问题:字符数组的元素转换为整数变量