1

如何设置处理程序以从 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 发送的原始字符串

4

1 回答 1

1

我找到了解决方案:

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

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

那应该返回您期望的字符串。FTW!

于 2013-09-25T18:01:54.167 回答