Home > Mobile >  Pyserial write data to serial port
Pyserial write data to serial port

Time:12-01

It´s my first time working with pyserial. I made an simple gui with pysimplegui and now I´d like to write the data from the sliders to the serial monitor. How can I do it?

import PySimpleGUI as sg
import serial

font = ("Courier New", 11)
sg.theme("DarkBlue3")
sg.set_options(font=font)

ser = serial.Serial("COM6")
ser.flushInput()

layout = [
    [sg.Text("X"), sg.Slider((0, 360), orientation='horizontal', key='SLIDER_X')],
    [sg.Text("Y"), sg.Slider((0, 360), orientation='horizontal', key='SLIDER_Y')],
    [sg.Text("Z"), sg.Slider((0, 360), orientation='horizontal', key='SLIDER_Z')],
    [sg.Push(), sg.Button('Exit')],
]

window = sg.Window("Controller", layout, finalize=True)
window['SLIDER_X'].bind('<ButtonRelease-1>', ' Release')
window['SLIDER_Y'].bind('<ButtonRelease-1>', ' Release')
window['SLIDER_Z'].bind('<ButtonRelease-1>', ' Release')

while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, 'Exit'):
        break
    elif event == 'SLIDER_X Release':
        print("X Value:", values["SLIDER_X"])
    elif event == 'SLIDER_Y Release':
        print("Y Value:", values["SLIDER_Y"])
    elif event == 'SLIDER_Z Release':
        print("Z Value:", values["SLIDER_Z"])

    data = values["SLIDER_X"], values["SLIDER_Y"], values["SLIDER_Z"]

    print("String:", data)

window.close()
ser.close()

If I just do

ser.write(data) 

I get an error:

TypeError: 'float' object cannot be interpreted as an integer

I just want to write the data to the serial port so I can read it with an Arduino.

CodePudding user response:

There are 2 issues with the code here:

  1. Variable data has a type of tuple, not a number.
  2. Each member of the tuple is a float as the TypeError indicates.

You will need to pass one value at a time to ser.write. And you will need to cast the float returned by the slider widget to an integer. Something like the following:

data = int(values["SLIDER_X"])
ser.write(data)
  • Related