0

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();
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. So I had to send one byte at a time, but add a 10 ms delay as well. Seems like python will send the entire message at a time while hyperterminal sends one byte at a time. getchar() seemed to look at the first char and then the rest of the data was lost with pyserial. One small changes to the for loop code above is b must be converted to a byte first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.