Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.

I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.

How do you do this in Pyserial?

Here's the code I tried which doesn't work. It reads the lines sequentially.

import serial

import time

ser = serial.Serial('com4',9600,timeout=1)

while 1:

    time.sleep(10)

    print ser.readline() #How do I get the most recent line sent from the device?

1 Answer

0 votes
by (16.8k points)

Using this code, you can easily read the last line from your serial device

from serial import *

from threading import Thread

last_received = ''

def receiving(ser):

    global last_received

    buffer = ''

    while True:

        # last_received = ser.readline()

        buffer += ser.read(ser.inWaiting())

        if '\n' in buffer:

            last_received, buffer = buffer.split('\n')[-2:]

if __name__ ==  '__main__':

    ser = Serial(

        port=None,

        baudrate=9600,

        bytesize=EIGHTBITS,

        parity=PARITY_NONE,

        stopbits=STOPBITS_ONE,

        timeout=0.1,

        xonxoff=0,

        rtscts=0,

        interCharTimeout=None

    )

    Thread(target=receiving, args=(ser,)).start()

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...