[Twisted-Python] serial communication - getting started

Robert Voigtländer r.voigtlaender at gmail.com
Mon Oct 21 05:35:44 MDT 2013


Hi,

I am new to Python. Trying to figure out how to use the serial port I
started with pyserial.
Works - but the CPU usage on my Raspberry Pi is at about 30% just for
reading the port. Before I started to optimize the code it was even 90+%.

So I tried twisted - and boom down to 3-4%. Even though twisted also uses
pyserial (as far as I read) - obviously better than I do.

So far so good.
With copy&paste from the internet and some editing I got the PI to read
from my Arduino. (code below)
But the code seems to be blocking. I tried putting things in a thread - but
I must have done something wrong. It is still blocking.

I also don't know how to write.
Does s.write("test") work?

Would be great if someone could help me out here.

Thanks a lot.
Robert



import logging
from twisted.protocols.basic import LineReceiver
from twisted.protocols.basic import LineReceiver

from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from twisted.python import usage
import thread

class THOptions(usage.Options):
    optParameters = [
        ['baudrate', 'b', 115200, 'Serial baudrate'],
        ['port', 'p', '/dev/ttyACM0', 'Serial port to use'],]


class Echo(LineReceiver):
    def processData(self, data):
        print(data)

    def lineReceived(self, line):
        try:
            data = line.rstrip()
            #logging.debug(data)
            self.processData(data)
            #print(line.rstrip())
            #pass
        except ValueError:
            logging.error('Unable to parse data %s' % line)
            return

def SerialInit():
    o = THOptions()
    try:
        o.parseOptions()
    except usage.UsageError, errortext:
        logging.error('%s %s' % (sys.argv[0], errortext))
        logging.info('Try %s --help for usage details' % sys.argv[0])
        raise SystemExit, 1

    baudrate = o.opts['baudrate'] #int('115200')
    port = o.opts['port']
    logging.debug('About to open port %s' % port)
    s = SerialPort(Echo(), port, reactor, baudrate=baudrate)
    reactor.run()


thread.start_new_thread(SerialInit())

if __name__ == '__main__':
    print("-----")
    s.write('123456789')
    #s.write("\n")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-python/attachments/20131021/e8ca46ec/attachment.html>


More information about the Twisted-Python mailing list