I am trying to pull my car's engine rpm, speed, throttle position from the can bus. I am new to advanced stiff like this. I have gotten as far as being able to print them out on screen but I need them stored in a variable, converted to an integer from hex, so that I may use that info in other ways. Anyways, I am using the can bus library from sparkfun and I'm using a modified can read demo.
The problem I have is it prints out undefined boxes instead of head, but I believe it's because I am trying to store a byte in a char variable. With that said how can I store a hex string (0x00-0xFF) in a variable and then convert it to an integer?
Here is the code, when it's just printed using
Serial.print(message.data[i],HEX);
It comes out perfectly fine in hex
Here is the entire sketch as it is now
/****************************************************************************
CAN Read Demo for the SparkFun CAN Bus Shield.
Written by Stephen McCoy.
Original tutorial available here: http://www.instructables.com/id/CAN-Bus-Sniffing-and-Broadcasting-with-Arduino
Used with permission 2016. License CC By SA.
Distributed as-is; no warranty is given.
*************************************************************************/
#include <stdlib.h>
#include <Canbus.h>
#include <defaults.h>
#include <global.h>
#include <mcp2515.h>
#include <mcp2515_defs.h>
char rpm[2];
int newrpm;
//********************************Setup Loop*********************************//
void setup() {
Serial.begin(9600); // For debug use
Serial.println("CAN Read - Testing receival of CAN Bus message");
delay(1000);
if(Canbus.init(CANSPEED_500)) //Initialise MCP2515 CAN controller at the specified speed
Serial.println("CAN Init ok");
else
Serial.println("Can't init CAN");
delay(1000);
}
//********************************Main Loop*********************************//
void loop(){
tCAN message;
if (mcp2515_check_message())
{
if (mcp2515_get_message(&message))
{
if(message.id == 0x201) //uncomment when you want to filter
{
//Serial.print("ID: ");
//Serial.print(message.id,HEX);
//Serial.print(", ");
// Serial.print("Data: ");
//Serial.print(message.header.length,DEC);
for(int i=0;i<message.header.length;i++)
{
if (i<2) // only process first two bytes
{
rpm[i] = message.data[i]; //Store each byte
// Serial.print(message.data[i],HEX);
// Serial.print(" ");
}
}
Serial.println(rpm);
long int newrpm = strtol(rpm, NULL, 16); //convert hex string to decimal
// newrpm = (newrpm+1)/4; //divide by 4 to get rpm
// Serial.println(newrpm);
}
}}
}