Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created February 14, 2021 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxpromer/8e5d06b759b4f746e916f5bb07da485c to your computer and use it in GitHub Desktop.
Save maxpromer/8e5d06b759b4f746e916f5bb07da485c to your computer and use it in GitHub Desktop.
/* Dev by IOXhop.com */
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 8); // RX, TX
float temp = 0, humi = 0;
void readXY_MD02() {
uint8_t buff[] = {
0x01, // Devices Address
0x04, // Function code
0x00, // Start Address HIGH
0x01, // Start Address LOW
0x00, // Quantity HIGH
0x02, // Quantity LOW
0x20, // CRC LOW
0x0B // CRC HIGH
};
mySerial.write(buff, sizeof(buff));
mySerial.flush(); // wait MODE_SEND completed
delay(200);
if (mySerial.find("\x01\x04")) {
uint8_t n = mySerial.read();
if (n != 4) {
Serial.println("Error data size");
return;
}
temp = ((uint16_t)(mySerial.read() << 8) | mySerial.read()) / 10.0;
humi = ((uint16_t)(mySerial.read() << 8) | mySerial.read()) / 10.0;
} else {
Serial.println("ERROR Timeout");
return;
}
}
void setup() {
Serial.begin(115200);
mySerial.begin(9600); // Rx, Tx
mySerial.setTimeout(200);
}
void loop() {
readXY_MD02();
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println(" *C");
Serial.print("Humidity: ");
Serial.print(humi);
Serial.println(" *C");
delay(300);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment