0

I'm trying to make a serial connection from processing to arduino. The idea is that when I press "a", the speaker from Arduino will produce a sound and the same goes with another key pressed but with a different note. However, I'm a bit stuck with the codes. Can anyone let me know what is the problem of my codes?

Processing code:

import processing.serial.*;
Serial myPort; 
int val; // Data received from the serial port

void setup()
{
size(200, 200);
String portName = Serial.list()[0]; 
myPort = new Serial(this, portName, 9600);
}

void draw() {
}

 void keyPressed(){
   if (key == 'a'){
     myPort.write(1); 
   }
   if (key == 'd'){
     myPort.write(2); 
   }  
 }
 void keyReleased(){
   myPort.write(0);
 } 

Arduino code:

char val; // Data received from the serial port
int speakerPin = 8;

void setup() {
pinMode(speakerPin, OUTPUT);
Serial.begin(9600); 
}

void loop() {
while (Serial.available()) { 
val = Serial.read(); 
}
if (val == '1') {  
tone(speakerPin, 262, 200); 
} else if (val == '2'){
tone(speakerPin, 523, 200); 
}
delay(100); 
}

Many many thanks!

1 Answer 1

1

You are so close!

The issue is on the Arduino side you're checking characters, however, on the Processing side you're sending the actual values, not the ASCII characters.

1 != '1' (49)
2 != '2' (50)

In Processing, simply use the char type single quote symbols:

myPort.write('1');

...

myPort.write('2'); 

(which is the same as myPort.write(49); for '1', myPort.write(50); for '2')

Alternatively you can change the way you're checking on Arduino side to not use chars to be consistent with how you're sending from Processing. e.g.

if (val == 1)

(instead of if (val == '1')).

Sign up to request clarification or add additional context in comments.

1 Comment

Also, consider sending the character of the keyboard key that is pressed instead of translating 'a' into '1', 'b' into '2', etc. Instead, send the key character ('a'), and in the Arduino code, check for an 'a': if val=='a', etc. Then the Processing code can just be: void keyPressed(){myPort.write(key);}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.