我正在尝试将char从处理发送到arduino,但是arduino只识别其中的2个,
问题在于'2'字符
当我按's'键时,处理代码正在发送'2'字符,因为我可以看到arduino rx led灯,但是电机什么也没做,
使用'1'或'0'字符我没有问题,我将arduino代码中的'2'切换为对应于drive_forward然后再切换到drive_reverse,但是分配给它的'2'字符的那个不能用于两种情况,正如我所说的'1'和'0'字符被发送和接收良好
我想这是arduino代码中的东西,但我不知道是什么
arduino代码:
int motor1 = 4;
int motor2 = 5;
char val;
// --------------------------------------------------------------- Setup
void setup() {
Serial.begin(9600);
// Setup motors
pinMode(motor1, OUTPUT);
pinMode(motor2, OUTPUT);
}
// ---------------------------------------------------------------- Loop
void loop() {
if (Serial.available()>0)
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
}
if (val == '2'){
drive_forward();
}
if (val == '1'){
drive_reverse();
}
if (val == '0'){
motor_stop();
}
}
// --------------------------------------------------------------------------- Drive
void motor_stop(){
digitalWrite(motor1, LOW);
digitalWrite(motor2, LOW);
}
void drive_forward(){
digitalWrite(motor1, HIGH);
digitalWrite(motor2, LOW);
delay(15);
digitalWrite(motor1, LOW);
digitalWrite(motor2, LOW);
delay(15);
}
void drive_reverse(){
digitalWrite(motor2, HIGH);
digitalWrite(motor1, LOW);
delay(15);
digitalWrite(motor2, LOW);
digitalWrite(motor1, LOW);
delay(15);
}
处理代码:
import processing.serial.*;
Serial myPort;
void setup()
{
size(200,200);
myPort = new Serial(this, Serial.list()[2], 9600);
}
void draw() {
}
void keyPressed() {
if (key == 'w' || key == 'W')
{
myPort.write('1');
println("1");}
if (key == 's' || key == 'S')
{
myPort.write('2');
println("2");}
}
void keyReleased() {
myPort.write('0');
println("0");
}
1 回答
正如@tailedmouse所说,发送数据为整数 .
处理代码:
Arduino代码: