Hello
i have solved problem with my esp32 that i want to share it with others .
Since the Uart is receive only char with 1 bytes so if you want to receive an integer with 2 bytes you must receive two char and
merge them (or combine) with each other
i simple do that
import machine
buf=''
lower='' ##global variable to the lower byte
uper='' ##global variable to the upper byte
u2=machine.UART(2, baudrate=115200, rx=16, tx=17, timeout=10)
if(u2.any()>3):
buf= u2.read(2)
uper=buf[:1]
lower=buf[1:2]
uper=ord(upper)
lower=ord(lower)
t=int((uper<<8)+lower)
print(t)
pls:
if you have any notes ,feel free to write it down
how to receive integer from uart 1
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
An alternative
Try:
You'll find it delivers the same result as
Code: Select all
a = '12'
t = int.from_bytes(a, 'little')
Code: Select all
a = '12'
upper = ord(a[1])
lower = ord(a[0])
t =int((upper << 8) +lower)
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
Re: how to receive integer from uart 1
It is working thanks for your concern
Re: how to receive integer from uart 1
I usually implement an end-of-message character and send my numbers by plain ASCII string. This way I can more easily decode the message. Another thing you can try is to use json format (still send it in with an end-of-message character such as \n). On PC side, use json module to serialize your data. On MP side, use ujson to deserialize your data. It's infinitely expandable compared with a method that only works with single 2-byte integer values. Just my 2 cents. I had to code serialization/deserialization on Arduino from scratch some years ago and won't be doing that on MP boards thanks to json modules. Hard to beat that simplicity.