# Serial read with python

**URL:** <https://discuss.python.org/t/serial-read-with-python/16925>\
**Category:** Python Help\
**Tags:** help\
**Created:** [June 29, 2022, 2:19pm UTC](https://discuss.python.org/t/serial-read-with-python/16925 "2022-06-29T14:19:03Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![juniorprogrammer](https://avatars.discourse-cdn.com/v4/letter/j/e9a140/32.png) [@juniorprogrammer](https://discuss.python.org/u/juniorprogrammer)\
**Post date:** [June 29, 2022, 2:19pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/1 "2022-06-29T14:19:03Z")

</div>

Hi,

Firstly I’m new with python. I’m trying to read values on the serial line to plot a graph. In my serial monitor putty everything is in the right way printed on the serial line.

But when I’m trying to read it with python it adds an character and because of this the graph can not be plotted.  
 ![image](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/d/da97e23b90307f3f2859ea9b76581672a45ef18c.png)

Can someone help me out where this character comes from and how I can get rid of it?

Kind regards,

JP

---

<div class="post-metadata">

**Author:** ![juniorprogrammer](https://avatars.discourse-cdn.com/v4/letter/j/e9a140/32.png) [@juniorprogrammer](https://discuss.python.org/u/juniorprogrammer)\
**Post date:** [June 29, 2022, 2:19pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/2 "2022-06-29T14:19:51Z")

</div>

It add an \x but don’t filters it with data.decode()

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [June 29, 2022, 3:21pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/3 "2022-06-29T15:21:20Z")

</div>

Welcome, JP!

We will be able to help you better if you post your code and data as characters (no screen images).

Post code and data between backtics like this:

> ```  
> \<code here\>  
> ```

  

> [@juniorprogrammer](#):
>
> It add an \x

Yes, it appears that Python is not decoding the `\x00` byte. However, the problem is probably not with Python.

Serial communication is simple, but also complex and not easy.

What is your programming experience before Python?

Have you worked with serial communication before?

It looks like your port settings might be wrong. Do you know what settings your serial connection uses? It appears that your STOPBITS are too small or BYTESIZE is too large and Python is receiving a control byte along with the data bytes.

```auto
import serial

ser = serial.Serial(
    port='/COM4',
    baudrate=57600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

while(True):
    print(ser.readline())

ser.close()

```

---

<div class="post-metadata">

**Author:** ![juniorprogrammer](https://avatars.discourse-cdn.com/v4/letter/j/e9a140/32.png) [@juniorprogrammer](https://discuss.python.org/u/juniorprogrammer)\
**Post date:** [June 29, 2022, 3:32pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/4 "2022-06-29T15:32:02Z")

</div>

Hi Leland,

I’m not familiar with python, but I can do things with C. I use an nrf52840 to send adc values over ble. This is the client side. I do receive the values with an ble dongle and try to read it to plot it in a graph. This is the python code I found online and give it a try:

```auto
import serial
import matplotlib.pyplot as plt

plt.ion()
fig=plt.figure()

i=0
x=list()
y=list()
i=0
ser = serial.Serial('COM7',115200)
ser.close()
ser.open()
while True:

    data = ser.readline()
    print(data.decode())
    #x.append(i)
    #y.append(data.decode())

    #plt.scatter(i, float(data.decode()))
    #i += 1
    #plt.show()
    #plt.pause(0.0001) # Note this correction

```

Is this enough to understand the problem? Sorry for the missing code.

Kind regard,

JP

---

<div class="post-metadata">

**Author:** ![juniorprogrammer](https://avatars.discourse-cdn.com/v4/letter/j/e9a140/32.png) [@juniorprogrammer](https://discuss.python.org/u/juniorprogrammer)\
**Post date:** [June 29, 2022, 3:37pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/5 "2022-06-29T15:37:29Z")

</div>

> [@mlgtechuser](#):
>
> ```auto
> import serial
> 
> ser = serial.Serial(
> port='/COM4',
> baudrate=57600,
> parity=serial.PARITY_ODD,
> stopbits=serial.STOPBITS_TWO,
> bytesize=serial.SEVENBITS
> )
> 
> while(True):
> print(ser.readline())
> 
> ser.close()
> 
> ```

This is what I get:

```auto
b'0.03\r\n'
b'\x000.03\r\n'
b'\x000.03\r\n'
b'\x000.03\r\n'

```

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [June 29, 2022, 4:14pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/6 "2022-06-29T16:14:54Z")

</div>

The settings need to be specifically for your serial connection. It looks like you’re picking up an extra byte in your data that is actually part of the previous data packet. This is why the `\x00` is _ **not** _ in the first data value.

I can’t help you find the correct settings. Sometimes you just have to try different settings until it works.

I usually write nested loops to auromatically try all possible settings. Even it it takes 40 minutes to write and run the code, it will still be faster than performing _and tracking_ hundreds of manual tests.

---

<div class="post-metadata">

**Author:** ![juniorprogrammer](https://avatars.discourse-cdn.com/v4/letter/j/e9a140/32.png) [@juniorprogrammer](https://discuss.python.org/u/juniorprogrammer)\
**Post date:** [June 29, 2022, 4:18pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/7 "2022-06-29T16:18:49Z")

</div>

Where does this go wrong now? Do I have to fix it on python or on my dongle software?

```auto
float(data.replace(b'\x00', b'').decode())

```

This worked for now, but I still don’t know where it exactly goes wrong?

---

<div class="post-metadata">

**Author:** ![vbrozik](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/vbrozik/32/7423_2.png) [@vbrozik](https://discuss.python.org/u/vbrozik)\
**Post date:** [June 29, 2022, 4:54pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/8 "2022-06-29T16:54:02Z")

</div>

I think it is practically impossible that wrong parameter settings of the serial port would cause it to read extra `NUL` characters (`b'\x00'`, also called null character) and otherwise read correct data. It looks like your device sends null-terminated records. PuTTY and other terminals do not show `NUL` characters.

The following code should resolve the problem. Just add the serial port parameters (`baudrate` etc.) as needed, adjust the timeout and you will probably want to collect the received values into a list (`your_list.append(value)`).

```python
import serial

with serial.Serial(
        port='COM4', timeout=5 # set your parameters as needed, reading timeout 5 seconds
        ) as ser:
    while True:
        record = ser.read_until(expected=b'\x00') # read null-terminated record
        if not record or record[-1] != 0: # incomplete record read means timeout
            break
        value = float(record.rstrip(b'\r\n\x00')) # remove CR, LF and NUL at the end
        print(value) # do whatever with the value

```

I tested that `float()` can convert directly from `bytes`, it treats the characters as ASCII and calling `.decode()` is not needed.\[1\]

* * *

1. There is this open issue [Explicitly mention bytes and other buffers in the documentation for float() · Issue #77748 · python/cpython · GitHub](https://github.com/python/cpython/issues/77748) because documentation does not describe this possibility.

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [June 30, 2022, 4:38am UTC](https://discuss.python.org/t/serial-read-with-python/16925/9 "2022-06-30T04:38:14Z")

</div>

You can adjust the settings at your dongle OR in your python program. They just need to be _ **the same** _.

With serial connections, the main ‘best practice’ is to start with low speeds (like 9600) and get _ **everything else** _ working before increasing the speed.

html test

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [June 30, 2022, 10:48am UTC](https://discuss.python.org/t/serial-read-with-python/16925/10 "2022-06-30T10:48:07Z")

</div>

> [@vbrozik](#):
>
> I think it is practically impossible that wrong parameters would cause the port to insert null characters (`b'\x00'`) and otherwise read correct data

Error checking active only on the transmitting side will add a checksum to the data packet that is then mishandled on the receiving side. The checksum can be any number of bytes.

> [@mlgtechuser](#):
>
> Serial communication is simple, but also complex and not easy.

(I tried to warn everyone. 😜 )

![image](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/2/270ac9e3976b5f705764ae9157212d9e69fa0899.png)

The `'\x00'` appears to be a two-byte checksum added by the sending device. @juniorprogrammer, what is your dongle talking to? That is the device that might be adding an error detection checksum. If the receiving device isn’t expecting a checksum in the data, it will treat the checksum as data. If the receiving device _ **is** _ expecting a checksum and it knows how many bytes are in the checksum, then the receiving device will strip out the checksum.

PuTTY is stripping off the extra two bytes after the `\r\n`. The PuTTY manual refers to detecting CRC errors but doesn’t say anything about enabling Error Checking, so it might be ‘always enabled’ internally. _ **If** your dongle can be set to use CRC_ (or whatever error checking the sending device is using), then your dongle will strip the extra byte (assuming it’s a checksum). There is also one more setting to check: Flow Control.

![image](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/1/133aa4f70eea1a873efd61f2a3edb82e9ba8b2ef.png)

The `serial.Serial()` class has a flow control argument, so check the PuTTY ‘Flow Control’ setting above and put one of these in your `ser = serial.Serial()` statement to use the same flow control that PuTTY is using.

```auto
xonxoff=True,
rtscts=True,

```

THEN… &nbsp;Get the serial settings of the transmitting (sending) device and look for error checking enabled. _And make sure **both sides** of the serial link have the same settings_–including the error checking.

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [June 30, 2022, 11:00am UTC](https://discuss.python.org/t/serial-read-with-python/16925/11 "2022-06-30T11:00:33Z")

</div>

Future Step: Once it’s talking and you’re receiving data, you might need to specify the encoding. It looks like you’re only sending basic numerals and a decimal point, though, so the encoding probably won’t be a factor.

```auto
#for example-
msg = ser.readline().decode('utf-8').rstrip() #rstrip() drops trailing spaces.

```

Anyone reading this topic later on who _IS_ sending data with an extended character set will definitely need to specify the encoding.

---

<div class="post-metadata">

**Author:** ![vbrozik](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/vbrozik/32/7423_2.png) [@vbrozik](https://discuss.python.org/u/vbrozik)\
**Post date:** [June 30, 2022, 4:32pm UTC](https://discuss.python.org/t/serial-read-with-python/16925/12 "2022-06-30T16:32:01Z")

</div>

> [@mlgtechuser](#):
>
> The `'\x00'` appears to be a two-byte checksum added by the sending device.

I do not agree with this hypothesis (which complicate things) 🙂

- `b'\x00'` is a single byte (it is a single character in `bytes` as well as in `str`), not two
- `'\x00'` or we can write it as `'\0'`\[1\] is ASCII `NUL` character which is often used to terminate records. In C-language it is used to terminate strings. In Unix tools it is used to terminate records (for example `find ... -print0`). I am almost sure that it is this role of `b'\x00'` we see here.
- We have always seen the byte `b'\x00'` when the characters before it were `b'0.07\r\n'` or `b'0.03\r\n'`. This is highly improbable for a checksum.
- In a binary protocol\[2\] I would expect to see multiple non-ASCII characters like: field separators/headers, field lengths, padding bytes etc. This communication looks like a simple ASCII stream.

> [@mlgtechuser](#):
>
> There is also one more setting to check: Flow Control.

Yes, but this is premature. No flow-control problems have been seen in the examples of the communication. There we saw no lost characters or misinterpreted start-bits (which could mangle characters). I think the computer has no problems reading the characters at the speed the device sends them.

* * *

1. Which is a little ambiguous! It must not be followed by a digit, for example `'\052' == '*'` 

2. You expect a binary checksum - so binary protocol.

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 1, 2022, 3:01am UTC](https://discuss.python.org/t/serial-read-with-python/16925/13 "2022-07-01T03:01:35Z")

</div>

The extra data is coming from somewhere. Let’s focus on finding where it’s coming from.

As a foundation to that, both devices need to be set up the same–including error checking, whether it s checksum, CRC, or another method, and regardless of how many bytes the error checking might add (the number of bytes depends on the error checking method used).

To start fixing things without confirming settings is asking for something fundamental to be overlooked. It’s like skipping the first step in any troubleshooting procedure: “Is the device plugged in, does the receptacle it’s plugged into have power, etc.”
