1

I'm currently writing a Python program intended to write data out to a Raspberry Pico microcontroller using the pyserial module, with a Tkinter graphical user interface. However, the Pico doesn't appear to be picking up what I write to it over the serial cable when I press the button corresponding to that command on the interface.

This is the code that I have:

import serial
import time
import tkinter as tk

def activate_serial():
    with serial.Serial('COM12', 9600, timeout=1) as ser:
        while ser.in_waiting>0:
            out = ser.readline()
            print(out)
            time.sleep(0.5)

def send_data():
    serial.Serial('COM12', 9600, timeout=1).write(bytes(str(1)+'\n','utf-8'))

gui = tk.Tk()
label_no = tk.Label(text="Entry")
send = tk.Button(text="Send Command", command=send_data())
input_mod = tk.Entry()
label_no.pack()
input_mod.pack()
send.pack()

gui.after(500,activate_serial)

gui.mainloop()

How it's supposed to work is that the Tkinter interface opens first; then, the after command runs the code block to connect to the serial monitor. From that point onwards, whenever I press the button on the GUI, it should write out a '1' to the Pico, which then sends it back and writes it out to get printed by the Python code using this code, in the Arduino IDE language:

void setup() {
  Serial.begin(9600);
}
void loop() {
  if (Serial.available()>0)
  {
    int dataIn = Serial.parseInt();
    Serial.readString();
    digitalWrite(LED_BUILTIN, HIGH);
    delay(100);
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println(dataIn);
  }
}

Whenever I run the program, the GUI opens without error, and I can press the button. However, even though I've tried running the Arduino and Python codes a number of times, it never gets to the point where the input gets written back out to my output line (I'm testing/running this in PyCharm).

Nate
  • 11
  • 1

1 Answers1

1

Try changing this line:

send = tk.Button(text="Send Command", command=send_data())

to

send = tk.Button(text="Send Command", command=send_data)
Pragmatic_Lee
  • 473
  • 1
  • 4
  • 10