This code works just fine with the serial monitor.
Now I want to use python3 on my Mac instead of the Serial Monitor
import serial
#! /usr/local/bin/python3
import serial
from time import sleep
# for Mac
ser = serial.Serial("/dev/cu.usbmodem1D1330", baudrate=9600)
ser.write(('1').encode())
now the LED doesn't blink any more. I use the correct port /dev/cu.usbmodem1D1330 as in Ardrino. Can someone tell me what I have done wrong? Thanks
The Python code "ser.write(('1').encode())" sends the binary character b'00000001'. The Arduino code is looking for the ASCII coding of 1 which is b'00110001'
"ser.write('1')" or "ser.write(('00110001').encode())" might work better.
Thank you all for the replies. Unfortunately, none of the above suggestions work in my case.
@hammy "Connect your Mac to to the IDE serial monitor on the PC and see what it's actually sending out"
How do I do that? Every time the serial monitor open, when I run the python code, it always gives me an error "resource busy"
One thing I am very unclear is that on the Aduino side what data type I should give the ariduino serial monitor
to receive the data from python, int? char? byte?
and on the python3 side if I say ser.write('1'.encode()) in python3
what exactly the encode and should the arduino be set to receive, a char? an int? I tried both neither one works.
The problem comes from Python3 using Unicode for strings by default rather than using ASCII which is what the Arduino compiler is using.
To send the ASCII character for 1 you can explicitly use a bytes literal as follows:
ser.write(b'1')
Alternately you can specify the string and encode it as ASCII:
ser.write('1'.encode('ASCII'))
These are equivalent in that the following statement evaluates to True:
b'1' == '1'.encode('ASCII')
The data going over serial is just a single byte in this case so you should be able to put in any 8 bit data type on the Arduino side, so "char" or "byte" would work. Since it is ASCII data the convention would be to treat is as "char".