Hello, I am trying to receive message from CANBUS and combine the two bytes before converting the entire string into decimal number.
My code below:
#include <SPI.h>
#include "mcp2515_can.h"
/*SAMD core*/
#ifdef ARDUINO_SAMD_VARIANT_COMPLIANCE
#define SERIAL SerialUSB
#else
#define SERIAL Serial
#endif
long volt;
long current;
long SOC;
long batterytemp;
const int SPI_CS_PIN = 9;
mcp2515_can CAN(SPI_CS_PIN); // Set CS pin
void setup() {
SERIAL.begin(115200);
while(!Serial){};
while (CAN_OK != CAN.begin(CAN_250KBPS)) { // init can bus : baudrate = 500k
SERIAL.println("CAN BUS Shield init fail");
SERIAL.println(" Init CAN BUS Shield again");
delay(100);
}
SERIAL.println("CAN BUS Shield init ok!");
}
unsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
void loop() {
unsigned char len = 0;
unsigned char buf[8];
if(CAN_MSGAVAIL == CAN.checkReceive())
{
CAN.readMsgBuf(&len, buf);
unsigned long canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Data from ID: 0x");
Serial.print(canId, HEX);
Serial.print(" ");
for (int i = 0; i < len; i++) {
Serial.print(buf[i], HEX);
Serial.print(" ");
}
String hi = String(buf[3],HEX);
String lo = String(buf[2],HEX);;
String tot = hi+lo;
//long total = strtoul(tot,&ptr,10);
Serial.print("Hi is: ");
Serial.println(hi);
Serial.print("Lo is: ");
Serial.println(lo);
Serial.print("Combined is: ");
Serial.print(tot);
Serial.print(" ");
Serial.print("Combined int is: ");
Serial.print(j);
Serial.print(" ");
}
}
Say I am receiving a message data:00 00 EF 23 00 00 00 00, I was able to read the data and the code gives me a String tot: 23ef, which is correct. Now I would like to convert this '23ef' to decimal which should be 9919. Is there a simple way of doing so?
I know my 'tot' is a String and I need to convert this 'entire' string into Decimal number. I am pretty new to this, please help.
Thanks in advance.