如何在Arduino serial read()上将char转换为int?

时间:2014-11-07 22:39:54

标签: c++ char arduino

我从我的Android设备向Arduino发送字符串值,但我无法将输入serial.read()转换为实际的整数值。

如何获得介于1..180之间的整数(以控制伺服电机)?

void setup()
{
    myservo.attach(9);
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available())
    {
        int c = Serial.read();
        if (c == '0')
        {
            myservo.write(0);
        }
        else
        {
            // Servo write also int number
            myservo.write(c);
        }
    }
}

4 个答案:

答案 0 :(得分:5)

你的问题比你的问题更加微妙。由于Serial.read()会一次为您提供一个字符,如果您在串行监视器中输入“180”,您将获得“1”,然后是“8”,然后是“0”。

当你收到一个char并更改为int时,你将获得ASCII中的char等价物。 '0'的值实际上是48,所以你需要处理它。然后使用每个连续的char,你需要将结果右移一个空格(10的幂)并在1的列中插入新值以重新组合输入的角度。

以下是一些应该有效的代码:

#include <Servo.h>
Servo myservo;

void setup() 
    { 
      myservo.attach(9); 
      Serial.begin(9600);
      myservo.write(0); //or another starting value
    } 


    void loop() 
    { 
      //reset the values each loop but only reprint
      //them to the servo if you hit the while loop
      int angle = 0;

      while(Serial.available() > 0){
        //Get char in and convert to int
        char a = Serial.read();
        int c = (int)a - 48;
        //values will come in one character at a time
        //so you need to increment by a power of 10 for
        //each character that is read
        angle *= 10;
        //then add the 1's column
        angle += c;
        //then write the angle inside the loop
        //if you do it outside you will keep writing 0
        Serial.println(angle);//TODO this is a check. comment out when you are happy
        myservo.write(angle);
      }


    }

答案 1 :(得分:2)

简而言之,在您的情况下,使用Serial.parseInt()

更合适
void loop() {
    if (Serial.available()) {
        int c = Serial.parseInt();
        myservo.write(c);
    }
}

答案 2 :(得分:0)

你想读什么价值?

让我们说你有一个光传感器。它看起来像这样:

int photocellPin = 0;
int photocellReading;

void setup() {
    Serial.begin(9600);
    myservo.attach(9);
}

void loop() {
    photcellReading = analogRead(photocellPin);
    myservo.write(photocellReading);
}

答案 3 :(得分:0)

我会用另一种方式来做。首先我将字符连接到字符串,然后将字符串转换为数字,如下所示:

String num_string="";
byte col=0;
boolean cicle= true;
while(cicle){
 
    char c;


    lcd.setCursor(col,2);
    c=keypad.waitForKey();
    lcd.print(c);
    num_string=num_string+c;
    col++;
    
    if(keypad.waitForKey()=='*'){
      cicle=false;
    }
}
unsigned long num = num_string.toInt();

这是一个正确的程序吗?它对我有用 (我简化了源代码来解释所采用的程序,所以可能会有一些错误)