Created
November 3, 2024 12:56
-
-
Save adlerweb/d798e0c0799db541bf1606ace240f2ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#include <SoftwareSerial.h> | |
SoftwareSerial SRSerial(D1, D0); | |
void setup() { | |
Serial.begin(115200); | |
SRSerial.begin(9600); | |
} | |
uint8_t sr_act = 0; | |
uint8_t buffer; | |
uint16_t data = 0; | |
uint8_t check = 0xFF; | |
uint8_t curByte = 0; | |
uint16_t hcc = 0; | |
uint16_t read_hc() { | |
if(sr_act == 0) { | |
SRSerial.write(0x55); | |
//Serial.println("[>>] 0x55"); | |
sr_act++; | |
data = 0; | |
curByte = 0; | |
return 0; | |
}else{ | |
hcc++; | |
if(hcc > 10000) { | |
hcc = 0; | |
sr_act = 0; | |
} | |
if(!SRSerial.available()) return 0; | |
buffer = SRSerial.read(); | |
//Serial.print("[<<] 0x"); | |
//Serial.println(buffer, HEX); | |
switch (curByte) | |
{ | |
case 3: | |
if(buffer != check) { | |
Serial.println(); | |
Serial.print("[!!] Invalid result - Calc: 0x"); | |
Serial.print(check, HEX); | |
Serial.print(" - Rcvd: 0x"); | |
Serial.print(data, HEX); | |
Serial.print(" 0x"); | |
Serial.println(buffer, HEX); | |
}else{ | |
//Serial.print("[II] Valid: 0x"); | |
//Serial.println(data); | |
sr_act = 0; | |
check = 0xFF; | |
curByte = 0; | |
return data; | |
} | |
break; | |
case 2: | |
data |= buffer; | |
check += buffer; | |
curByte++; | |
break; | |
case 1: | |
data = buffer << 8; | |
check += buffer; | |
curByte++; | |
break; | |
case 0: | |
if(buffer == 0xff) curByte++; | |
break; | |
default: | |
return 0; | |
} | |
} | |
return 0; | |
} | |
void loop() { | |
uint16_t dist = 0; | |
dist = read_hc(); | |
if(dist > 20) { | |
Serial.print("[HC] "); | |
Serial.println(dist); | |
delay(75); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment