Last active
September 18, 2017 15:39
-
-
Save ssnover/828bf1f7d64580398625a9c37498c5f2 to your computer and use it in GitHub Desktop.
Arduino CAN-to-JSON Listener
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 <cstdio> | |
#include "Arduino.h" | |
#include "mcp_can.h" | |
#define NOP() asm("nop\n") | |
MCP_CAN my_can_controller(10); | |
const uint8_t CAN_INTERRUPT_PIN(2); | |
uint32_t messageId; | |
uint8_t messageLength; | |
uint8_t messageBuffer[8]; | |
void setup() | |
{ | |
Serial.begin(115200); | |
bool init_status(my_can_controller.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ)); | |
if (CAN_OK == init_status) | |
{ | |
Serial.println(F("Initialized the CAN controller IC.")); | |
} | |
else | |
{ | |
Serial.println(F("Error initializing CAN controller IC.")); | |
while (true) | |
{ | |
NOP(); | |
} | |
} | |
my_can_controller.setMode(MCP_NORMAL); | |
pinMode(CAN_INTERRUPT_PIN, INPUT); | |
} | |
void loop() | |
{ | |
if (digitalRead(CAN_INTERRUPT_PIN) == false) | |
{ | |
my_can_controller.readMsgBuf(&messageId, &messageLength, messageBuffer); | |
// determine if message ID is standard length (11 bits) | |
if ((messageId & 0x8000000) != 0x8000000) | |
{ | |
Serial.print(F("{\"id:\"")); | |
Serial.print(messageId); | |
Serial.print(F(",\"length:\"")); | |
Serial.print(messageLength); | |
Serial.print(F(",\"bytestring:0x\"")); | |
uint8_t serialBuffer[2]; | |
for (uint8_t i = 0; i < messageLength; ++i) | |
{ | |
sprintf(serialBuffer, "%2X", *(messageBuffer + i)); | |
Serial.print(serialBuffer); | |
} | |
Serial.print(F("}\n")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment