Hello,
In Arduino code, I have
const int buttonPin = 4;
const int buttonPin2 = 9;
const int ledPin = 6;
const int ledPin2 = 12;
int buttonState = 0;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
Serial.begin(115200);
Serial.flush();
pinMode(LED_BUILTIN, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH )
{
digitalWrite(ledPin, LOW);
}
else
{
digitalWrite(ledPin, HIGH);
Serial.write("BUTTON1PRESSED");
}
buttonState = digitalRead(buttonPin2);
if (buttonState == HIGH )
{
digitalWrite(ledPin2, LOW);
}
else
{
digitalWrite(ledPin2, HIGH);
Serial.write("BUTTON2PRESSED\n");
}
}
==========
I'd like to detect that a button is pressed and do some action in my Python code, like this:
# Importing Libraries
import serial
import time
arduino = serial.Serial(port='COM4', baudrate=115200, timeout=.1)
def readFromButton():
value = arduino.readline()
print(value)
time.sleep(1)
if ( value == "BUTTON1PRESSED\n"):
print('button1 pressed\n')
elif ( value == "BUTTON2PRESSED\n"):
print('button2 pressed\n')
while True:
readFromButton()
=======
The problem is that when I push a button , I got a lot of either BUTTON2PRESSED\n or BUTTON1PRESSED\n printed and I don't know how to get a single output from Arduino et take action wrt the output value, i,e, when I press the button, I change something in my Python code. Here, I don't have print('button1 pressed\n') nor print('button1 pressed\n') printed.
Also, is my test comparing value correct ?
Thank you very much,
Best regards