在pyfirmata中,如何为字符串消息设置处理程序?

时间:2013-09-24 21:02:04

标签: python arduino

如何设置处理程序以从Arduino UNO接收pyfirmata中的消息?

我有以下Python代码:

from logic.ModuleClass import Module
from events.EventDispatcherClass import Event
from pyfirmata import Arduino, util
import pyfirmata

class Comm(Module):
    """
    Handles the communication between python and arduino
    AttachTo: ""
    """

    NAME = "Communicator"

    def __init__(self, port):
        super(Comm,self).__init__(Comm.NAME)
        self.board = Arduino(port)
        # start an iterator thread so that serial buffer doesn't overflow
        it = util.Iterator(self.board)
        it.start()

        self.board.add_cmd_handler(pyfirmata.pyfirmata.STRING_DATA, self._messageHandler)

    def _messageHandler(self, *args, **kwargs):
        print args

    def update(self):
        super(Comm,self).update()

    def writeData(self,data):
        #print data
        self.board.send_sysex(pyfirmata.pyfirmata.STRING_DATA,data)

    def dispose(self):
        super(Comm,self).dispose()
        try:
            self.board.exit()
        except AttributeError:
            print "exit() raised an AttributeError unexpectedly!"+self.toString()

在Arduino上,我发送了一个字符串:

Firmata.sendString("test");

我添加了_messageHandler(self,* args,** kwargs),我收回了我认为是字符代码的集合。我是python的新手,我不太确定如何获得从Arduino发送的原始字符串

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

要将从arduino发送的字符串转换为pyfirmata,只需在python中使用以下代码:

def _messageHandler(self, *args, **kwargs):
    print util.two_byte_iter_to_str(args)

那应该返回你期待的字符串。 FTW!