Raspberry Pi(Debian)上的Twisted Python脚本通过USB与Arduino通信

2024-10-01 17:42:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在从事一个Arduino/Raspberry Pi项目,在这个项目中,我发现自己不仅学习Python,还学习Twisted Python;因此,我提前为我的新手道歉。我现在尽量保持简单,只想在两个设备之间的任何时候发送一个字符。在

到目前为止,我能够从树莓派派到阿尔杜诺,并有效地关闭了它的LED灯,正如预期的那样。然而,我似乎不能生成扭曲的代码来检测从Arduino到串行端口上的RPi的任何东西。我通过在RPi上运行的Arduino程序员中的串行监视器应用程序验证了Arduino每2秒发送一次字符。在

下面的代码在RPi上运行,接收一个GET请求,并通过串行端口将部分数据传递给Arduino。但我似乎无法让这些代码监听同一个串行端口。:/我已经为此工作了一个多月了,似乎被卡住了。我只是似乎找不到Twisted Python在线接收串行数据的好例子;或者至少找一个我理解的例子。不管怎样,到目前为止我所掌握的是:

import sys
from urlparse import urlparse
from twisted.web import server, resource
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.serialport import SerialPort

serServ = None

class USBclient(Protocol):
    def connectionMade(self):
        global serServ
        serServ = self
        print 'Arduino device: ', serServ, ' is connected.'

    def cmdReceived(self, cmd):
        serServ.transport.write(cmd)
        print cmd, ' - sent to Arduino.'
        pass

    def serialReadEvent(self):      #maybe it should be: doRead()? Couldn't get either to work.
        print 'data from arduino is at the serial port!'

class HTTPserver(resource.Resource):
    isLeaf = True
    def render_GET(self, request):      #passes the data from the get request
        print 'HTTP request received'
        myArduino = USBclient()
        stringit = str(request)
        parse = stringit.split()
        command, path, version = parse
        myArduino.cmdReceived(path)

class cmdTransport(Protocol):
    def __init__(self, factory):
        self.factory = factory

class cmdTransportFactory(Factory):
    protocol = cmdTransport

if __name__ == '__main__':
    HTTPsetup = server.Site(HTTPserver())
    reactor.listenTCP(5000, HTTPsetup)
    SerialPort(USBclient(), '/dev/ttyACM0', reactor, baudrate='115200')
    reactor.run()

正如你所看到的,代码只是在串行端口上寻找任何东西,但我似乎不能让这种神奇发生。提前谢谢,任何帮助都将不胜感激!在


Tags: 端口代码fromimportselfrequestdeftwisted
1条回答
网友
1楼 · 发布于 2024-10-01 17:42:22

由此判断:http://twistedmatrix.com/trac/browser/tags/releases/twisted-12.3.0/twisted/internet/_win32serialport.py#L84您应该查看Protocol子类的dataReceived(self,…)方法

因此:

class USBclient(Protocol):
    def connectionMade(self):
        global serServ
        serServ = self
        print 'Arduino device: ', serServ, ' is connected.'

    def cmdReceived(self, cmd):
        serServ.transport.write(cmd)
        print cmd, ' - sent to Arduino.'
        pass

    def dataReceived(self,data):      
        print 'USBclient.dataReceived called with:'
        print str(data)

试试这个看看能不能用。在

相关问题 更多 >

    热门问题