how to receive integer from uart 1

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
M.fathy
Posts: 7
Joined: Mon Jun 18, 2018 1:09 pm

how to receive integer from uart 1

Post by M.fathy » Fri Aug 24, 2018 3:33 pm

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

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

An alternative

Post by pythoncoder » Sat Aug 25, 2018 5:23 am

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)
Peter Hinch
Index to my micropython libraries.

M.fathy
Posts: 7
Joined: Mon Jun 18, 2018 1:09 pm

Re: how to receive integer from uart 1

Post by M.fathy » Sun Aug 26, 2018 8:12 am

It is working thanks for your concern

User avatar
liudr
Posts: 211
Joined: Tue Oct 17, 2017 5:18 am

Re: how to receive integer from uart 1

Post by liudr » Mon Sep 10, 2018 4:41 am

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.

Post Reply