1 | #include <SoftwareSerial.h>
|
2 | #include <Wire.h>
|
3 | #include <LiquidCrystal_I2C.h>
|
4 |
|
5 | #define rxPin 2
|
6 | #define txPin 3
|
7 | #define DataEnablePin A0
|
8 |
|
9 | #define slaveID 0xA
|
10 | #define regRequested 33050
|
11 | #define numRegReq 0x1
|
12 | #define FRAMESIZE 9 //size of out/in array
|
13 |
|
14 | float dataReceived = 0.00;
|
15 |
|
16 | SoftwareSerial mySerial (rxPin, txPin);
|
17 | uint16_t calculateCRC(uint8_t *array, uint8_t num);
|
18 |
|
19 | LiquidCrystal_I2C lcd(0x3F, 20, 4);
|
20 |
|
21 | void setup() {
|
22 | pinMode(DataEnablePin, OUTPUT);
|
23 | digitalWrite(DataEnablePin, LOW);
|
24 | mySerial.begin(9600);
|
25 | Serial.begin(115200);
|
26 | lcd.begin();
|
27 | lcd.backlight();
|
28 |
|
29 | Serial.println("---- STARTING ----");
|
30 |
|
31 | }
|
32 |
|
33 | void loop() {
|
34 | uint8_t modArr[9];
|
35 |
|
36 | modArr[0] = slaveID; // Slave ID
|
37 | modArr[1] = 0x04; // Object type
|
38 |
|
39 | modArr[2] = highByte(regRequested);
|
40 | modArr[3] = lowByte(regRequested);
|
41 |
|
42 | modArr[4] = highByte(numRegReq);
|
43 | modArr[5] = lowByte(numRegReq);
|
44 |
|
45 | uint16_t temp = calculateCRC(modArr, FRAMESIZE - 3);
|
46 | modArr[6] = lowByte(temp);
|
47 | modArr[7] = highByte(temp);
|
48 |
|
49 | digitalWrite(DataEnablePin, HIGH);
|
50 | delayMicroseconds(20);
|
51 | mySerial.write(modArr, FRAMESIZE - 1);
|
52 | mySerial.flush();
|
53 | delayMicroseconds(10);
|
54 | digitalWrite(DataEnablePin, LOW);
|
55 |
|
56 |
|
57 | if (mySerial.available() >= FRAMESIZE) {
|
58 |
|
59 | for (uint16_t n = 0; n < FRAMESIZE - 2; n++) {
|
60 | modArr[n] = mySerial.read();
|
61 | }
|
62 | }
|
63 |
|
64 | if (modArr[0] == slaveID) {
|
65 | dataReceived = word(modArr[3], modArr[4]) / 100.00f;
|
66 | }
|
67 |
|
68 | lcd.print("F:");
|
69 | lcd.setCursor(3,0);
|
70 | lcd.print(dataReceived);
|
71 | lcd.setCursor(10,0);
|
72 | lcd.print("Hz");
|
73 | lcd.home();
|
74 |
|
75 | delay(2500);
|
76 |
|
77 | }
|
78 |
|
79 | uint16_t calculateCRC(uint8_t *array, uint8_t num) {
|
80 | uint16_t _crc, _flag;
|
81 | _crc = 0xFFFF;
|
82 | for (uint8_t i = 0; i < num; i++) {
|
83 | _crc = _crc ^ array[i];
|
84 | for (uint8_t j = 8; j; j--) {
|
85 | _flag = _crc & 0x0001;
|
86 | _crc >>= 1;
|
87 | if (_flag)
|
88 | _crc ^= 0xA001;
|
89 | }
|
90 | }
|
91 | return _crc;
|
92 | }
|