RS485 Wind Speed Sensor on Raspberry Pi with Python

userHead Lars.Ullmer 2023-11-16 22:58:36 316 Views0 Replies

I am using a Raspberry Pi 3 and the wind speed sensor SEN0483 (see https://wiki.dfrobot.com/RS485_Wind_Speed_Transmitter_SKU_SEN0483) which is connected by a USB to RS485 module.

I want to read the data send by the wind speed sensor using Python code. For this I use the following code (based on the provided code in C in the wiki):

 

import serial
import time

def addedCRC(buf, len):
   crc = 0xFFFF
   for pos in range(len):
       crc ^= int.from_bytes(buf[pos], byteorder='big')
       for i in range(8, 0, -1):
           if (crc & 0x0001) != 0:
               crc >>= 1
               crc ^= 0xA001
           else:
               crc >>= 1
   buf[len] = crc % 0x100
   buf[len + 1] = crc // 0x100

def CRC16_2(buf, len):
   crc = 0xFFFF
   for pos in range(len):
       crc ^= int.from_bytes(buf[pos], byteorder='big')
       for i in range(8, 0, -1):
           if (crc & 0x0001) != 0:
               crc >>= 1
               crc ^= 0xA001
           else:
               crc >>= 1
   crc = ((crc & 0x00ff) << 8) | ((crc & 0xff00) >> 8)
   return crc

def read_wind_speed(address):
   serial_port = '/dev/ttyUSB0'  # Anpassen je nach USB-Adapter-Anschluss
   baud_rate = 9600
   ser = serial.Serial(serial_port, baud_rate, timeout=1)

   try:
       COM = bytearray([address, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00])
       addedCRC(COM, 6)
       ser.write(COM)
       ret = False
       wind_speed = 0

       while not ret:
           if ser.in_waiting > 0:
               ch = ser.read(1)
               if ch[0] == address:
                   data = ch
                   ch = ser.read(1)
                   if ch[0] == 0x03:
                       data += ch
                       ch = ser.read(1)
                       if ch[0] == 0x02:
                           data += ch
                           data += ser.read(4)
                           crc = CRC16_2(data, 5)
                           if crc == (data[5] * 256 + data[6]):
                               ret = True
                               wind_speed = (data[3] * 256 + data[4]) / 10.0

   except serial.SerialException as e:
       print('serial error:', e)

   ser.close()
   return wind_speed


sensor_address = 0x01


wind_speed = read_wind_speed(sensor_address)
if wind_speed != 0:
   print('wind speed:', wind_speed, 'm/s')
else:
   print('error')

 

The code does not work as I obtain “error”.

 

Is there any Python code provided already for this sensor or does anyone have a working code to read the wind speed with Python?

 

Thank you in advance!