Kundan Kumar
Kundan Kumar

Reputation: 511

Sending hexadecimal or ASCII value stored in a variable using pyserial

I was trying to send a byte containing hex value over serial port using pyserial. The hex value has to be in a variable (so that I can do some manipulations before sending). Sample code will explain my intent:

import serial  
com=serial.Serial('COM1')  
a_var=64
a_var=a_var+1
com.write(a_var)  #This of course throws error

I want to receive 'A' or 0x41 on the other side. I could send hex using

    com.write(b'\x41') 

but not using a variable. Converting it to string or character or encoding the string did not help. I am using python 3.5.

Thanks

Upvotes: 1

Views: 10894

Answers (2)

Kundan Kumar
Kundan Kumar

Reputation: 511

bytearray can be used to send bytes (as hex or ascii). They are mutable, hence numerical manipulations are possible. Any number of bytes can be sent using it.

import serial

com=serial.Serial('COM2')
elements=[65,67,69,71]      #Create an array of your choice
a_var=bytearray(elements)   #Create byte array of it
com.write(a_var[0:3])       #Write desired elements at serial port

a_var[0]=a_var[0]+1         #Do your mathematical manipulation

com.write(a_var[0:1])       #Write again as desired
com.close()

Upvotes: 0

Klaus D.
Klaus D.

Reputation: 14369

At first the name choice of your variable was not optimal. input is a built-in function and you might shadow it.

There are many way to put bytes into a variable:

to_send = b'A'
to_send = b'\x41'
to_send = bytes([65])

You see how to use an ASCII character, the escape sequence for hex numbers and the list of integers.

Now send via

com.write(to_send)

Upvotes: 2

Related Questions