You are on page 1of 2

/Users/jaycesheachow/Public/arduino_com.

py
Saved: 12/16/15, 9:08:05 PM
1
2
3

Page 1 of 2
Printed For: Jayce Shea Chow

#!/usr/bin/env python
import serial
import time

4
5
6

""" Base structure for communicating with ROS """


""" ## = required for all ros programs, # = specific to this example """

7
8
9

import rospy ##import ros


from std_msgs.msg import String, Int16MultiArray #import the ros messages we

10
11
12
13
14
15

class ComHandler(object): #classes make things better, promise


""" This class encompasses the entire node """
def __init__(self):
''' setup ROS stuff '''
rospy.init_node('message_counter') ## initialize node

16
17
18

rospy.Subscriber('data_array', Int16MultiArray, self.send_data) # li


self.pub = rospy.Publisher('errors', String, queue_size=10) # publis

19
20

self.ser = serial.Serial('/dev/ttyUSB0')

21
22
23
24

while self.ser.inWaiting <= 0:


time.sleep(1)
print self.ser.read()

25
26
27
28

''' initialize variables to use later '''


self.data = [1, 2, 3, 4, 5, 6]
self.msg = "no coms yet"

29
30
31
32

def send_data(self, msg):


""" Runs every time another node publishes to the chatter topic """
# note, nothing in here is ROS specific, it's just python code that

33
34
35
36
37
38
39
40
41

#print msg.data
self.data = msg.data #print the recieved message
print self.data
for num in self.data:
self.ser.write('a')
self.ser.write(str(num))
self.ser.write(',')
self.ser.write('\n')

42
43
44
45

def run(self):
""" main run loop """

/Users/jaycesheachow/Public/arduino_com.py
Saved: 12/16/15, 9:08:05 PM
46
47

Page 2 of 2
Printed For: Jayce Shea Chow

r = rospy.Rate(2) ## sets rate for the program to run (Hz)


while not rospy.is_shutdown(): #instead of while true, otherwice crt

48
49
50
51
52
53
54
55
56
57
58
59

response = ''
if self.ser.inWaiting() > 0:
response += self.ser.readline()
if response[0] == '0':
#print response
self.msg = "no error"
elif response[0] == '1':
print "list length error"
self.msg = "list length error"
else:
self.msg = "error"

60
61
62

self.pub.publish(self.msg) #publish message to 'chatter_count' t

63
64

r.sleep() ## wait until next time this code should run (accordin

65
66
67
68
69
70

if __name__ == '__main__':
"run above code"
node = ComHandler()
node.run()

You might also like