Skip to content

Instantly share code, notes, and snippets.

@lukasMega
Last active June 24, 2024 09:25
Show Gist options
  • Save lukasMega/ec7d0d8187dde7c1ebe49f72b0549eab to your computer and use it in GitHub Desktop.
Save lukasMega/ec7d0d8187dde7c1ebe49f72b0549eab to your computer and use it in GitHub Desktop.
Modbus RS-485 temperature & humidity sensor from Aliexpress

Sensor details

Name

  • XY-MD02 Temperature and Humidity Transmitter Detection Sensor Module Modbus SHT40 Temperature Sensor RS485 Signal Analog

URL

Description

  • Parameters:
    Product name: temperature and humidity transmitter
    DC power supply: DC 5V-30V
    Output signal: RS485 signal
    Temperature accuracy: ±0.5℃ (25℃)
    Humidity accuracy: ±3%RH
    Temperature range: 0%RH-80%RJ
    Temperature resolution: 0.1℃
    Humidity resolution: 0.1%RH
    Equipment power consumption: ≤0.2W
    Communication address: 1-247 can be set, default 1
    Communication protocol: Modbus-RTU protocol and custom common protocol
    Baud rate: configurable, default 9600, 8-bit data, 1-bit stop, no parity
    

Requirements

npm install modbus-serial

Code

const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();

client.connectRTUBuffered("/COM4", { baudRate: 9600, parity: 'none', stopBits: 1, dataBits: 8 }, readSafe);
client.setTimeout(500);
client.setID(1);

async function read() {
    const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
    let resp;

    for (let i = 0; i < 10; i++) {
        // read 2 registers starting at address 1:
        resp = await client.readInputRegisters(1, 2);
        console.log({ temp: resp.data[0] / 10, humidity: resp.data[1] / 10 });
        await sleep(500);
    }

    client.close();
}

async function readSafe() {
    try {
        await read();
    } catch(e) {
        console.error(e);
    }
    process.exit(0);
}

example output:

D:\dev\modbus-test>npm start

> [email protected] start
> node index.js

{ temp: 28, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
{ temp: 27.9, humidity: 41.7 }
@lukasMega
Copy link
Author

lukasMega commented Jun 23, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment