PYTHON: Serial communication with JM60 microcontroller and general.

The serial communication is so useful to generate a dynamic information exchange between a microcontroller and other devices, the advantage of that technology is higher transmission rates because of the physical connection.

In this post, we will see the methods for sending and receiving data with Python 3, the microcontroller programming will be seen another day.

First, a Serial object was created with "port" and "baudrate" attributes, if you are using Linux, you can see the port of the communication device using the dmesg command tool, for more information, type "man dmesg" into a terminal window.

The baudrate attribute is the bits per second communication speed, both devices should be configured with the same baudrate for communication to work. Standard baudrate used for most applications is 9600, but you can change it to any value the microcontroller can handle.[1]

The code explains itself!.
import serial 

ser = serial.Serial(
port='COM10',
baudrate=9600,
)

if not ser.isOpen():
   ser.open()


SENDING

Next, you can send or receive data from the serial port. There are two ways to do that. First, if you want to send a single character or a constant string, type:
ser.write(b"A")

The b before the string is the key part of the code, it converts the string type to byte type directly, it is necessary to use the write method. If you want to send a variable string, then the conversion from string to bytearray type is needed.
sp = input("Send a command= ")
sp_ba = bytearray(sp+'\n',"UTF-8")
ser.write(sp_ba)
The trick is to make a conversion of the string to a bytearray adding a '\n' jump character.

RECEIVING

To receive you can call the inWaiting method, it tells you if there is some buffered data waiting to be received.

The code below sleeps for one second waiting for the serial port to end for sending , then reads one byte at a time while it's still buffered to read.

In order to correctly use the received data as string, for example, you need to decode the received buffer as UNICODE, so you can see some symbols as °

time.sleep(1) 
while ser.inWaiting() > 0: 
   out += ser.read(1)

out_data = out.decode("unicode_escape")
Have a good code
Chameleon

REFERENCES
[1]"Serial Communication - learn.sparkfun.com", Learn.sparkfun.com, 2016. [Online]. Available: https://learn.sparkfun.com/tutorials/serial-communication/rules-of-serial. [Accessed: 16- Jun- 2016].

[2]"Installing pyserial under linux:Serial Begin", M8051.blogspot.com.co, 2016. [Online]. Available: http://m8051.blogspot.com.co/2013/03/installing-pyserial-under-linuxserial.html. [Accessed: 16- Jun- 2016].

No comments

Powered by Blogger.