I use this script to access my Arduino board over Raspberry Pi.
I recognized two things. If I don't use "ser.flushInput()". The board hangs after some time.
The other thing is, if I use a serial->write() oder print, The board also hangs after some time.
I mean with hangs, that I get a read/write timeout() and the board shows serial data going in and out, even when nothing is sent. Anyone an idea why this is so?!
import socket
import json
import serial
from time import *
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 7000))
# whether to use or not to use this timeout is the question?!
# rtscts=1 is necessary for raspbian due to a bug in the usb/serial driver ):
ser = serial.Serial('/dev/ttyACM0', '38400', writeTimeout=0.1, rtscts=1)
#chksum calculation
def chksum(str):
c = 0
for a in str:
c = ((c + ord(a)) << 1) % 256
return c
#main loop for receiving a json string
#The checksum will get validated on every important step
def main():
while True:
# Wait for UDP packet
data, addr = sock.recvfrom(128)
# parse it
p = json.loads(data)
# if control packet, send to ardupilot
if p['type'] == 'rc_input':
str = "RC#%d,%d,%d,%d" % (p['roll'], p['pitch'], p['thr'], p['yaw'])
# calc checksum
chk = chksum(str)
# concatenate msg and chksum
output = "%s*%x\r\n" % (str, chk)
#print "Send to control board: " + output
ser.write(output)
# flushInput() seems to be extremely important
# otherwise the APM 2.5 control boards stucks after some command
ser.flushInput()
if p['type'] == 'pid_config':
str = "PID#%.4f,%.4f,%.4f;%.4f,%.4f,%.4f;%.4f,%.4f,%.4f;%.4f,%.4f,%.4f" % (
p['pit_rkp'], p['pit_rki'], p['pit_rimax'],
p['rol_rkp'], p['rol_rki'], p['rol_rimax'],
p['yaw_rkp'], p['yaw_rki'], p['yaw_rimax'],
p['pit_skp'], p['rol_skp'], p['yaw_skp'] )
# calc checksum
chk = chksum(str)
# concatenate msg and chksum
output = "%s*%x\r\n" % (str, chk)
#print "Send to control board: " + output
ser.write(output)
# flushInput() seems to be extremely important
# otherwise the APM 2.5 control boards stucks after some command
ser.flushInput()
main()