Page 1 of 1

how to receive integer from uart 1

Posted: Fri Aug 24, 2018 3:33 pm
by M.fathy
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

An alternative

Posted: Sat Aug 25, 2018 5:23 am
by pythoncoder
Try:

Code: Select all

a = '12'
t = int.from_bytes(a, 'little')
You'll find it delivers the same result as

Code: Select all

a = '12'
upper = ord(a[1])
lower = ord(a[0])
t =int((upper << 8) +lower)

Re: how to receive integer from uart 1

Posted: Sun Aug 26, 2018 8:12 am
by M.fathy
It is working thanks for your concern

Re: how to receive integer from uart 1

Posted: Mon Sep 10, 2018 4:41 am
by liudr
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.