Broken serial (uart) communication out-of-the-box with nanopi M1

Having issues with your DietPi installation or found a bug? Post it here.
Post Reply
Posts: 1
Joined: Mon May 31, 2021 10:30 pm

Broken serial (uart) communication out-of-the-box with nanopi M1

Post by dired »

Hello dear colleagues,

I have the MH-Z19c IR-CO2 sensor, that can be controlled via uart (or pwm but not going there).
I wanted to use it with a NanoPi M1.

Hence I flashed the DietPi_NanoPiM1-ARMv7-Buster image, activated uart1 in /boot/armbianEnv.txt , unmasked /dev/ttyS1 via dietpi-config, and tried to read sensor values with a very simple python3 script:

Code: Select all

import serial
import time

def mh_z19():
    ser = serial.Serial('/dev/ttyS1',
    while 1:
        print('command written', result)
        print('read done',len(s))
        if len(s) >= 4:
            if s[0] == 0xff and s[1] == 0x86:
                print ( {'co2': s[2]*256 + s[3]} )

if __name__ == '__main__':
    print('hello world')
    value = mh_z19()
Now with that, I was not receiving 9 bytes. Maybe once in the 4 hours that I tried debugging. What I received instead was a varying number of bytes, most often times only 3 (which I know now were the last 3 bytes). When I received e.g. 7 or 8 bits, since the first 2 bytes are fixed, I could "extract" the values, but that did not happen reliably at all. Also, after a short time (~20 seconds), it reliably only continued to read 0 bytes. Decreasing the baudrate slightly gave slightly different results, but I was never able to read the expected 9 bytes properly.

At this point I was close to believing that either my sensor doesn't work or that I need to use c to properly use serial communication.
Hence I tried the simple loopback-script (connecting not the sensor but TX to RX) from ... _linux/src (modified to use my ttyS1).
The output was very strange, partial strings mangled together, or (running it a second and third time) empty responses from TX.

I also tried to use another UART (uart2 = /dev/ttyS2) with the same results!

As a last resort, I installed armbian (not dietpi).
Now with armbian, it works as expected. Reading 9 bytes continuously without problems with python.

Hence the problem lies not in the sensor, it's in the dietpi OS somewhere. After several hours of trying to debug it I concluded that I can't find the source of problems.

If there is increased interest, I can record the outputs I was talking about, do a dietpi-bugreport, or inspect some other "part" of my setup that you ask for.
Otherwise I don't need help since I solved the situation for me, I post this only for others with this problem to be able to find a reference to it on the internet / possibly improve dietpi by fixing this bug.

Best Regards \o
Post Reply