将ASCII dec转换为字符的问题

时间:2014-12-30 13:09:25

标签: c++ for-loop arduino

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

2 个答案:

答案 0 :(得分:0)

正如@iharob所指出的,C中的char()不是翻译函数。 C中进行ASCII转换的最简单方法是从输入的值中减去“0”。这依赖于数字在ASCII表中按顺序排列的事实。但是,您需要确保用户的输入实际上是一个数字。您的代码也只允许重复0-9。

nRepeat = incomingByte - '0';
if (nRepeat >= 0 && nRepeat <= 9) {
    // Valid digit entered, proceed
    //...
}

答案 1 :(得分:0)

当您Serial.read()时,您获得用户所写号码的ASCII值,即0 (zero) = 49。 如果要获取所写数字的int值,可以使用Serial.parseInt()。然后,您可以生成if语句以确保该数字介于0到10之间。

有关Serial.parseInt()的更多文档:http://arduino.cc/en/Reference/ParseInt