From c314930936138aee4b7ce114196882347d0aceda Mon Sep 17 00:00:00 2001
From: Stanley Huang <stanleyhuangyc@gmail.com>
Date: Mon, 19 Dec 2016 17:28:11 +1100
Subject: Added readDTC() for reading OBD-II Trouble Codes into an array

---
 libraries/OBD2UART/OBD2UART.cpp | 37 +++++++++++++++++++++++++++++++++++++
 libraries/OBD2UART/OBD2UART.h   |  6 ++++--
 2 files changed, 41 insertions(+), 2 deletions(-)

diff --git a/libraries/OBD2UART/OBD2UART.cpp b/libraries/OBD2UART/OBD2UART.cpp
index f756705..5cd9ff6 100644
--- a/libraries/OBD2UART/OBD2UART.cpp
+++ b/libraries/OBD2UART/OBD2UART.cpp
@@ -98,6 +98,43 @@ byte COBD::readPID(const byte pid[], byte count, int result[])
 	return results;
 }
 
+byte COBD::readDTC(uint16_t codes[], byte count)
+{
+	/*
+	Response example:
+	0: 43 04 01 08 01 09 
+	1: 01 11 01 15 00 00 00
+	*/ 
+	byte codesRead = 0;
+ 	for (byte n = 0; n < 6; n++) {
+		char buffer[128];
+		sprintf(buffer, "03%02X\r", n);
+		write(buffer);
+		Serial.println(buffer);
+		if (receive(buffer, sizeof(buffer)) > 0) {
+			Serial.println(buffer);
+			if (!strstr(buffer, "NO DATA")) {
+				char *p = strstr(buffer, "43");
+				if (p) {
+					while (codesRead < count && *p) {
+						p += 6;
+						if (*p == '\r') {
+							p = strchr(p, ':');
+							if (!p) break;
+							p += 2; 
+						}
+						uint16_t code = hex2uint16(p);
+						if (code == 0) break;
+						codes[codesRead++] = code;
+					}
+				}
+				break;
+			}
+		}
+	}
+	return codesRead;
+}
+
 void COBD::clearDTC()
 {
 	char buffer[32];
diff --git a/libraries/OBD2UART/OBD2UART.h b/libraries/OBD2UART/OBD2UART.h
index eaab88d..a6c186e 100644
--- a/libraries/OBD2UART/OBD2UART.h
+++ b/libraries/OBD2UART/OBD2UART.h
@@ -117,15 +117,17 @@ public:
 	virtual void sleep();
 	// set working protocol (default auto)
 	virtual bool setProtocol(OBD_PROTOCOLS h = PROTO_AUTO);
-	// send AT command and receive response
+	// send AT command and receive response (return bytes received)
 	virtual byte sendCommand(const char* cmd, char* buf, byte bufsize, int timeout = OBD_TIMEOUT_LONG);
+	// read diagnostic trouble codes (return number of DTCs read)
+	virtual byte readDTC(uint16_t codes[], byte count = 1);
 	// clear diagnostic trouble code
 	virtual void clearDTC();
 	// get battery voltage (works without ECU)
 	virtual float getVoltage();
 	// get VIN as a string, buffer length should be >= OBD_RECV_BUF_SIZE
 	virtual bool getVIN(char* buffer, byte bufsize);
-	// get device temperature
+	// get device temperature (in celsius degree) 
 	virtual float getTemperature();
 	// get accelerometer data
 	virtual bool readAccel(int& x, int& y, int& z);
-- 
cgit v1.2.3