【问题标题】:Converting ASCII to int in Arduino在 Arduino 中将 ASCII 转换为 int
【发布时间】:2016-09-28 08:53:17
【问题描述】:

我正在尝试从串行监视器获取用户输入,以根据输入转动步进电机。但是我的代码返回的是 ASCII 值而不是原始输入。

#include <Stepper.h>

Stepper small_stepper(steps_per_motor_revolution, 8, 10, 9, 11);

void setup() {
  // Put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Ready");
}


void loop() {

  // Put your main code here, to run repeatedly:
  int Steps2Take = Serial.read();
  Serial.println(Steps2Take); // Printing
  if (Steps2Take == -1)
    Steps2Take = 0;
  else {
    small_stepper.setSpeed(1000); // Setting speed
    if (Steps2Take > 0)
      small_stepper.step(Steps2Take * 32);
    else
      small_stepper.step(-Steps2Take * 32);
    delay(2);
  }
}

【问题讨论】:

标签: arduino type-conversion ascii


【解决方案1】:

只需使用 .toInt() 函数。

您应该从序列中读取字符串,然后将其转换为整数。

Serial.print(Serial.readString().toInt());

【讨论】:

    【解决方案2】:

    您可以通过三种方式做到这一点!请注意,如果数字大于 65535,则必须使用 long 变量。小数使用浮点变量。

    1. 您可以使用需要字符串类型变量的 toInt() 或 toFloat()。注意 toFloat() 非常耗时。

         // CODE:
         String _int = "00254";
         String _float = "002.54"; 
         int value1 = _int.toInt();
         float value2 = _float.toFloat();
         Serial.println(value1);
         Serial.println(value2);
      
         // OUTPUT:
         254
         2.54
      
    2. 您可以使用 atoi。该函数接受一个字符数组,然后将其转换为整数。

         // CODE:
         // For some reason you have to have +1 your final size; if you don't you will get zeros.
         char output[5] = {'1', '.', '2', '3'}; 
         int value1 = atoi(output);
         float value2 = atof(output);
         Serial.print(value1);
         Serial.print(value2);
      
         // OUTPUT:
         1
         1.23
      
    3. 如果您有一个字符数组并且想将其转换为字符串,因为您不知道长度...比如消息缓冲区或其他东西,我不知道。您可以在下面使用它来将其更改为字符串,然后实现 toInt() 或 toFloat()。

        // CODE:
        char _int[8];
        String data = "";
        for(int i = 0; i < 8; i++){
          data += (char)_int[i];
        }
      
        char buf[data.length()+1];
        data.toCharArray(buf, data.length()+1);
      

    【讨论】:

      【解决方案3】:

      如果只是“类型转换”的问题,可以这样使用:

      int a_as_int = (int)'a';
      

      #include <stdlib.h>
      
      int num = atoi("23"); //atoi = ascii to integer
      

      正如here所指出的那样。

      解决问题了吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        • 2021-08-15
        • 2014-11-05
        • 1970-01-01
        相关资源
        最近更新 更多