Ipywidgets not passing through Arduino serial (serial output) (Jupyter Labs)

Hello,
I have this example and it runs perfectly fine in Jupyter labs:
(the LED turns on and stays on or turns off and stays off using this code)

import serial
with serial.Serial('/dev/ttyACM0', 9600, timeout=10) as ser:
    while True:
        led_on = input('Do you want the LED on? ')[0]
        if led_on in 'yY':
            ser.write(bytes('YES\n','utf-8'))
        if led_on in 'Nn':
            ser.write(bytes('NO\n','utf-8'))

And I tried to modify it so that I can use ipywidgtes (buttons specifically) and the same code does not do the same thing
(the builtin LED blinks but it does not stay on)

import serial
import ipywidgets
import ipywidgets as widgets
from IPython.display import display

button = widgets.Button(description="Click Me!")
button1 = widgets.Button(description="Click Me!1")
output = widgets.Output()
display(button, button1, output)

def on_button_clicked(b):  
    print("on")
    with serial.Serial('/dev/ttyACM0', 9600, timeout=10) as ser:
        ser.write(bytes('YES\n','utf-8'))
                
def on_button_clicked1(b):
    print("off")
    with serial.Serial('/dev/ttyACM0', 9600, timeout=10) as ser:
        ser.write(bytes('NO\n','utf-8'))
        
button.on_click(on_button_clicked)
button1.on_click(on_button_clicked1)

Question: Any idea why the widgets dont pass through serial data the same way as the example at the top?

324Hz
win21H2
he/him

Hi,
Would suggest add sleep/delay between serial.Serial() and ser.write() for a try. And may try baud rate 11520.

1 Like

Hello DaneLLL,
I tried switching up the things you mentioned like so:

import serial
import ipywidgets
import ipywidgets as widgets
from IPython.display import display

button = widgets.Button(description="Click Me!")
button1 = widgets.Button(description="Click Me!1")
output = widgets.Output()
display(button, button1, output)

def on_button_clicked(b):  
    print("on")
    with serial.Serial('/dev/ttyACM0', 11520, timeout=10) as ser:
        time.sleep(1)
        ser.write(bytes('YES\n','utf-8'))
                
def on_button_clicked1(b):
    print("off")
    with serial.Serial('/dev/ttyACM0', 11520, timeout=10) as ser:
        time.sleep(1)
        ser.write(bytes('NO\n','utf-8'))
        
button.on_click(on_button_clicked)
button1.on_click(on_button_clicked1)

and it still does not turn on for some reason.

324Hz
win21H2
he/him

Acctually, I have not edited the Arduino code which might be the reason its not getting the correct things

EDIT: It works thanks @DaneLLL

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.