2013-10-20 14 views
1

我試圖發送字符的從加工到Arduino的,但Arduino的只承認其中的2,處理Arduino的連接難度

的問題是與「2」字符

當我按下「S」鍵處理代碼發送'2'字符,因爲我可以看到arduino rx led照明但電機什麼也沒有,

與'1'或'0'字符我沒有問題, 我切換' 2'在arduino代碼中對應於drive_forward,然後對應於drive_reverse,但分配了'2'字符的那個在兩個ca中都不起作用SES, 正如我所說的「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"); 

}

+0

不太可能是問題,但你應該初始化VAL爲 '0'。 – struthersneil

+2

您是否嘗試過使用Arduino串行監視器? – ladislas

+0

只有一個程序可以使用com端口,所以如果我使用串口監視器,我將無法將處理程序連接到arduino並查看它究竟接收了什麼,因爲它是我看到的RX燈亮起當我試圖從處理髮送'2'字符 –

回答

1

正如@tailedmouse說,S結束數據爲整數。

處理代碼:

//skipped some code 
void keyPressed() { 
    if (key == 'w' || key == 'W') { 
     myPort.write(1); 
    } 

    if (key == 's' || key == 'S') { 
     myPort.write(2); 
     println("2"); 
    } 
} 

void keyReleased() { 
    myPort.write(0); 
    println("0"); 
} 

的Arduino代碼:

//skipped some code. 
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(); 
    } 
}