I am trying to use a button switch in Arduino to trigger a visual display in Processing. I used "HIGH" and "LOW" to identify whether the button is pressed.
However, my code is constantly giving null instead of giving "HIGH" or "LOW" depending on the button state. I think this is pretty basic but I'm just quite lost. Any helps or comments would be appreciated!
Below is my code for Arduino and Processing respectively.
const int buttonPin = 2;
const int LEDPin = 13;
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int analogValue = analogRead(A0)/4;
Serial.write(analogValue);
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
Serial.write(HIGH);
digitalWrite(LEDPin, HIGH);
} else {
Serial.write(LOW);
digitalWrite(LEDPin, LOW);
}
delay(100);
}
Processing code:
import processing.serial.*;
Serial myPort;
String val;
void setup() {
size(400,400);
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}
void draw() {
if (myPort.available() > 0) {
val = myPort.readStringUntil('\n');
println(val);
if (val == "HIGH") {
background(127,0,0);
}
if (val == "LOW") {
background(144, 26, 251);
}
}
}
Serial.write(HIGH);doesn't send'H','I','G','H'and'\n'but just a1.