Robin2:
This Python - Arduino demo may be of interest.Also see Serial Input Basics - simple reliable ways to receive data.
...R
Hi Robin2,
Excellent work on the 'ComArduino2.py'.
Any chance on a python 3 version of this code?
I'm suffering with the below error. (the arduino code works fine of course)
#=====================================
# Function Definitions
#=====================================
def sendToArduino(sendStr):
ser.write(sendStr)
#======================================
def recvFromArduino():
global startMarker, endMarker
ck = ""
x = "z" # any value that is not an end- or startMarker
byteCount = -1 # to allow for the fact that the last increment will be one too many
# wait for the start character
while ord(x) != startMarker:
x = ser.read()
# save data until the end marker is found
while ord(x) != endMarker:
if ord(x) != startMarker:
ck = ck + x
byteCount += 1
x = ser.read()
return(ck)
#============================
def waitForArduino():
# wait until the Arduino sends 'Arduino Ready' - allows time for Arduino reset
# it also ensures that any bytes left over from a previous message are discarded
global startMarker, endMarker
msg = ""
while msg.find("Arduino is ready") == -1:
while ser.inWaiting() == 0:
pass
msg = recvFromArduino()
print(msg)
#======================================
def runTest(td):
numLoops = len(td)
waitingForReply = False
n = 0
while n < numLoops:
teststr = td[n]
if waitingForReply == False:
sendToArduino(teststr)
print("Sent from PC -- LOOP NUM " + str(n) + " TEST STR " + teststr)
waitingForReply = True
if waitingForReply == True:
while ser.inWaiting() == 0:
pass
dataRecvd = recvFromArduino()
print("Reply Received " + dataRecvd)
n += 1
waitingForReply = False
print("===========")
time.sleep(5)
#======================================
# THE DEMO PROGRAM STARTS HERE
#======================================
import serial
import time
# NOTE the user must ensure that the serial port and baudrate are correct
serPort = "COM4"
baudRate = 9600
ser = serial.Serial(serPort, baudRate)
print("Serial port " + serPort + " opened Baudrate " + str(baudRate))
startMarker = 60
endMarker = 62
waitForArduino()
testData = []
testData.append("<LED1,200,0.2>")
testData.append("<LED1,800,0.7>")
testData.append("<LED2,800,0.5>")
testData.append("<LED2,200,0.2>")
testData.append("<LED1,200,0.7>")
runTest(testData)
ser.close
Error:
Traceback (most recent call last):
File "C:/ComArduino2.py", line 158, in <module>
waitForArduino()
File "C:/ComArduino2.py", line 102, in waitForArduino
msg = recvFromArduino()
File "C:/ComArduino2.py", line 80, in recvFromArduino
ck = ck + x
TypeError: can only concatenate str (not "bytes") to str