Serial connection of Processing and Arduino

I’m try 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!

Hi

Try this in Arduino side

if(Serial.available() > 0) {

Or try this code

byte x = 0;
int speakerPin = 8;
void setup()
{
  pinMode(speakerPin, OUTPUT);
  Serial.begin(9600);
  
}
 
void loop() {

  if (int(x) == 1) {
    Do something 
  }
  else if (int(x) == 2) {
    Do something 
    
  }
  
  }
 
 
void serialEvent() {
  while (Serial.available()) {
    x = Serial.read();
  } 
}

Hello @jinalilili,

A '1' (character) and 1 (integer number) are two different things.

Processing:
myPort.write(1);

Arduino:
if (val == '1') // This will NEVER be equal to 1

Reference:
https://processing.org/reference/char.html

This is a common error for those new to programming and serial communications.

Keep at it!

char a = '1';

// This will NOT be equal:
int b = 1;

//These will be equal:

//int b = 49; // ASCII for '1' in decimal
//int b = 0x31; // ASCII for '1' in hexadecimal

if (a == b)
  println("Equal");
else
  println("NOT Equal");

:)

Was also discussed here: https://stackoverflow.com/questions/72494671/serial-connection-of-processing-and-arduino. Not sure why this answer was not accepted. It would help if there was some feedback.

1 Like