我正在使用ros消息驱动LED。 我已经编写了一个Python脚本来管理消息接收并驱动WS2812 leds
我正在使用rpi_ws281x驱动LED(https://github.com/jgarff/rpi_ws281x)。
这是python代码:
#!/usr/bin/env python
from neopixel import *
from ina219 import INA219
from ina219 import DeviceRangeError
import rospy
from std_msgs.msg import String
import json
import simplejson
def updateLeds(leds):
for index, item in enumerate(leds):
print(index, item)
strip.setPixelColor(index, item)
strip.show()
def updateLed(led, color):
strip.setPixelColor(led, color)
rospy.loginfo("Initializing leds")
# LED strip configuration:
LED_COUNT = 4 # Number of LED pixels.
LED_PIN = 10 # GPIO pin connected to the pixels
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 40 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
rospy.init_node('leds_listener', anonymous=True)
rospy.loginfo("Initializing leds")
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
strip.setPixelColor(0, Color(255, 0, 0)) #GRB
strip.setPixelColor(1, Color(0, 255, 0))
strip.setPixelColor(2, Color(0, 0, 255))
strip.setPixelColor(3, Color(255, 255, 0))
strip.show()
ledColors = [Color(0, 0, 0), Color(0, 0, 0), Color(0, 0, 0), Color(0, 0, 0)]
updateLeds(ledColors)
rospy.loginfo("Initializing leds ok")
def callback(data):
rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.data)
try:
#parse the json
jsonData = simplejson.loads(data.data)
#check the mode
if jsonData["mode"].lower() == "basic":
led = int(jsonData["values"]["led"])
color = int(jsonData["values"]["color"], 16)
print("led:", led, "color", color)
ledColors[led] = color
#updateLeds(ledColors)
updateLed(led, color)
strip.show()
except ValueError as e:
rospy.logerr("Unable to parse json input ( %s ): %s", data.data, e)
def leds_listener():
rospy.Subscriber('leds', String, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
try:
leds_listener()
except rospy.ROSInterruptException:
pass
这是字符串形式的json消息
#examples of valid message
{
"mode" : basic,
"values" : {
"led" : "0",
"color" : "FF0033"
}
}
我通过发送消息 rostopic使用以下行:
export MY_MSG="data: '{\"values\": {\"color\": \"00FF00\", \"led\": \"1\"}, \"mode\": \"basic\"}'";rostopic pub -1 leds std_msgs/String "$MY_MSG"
它运行良好。
但是现在我想定期发送它,所以我使用下面的逗号行:
export MY_MSG="data: '{\"values\": {\"color\": \"00FF00\", \"led\": \"1\"}, \"mode\": \"basic\"}'";rostopic pub -r 0.2 leds std_msgs/String "$MY_MSG"
该软件向我显示了相同的日志输出,但行为确实不同。所有LED都无法正确驱动LED,而是变成最大值的白色。
定期发送一次消息有什么区别?