-
Notifications
You must be signed in to change notification settings - Fork 2
/
obd2-interface.ino
101 lines (91 loc) · 2.74 KB
/
obd2-interface.ino
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <global.h>
#include <Canbus.h>
#include <mcp2515_defs.h>
#include <mcp2515.h>
#include <defaults.h>
String UserInput;
char canBuffer[456];
void sendMessage(unsigned char mode, unsigned char pid) {
// buffer for can messages received
char buffer[64];
// build can message
tCAN message;
message.id = PID_REQUEST;
message.header.rtr = 0;
message.header.length = 8;
message.data[0] = 0x02;
message.data[1] = mode;
message.data[2] = pid;
message.data[3] = 0x00;
message.data[4] = 0x00;
message.data[5] = 0x00;
message.data[6] = 0x00;
message.data[7] = 0x00;
mcp2515_bit_modify(CANCTRL, (1 << REQOP2) | (1 << REQOP1) | (1 << REQOP0), 0);
if (mcp2515_send_message(&message)) {
delay(500);
if (!mcp2515_check_message()) {
Serial.println("Error: no message received");
}
while (mcp2515_check_message()) {
if (mcp2515_get_message(&message)) {
sprintf(buffer, "0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X", message.id, message.data[0], message.data[1], message.data[2], message.data[3], message.data[4], message.data[5], message.data[6], message.data[7]);
if (buffer[0] == 0) {
Serial.println("Error: no message received");
} else {
Serial.println(buffer);
}
}
}
}
}
// returns true on correct input
bool checkInput(String input) {
String val1 = input.substring(0, 4);
String val2 = input.substring(5);
if (val1.substring(0, 2) == "0x" && val2.substring(0, 2) == "0x") {
if (!isHexadecimalDigit(val1.charAt(2)) || !isHexadecimalDigit(val1.charAt(3))) {
return false;
}
if (!isHexadecimalDigit(val2.charAt(2)) || !isHexadecimalDigit(val2.charAt(3))) {
return false;
}
return true;
}
return false;
}
void setup() {
Serial.begin(9600);
Serial.println("obd2-interface");
Serial.println("--------------");
if (Canbus.init(CANSPEED_500)) {
Serial.println("can init successful");
} else {
Serial.println("can init failed");
return;
}
Serial.println("Enter Mode and PID for your request in hex like this: 0x01 0x0D");
Serial.println("Response in format: ID #Bytes Mode PID Ah Bh Ch Dh Unused");
Serial.println("--------------");
}
void loop() {
while (Serial.available()) {
UserInput = Serial.readString();
Serial.println("> " + UserInput);
if (!checkInput(UserInput)) {
Serial.println("Error: wrong format");
break;
}
char input[16];
char* pEnd;
UserInput.toCharArray(input, 16);
int mode = strtol(input, &pEnd, 16);
int pid = strtol(pEnd, &pEnd, 16);
/* additional info for dev
char outstring[32];
sprintf(outstring, "Mode: %d PID: %d\n", mode, pid);
Serial.print(outstring);
*/
sendMessage(mode, pid);
}
}