[Tutor] Converting a string to a byte array
Phil
phil_lor at bigpond.com
Sun Sep 24 19:29:05 EDT 2017
On 25/09/17 07:26, Cameron Simpson wrote:
Thank you Cameron and Peter for your replies.
>> I don't understand why this works from the pyqt IDE but not when run
>> from the console. I suppose the IDE is adding the correct encoding.
>
> I'm guessing the IDE is python 2 and not doing any encoding at all. In
> python 2 str _is_ effectively bytes and if you stay in ASCII you just
> get away with it.
>
No, the IDE is Eric and as far as I know it's python3 only. Just for
interest I amended my code to use what you provided and tried it under
IDLE. There aren't any errors but but my Arduino is not responding.
However, if I enter python3 mycode.py then it works perfectly. I'm sure
there's an explanation for this. I have thoney, another python IDE, on a
raspberrypi I'll try that later and see what the result is. Anyway, it
works from Eric and from the command prompt.
> So you need to know what your serial device expects. ASCII only?
As it turns out, it doesn't matter if the data is ASCII or UTF-8.
> mytext = "Fred"
> mytext = mytext + "\n"
> mybytes = mytext.encode('utf-8')
> ser.write(mybytes)
>
> Notice that I've appended the newline _before_ converting to bytes,
Thank you for the code and the explanation, it's greatly appreciated.
It's all a bit of an anticlimax really. Now that it works I don't know
what to do with it. Like so many of my projects.
--
Regards,
Phil
More information about the Tutor
mailing list