Question on write the data from the robot sensor to csv file

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()

Hello @AmirulJ ,

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.

1 Like

Thank you very much @albertoezquerro I’ll try first

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()

Hello @albertoezquerro I’ve try this coding and when executing it, there are no error but the csv file is still empty. May I know why?

#! /usr/bin/env python
# lds_to_csv_node.py

import rospy
import csv
from sensor_msgs.msg import LaserScan

# Global vars
csv_writer = None

def scan_callback(msg):
    d = msg.ranges [90]
    print d
    if csv_writer is not None:
        csv_writer.writerow(d)

def main():
    rospy.init_node("lds_to_csv")
    sub = rospy.Subscriber('/scan', LaserScan, scan_callback)
    fh = open("\\testread.csv", "wb")
    csv_writer = csv.writer(fh) # More constant params
    rospy.spin()
    fh.close()
    csv_writer = None

if __name__ == '__main__':
    main()

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.