-
Notifications
You must be signed in to change notification settings - Fork 0
/
comm.h
67 lines (62 loc) · 1.58 KB
/
comm.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#define MySerial Serial1
#define SER_TIMEOUT 300 //leave 300ms for the machine to answer
char getCRC(char *src, int len)
{
char b = 0;
for (int i = 0; i < len; i++)
{
b += src[i];
}
return ~b;
}
bool queryRegistry(char regID, char *buffer)
{
//preparing command:
char prep[] = {0x03, 0x40, regID, 0x00};
prep[3] = getCRC(prep, 3);
//Sending command to serial
MySerial.flush(); //Prevent possible pending info on the read
MySerial.write(prep, 4);
ulong start = millis();
int len = 0;
buffer[2] = 10;
Serial.printf("Querying register 0x%02x... ", regID);
while ((len < buffer[2] + 2) && (millis() < (start + SER_TIMEOUT)))
{
if (MySerial.available())
{
buffer[len++] = MySerial.read();
}
}
if (millis() >= (start + SER_TIMEOUT))
{
if (len == 0)
{
Serial.printf("Time out! Check connection\n");
}
else
{
Serial.printf("ERR: Time out on register 0x%02x! got %d/%d bytes\n", regID, len, buffer[2]);
char bufflog[250] = {0};
for (size_t i = 0; i < len; i++)
{
sprintf(bufflog + i * 5, "0x%02x ", buffer[i]);
}
Serial.print(bufflog);
}
delay(500);
return false;
}
if (getCRC(buffer, len - 1) != buffer[len - 1])
{
Serial.println("Wrong CRC!");
//mqttSerial.printf("ERROR: Wrong CRC on register 0x%02x!", regID);
Serial.printf("Calculated 0x%2x but got 0x%2x\n", getCRC(buffer, len - 1), buffer[len - 1]);
return false;
}
else
{
Serial.println(".. CRC OK!");
return true;
}
}