I am trying to communicate between arduino and pySerial but the serial monitor is giving me back weird characters so the arduino is not turning on/off led like it should. Thanks in advance.
Arduino code
int ledpin = 13;
int state; // 0 = led off, 1 = led on
int flag = 0; // used so msg is only printed once
char val;
void setup(){
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, LOW);
Serial.begin(9600);
}
void loop(){
//if data sent, read and save
if(Serial.available() > 0){
state = Serial.read() -'0';
val = char(state);
Serial.println(val);
flag = 0;
}
//if state = 0
if (val == '0'){
digitalWrite(ledpin, LOW);
if(flag = 0){
Serial.println('LED : Off');
flag = 1;
}
}
//if state = 1
if (val = '1'){
digitalWrite(ledpin,HIGH);
if(flag = 0){
Serial.println('LED : On');
flag = 1;
}
}
}
Python code
import serial
from tkinter import *
port = '/dev/ttyACM0'
speed = 9600
def send_command(val):
connection = serial.Serial(port,speed)
connection.write(b"val")
connection.close()
#Create the window
win = Tk()
#Modify the root window
win.title("Arduino system") # gives title to window
win.geometry("320x100") # sets the size of the window
#Creating components
f = Frame(win) # creates window
#label with text
l = Label(win , text = "Flash LED")
b1 = Button(f, text ="Send 0")
b2 = Button(f, text ="Send 1")
#Defining methods
def but1(): send_command('0') # command run if button 1 pressed
def but2(): send_command('1') # command run if button 1 pressed
b1.configure(command = but1) # assiging methods to buttons
b2.configure(command = but2) # assiging methods to buttons
#Adding Components
l.pack() #packs in the label
b1.pack(side = LEFT) #packs the buttons in one after the other
b2.pack(side = LEFT) #packs the buttons in one after the other
f.pack()
win.mainloop() # start Gui
after sending a 0 from python to arduino the following appears on the serial monitor F 1 <
after sending a 1
the same thing appears