将 ASCII dec 转换为字符时出现问题

Problems translating ASCII dec to character

本文关键字:问题 字符 ASCII dec 转换      更新时间:2023-10-16
在这个

函数中,我希望用户能够选择他/她想要重复测试的次数。我用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