如何在Arduino serial read()上将char转换为int
How do I convert char to int on Arduino serial read()?
我将字符串值从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);
}
}
}
您的问题比您所阐述的要微妙一些。由于Serial.read()会一次给你每个字符一个,如果你在串行监视器中键入"180",你会得到"1"、"8"answers"0"。
当您收到一个char并更改为int时,您将获得ASCII中的等价char。"0"的值实际上是48,因此您需要处理它。然后,对于每个连续的字符,您需要将结果右移一个空格(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);
}
}
简而言之,在您的情况下,使用Serial.parseInt()
:更合适
void loop() {
if (Serial.available()) {
int c = Serial.parseInt();
myservo.write(c);
}
}
我会用另一种方式来做。首先,我将char连接到一个字符串,然后将该字符串转换为一个数字,如下所示:
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();
这是一个正确的程序吗?它对我有用(我简化了源代码来解释所采用的过程,因此可能会有一些错误)
您试图读取什么值?
假设你有一个光传感器。它看起来是这样的:
int photocellPin = 0;
int photocellReading;
void setup() {
Serial.begin(9600);
myservo.attach(9);
}
void loop() {
photcellReading = analogRead(photocellPin);
myservo.write(photocellReading);
}