4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ROS topicを読み取ってcsvに保存する

4
Last updated at Posted at 2019-09-02

はじめに

Rosbagで取ったデータをぱぱっとExcelとかLibre Office Impressに入れてグラフ書きたいなと思って,ささっと書いたコードです.役に立ったら嬉しいです.

環境

Ubuntu 16.04
ROS kinetic

コード

topic2csv.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-

import rospy
from std_msgs.msg import Float32
import os

path = "my_message.csv"
count = 0

def callback(msg):
    global count
    global value
    value = msg.data
    rospy.loginfo("value: %f", value)

    buf = str(count) + "," + str(value) + "\n"
    with open(path, mode='a') as f:
        f.write(buf)
    count+=1



def listener():

    rospy.init_node('getter', anonymous=False)
    rospy.Subscriber("/my_message_topic", Float32, callback)

    rospy.spin()




if __name__ == '__main__':
    # csv fileが存在してなかったら作る
    if not os.path.isfile(path):
        f = open(path,'a')
        f.close()

    listener()

実行方法(2020/1/1追記)

実行の時は,

$ python topic2csv.py

という感じで実行してください.rosrunで実行するとうまく結果のファイルが作成されません.

結果のcsvファイル

別のターミナルで

$ rostopic pub -r 10 /my_message_topic std_msgs/Float32 32.5

とやったのを記録した結果です.

0,32.5
1,32.5
2,32.5
3,32.5
4,32.5
5,32.5
6,32.5
7,32.5
8,32.5
9,32.5
10,32.5
11,32.5
12,32.5
13,32.5
14,32.5
15,32.5
16,32.5
17,32.5
18,32.5
19,32.5
20,32.5
21,32.5
22,32.5
23,32.5
24,32.5
25,32.5
26,32.5
27,32.5
28,32.5
29,32.5
30,32.5
31,32.5
32,32.5
33,32.5
34,32.5

こんな感じです.

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?