Reputation: 1921
I'm trying to communicate between my PC and a microcontroller (MC). My microcontroller will read using getchar()
until 4 characters have been read or it bumps into the characters '\0'
, '\'
, or '\r'
.
The communication works perfectly fine with hyper-terminal. However, my python script doesn't seem to be sending '\0'
, '\'
, or '\r'
when encoding an input string and concatenating with one those special characters to it.
command = input("Enter Command: ")
port.write(bytes(command + '\n', 'UTF-8'))
So if I entered the command x
it should send 'x'
and'\n'
and the MC should stop waiting for more characters to read because of the new line. However, if I enter only x
, the MC will wait for 4 more characters to read.
How do I convert my string with the special characters properly to bytes? Thanks.
The MC code is:
buffer[ii] = getchar();
while(buffer[ii] != '\0' && buffer[ii] != '\n' && buffer[ii] != '\r' && ii < 4 - 1)
{
buffer[++ii] = getchar();
}
Upvotes: 0
Views: 8425
Reputation: 7944
You can convert a string into an array of integers 0 <= N <= 256 by either:
map(ord,command+'\n')
or
bytearray(command+'\n',"UTF-8")
If you had to write each byte one by one to the port:
>>> for b in bytearray("message\n","UTF-8"):
... port.write(b)
Should do the trick.
Upvotes: 1