This is my code from the sensor, I can print it in the terminal but I cant write it in the csv file automatically. Can someone help me to solve this problem. Thank you in advance!
#! /usr/bin/env python
import rospy
import csv
from sensor_msgs.msg import LaserScan
def callback(msg):
d = msg.ranges [90]
print d
rospy.init_node("read")
sub = rospy.Subscriber('/scan', LaserScan, callback)
rospy.spin()
f= open("\\testread.csv", "w")
c=csv.writer(f)
for x in range(1000):
c.writerow(d)
f.close()
Are you getting any error messages there? In any case, having a quick look at your code, it looks like the variable “d” , which contains the laser data, is local to the callback function. If you try to use it outside that function, like you are doing here:
c.writerow(d)
it won’t work. To fix this, you should define this variable before the callback function.
Hello @albertoezquerro I’ve try this coding by using global variables, but it still wont work. I got the squence expected error. Can you show me the right coding? Thank you
#! /usr/bin/env python
import rospy
import csv
from sensor_msgs.msg import LaserScan
def callback(msg):
global d
d = msg.ranges [90]
print d
rospy.init_node("read")
sub = rospy.Subscriber('/scan', LaserScan, callback)
rospy.spin()
f= open("\\testread.csv", "w")
c=csv.writer(f)
for x in range(5)
c.writerow(d)
f.close()
and this I’ve try to define new function but still error
#! /usr/bin/env python
import rospy
import csv
from sensor_msgs.msg import LaserScan
def laser_ranges()
global d
d = msg.ranges [90]
print d
def callback(msg):
laser_ranges()
rospy.init_node("read")
sub = rospy.Subscriber('/scan', LaserScan, callback)
rospy.spin()
f= open("\\testread.csv", "w")
c=csv.writer(f)
for x in range(5)
c.writerow(laser_ranges())
f.close()