When I taught Arduino last year I had projects that had the user give responses with serial read and serial write through the usb cord.
Is this possible (for beginner coders) in circuitpython? I have seen some discussion of it which perhaps sounds like using the touch pads around the CPx might be an easier choice.
reading from serial - circuitpython
Moderators: adafruit_support_bill, adafruit
Please be positive and constructive with your questions and comments.
- dastels
- Posts: 15653
- Joined: Tue Oct 20, 2015 3:22 pm
Re: reading from serial - circuitpython
It's pretty straight forward. Here's some code directly from one of my projects.:
Code: Select all
import busio
import board
...
uart = busio.UART(board.TX, board.RX, baudrate=115200)
...
while True:
if uart.in_waiting > 0:
ch = uart.read(1)
if cmd_buffer_index > 7:
cmd_buffer_index = 0
uart.write("command too long.. ignored\r\n")
else:
uart.write(ch)
if ch == b'\r':
if cmd_buffer_index > 0:
process_command(cmd_buffer[0:cmd_buffer_index])
cmd_buffer_index = 0
else:
cmd_buffer[cmd_buffer_index] = ch[0]
cmd_buffer_index += 1
continue
...
- Hapka
- Posts: 89
- Joined: Fri Jul 03, 2015 10:52 pm
Re: reading from serial - circuitpython
Thanks! I'll play with that.
- kevinjwalters
- Posts: 1025
- Joined: Sun Oct 01, 2017 3:15 pm
Re: reading from serial - circuitpython
Some previous discussions on reading data from the serial (USB) connection:
- danhalbert
- Posts: 4649
- Joined: Tue Aug 08, 2017 12:37 pm
Re: reading from serial - circuitpython
Note also that of CircuitPython 3.1.2, there's a new function runtime.serial_bytes_available, which returns True if there is at least one byte to read from USB serial.
- a_nice_cow
- Posts: 1
- Joined: Wed Feb 06, 2019 10:42 am
Re: reading from serial - circuitpython
I've been using serial_bytes_available like this:
Code: Select all
from supervisor import runtime
from sys import stdin
serial_buffer = ""
def serial_readline():
while runtime.serial_bytes_available:
c = stdin.read(1)
serial_buffer += c
if c == '\n':
line = serial_buffer
serial_buffer = ""
return line
while True:
serial_line = serial_readline()
# then if you wanted to eg. echo back over usb serial you'd do
if serial_line:
print(serial_line)
- antoniob
- Posts: 33
- Joined: Tue Jul 09, 2013 2:47 am
Re: reading from serial - circuitpython
Hi, being a newbie to CircuitPython, I've tried your code on an M0 Express board. CircuitPyton V4.1.x. Alas I get nothing, and exploring further, the buffered "serial_buffer" only ever has one character. Am I missing something?
Heading back to the Python texts to see what I have missed.
Thanks
Heading back to the Python texts to see what I have missed.
Thanks
Please be positive and constructive with your questions and comments.