【问题标题】:Problems translating ASCII dec to character将 ASCII dec 转换为字符的问题
【发布时间】:2014-12-30 13:09:24
【问题描述】:

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

【问题讨论】:

  • 你觉得char(nRepeat)在做什么,不是ascii翻译的函数,是函数风格的c++ cast。
  • 我假设,因为我声明了 nRepeat = char(53) 这给了我 nRepeat = 5,所以我可以使用此方法在 for 循环中作为 ex 的整数进一步使用。 5. 知道解决方案吗?
  • 这实际上取决于你如何打印它,如果.print()方法支持%c说明符,那么可能Serial.print("%c", nRepeat);会这样做,但我不知道Serial类你正在使用。
  • 看起来这是一个 Arduino 库,如果是这样,则使用 char incomingByte 消除了查看此示例的演员表的需要:arduino.cc/en/Tutorial/KeyboardSerial
  • ASCII 53 恰好是字符 '5'

标签: c++ for-loop arduino


【解决方案1】:

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

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

【讨论】:

  • 问题解决了,我写了一个更长的代码,当用户输入 1 时定义 nRepeat 等于 1 等,以解决用户在 0-10 之外输入的问题。感谢您的输入
【解决方案2】:

当您Serial.read() 时,您将获得用户写入的数字的 ASCII 值,即0 (zero) = 49。 如果要获取写入数字的int 值,可以使用Serial.parseInt()。然后,您可以发出if 声明以确保该数字介于 0 和 10 之间。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 2023-03-08
    • 2023-03-24
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多