The following sketch (base is an example from Seeed_Arduino_CAN-2.3.3 library, slightly modified by me) returns a 8 Byte buffer from CAN-Bus dialog.
On canId "849" the buf[1] and buf[2] bytes holds the interesting data (chars), where buf[2] is the highbyte and buf[1] the lowbyte.
I can read this and view it via SERIAL_PORT_MONITOR.print without any problems.
But when I try to display the calculated Word (sped) via SERIAL_PORT_MONITOR.print,
I get only correct values if the value of buf[2] < 80hex.
Above that, I get negative values although I've defined usigned variables.
What I'm doing wrong ?
Please help.
#include <SPI.h>
#define CAN_2515
const int SPI_CS_PIN = 10;
const int CAN_INT_PIN = 2;
#include "mcp2515_can.h"
mcp2515_can CAN(SPI_CS_PIN); // Set CS pin
int i;
byte hiv2;
byte hiv3;
unsigned long sped;
int CanBusSwitch = 8;
void setup() {
SERIAL_PORT_MONITOR.begin(9600);
while (CAN_OK != CAN.begin(CAN_100KBPS)) { // init can bus : baudrate = 500k
SERIAL_PORT_MONITOR.println("CAN init fail, retry...");
delay(100);
}
SERIAL_PORT_MONITOR.println("CAN init ok!");
pinMode(CanBusSwitch, OUTPUT); // Definiere Ausgang für CanBusSwitch (Umschaltung Zusatzinfos über Radio-Text-Display)
digitalWrite (CanBusSwitch, HIGH); // Schalte Ausgang für CanBusSwitch aktiv
}
void loop() {
unsigned char len = 0;
unsigned char buf[8];
if (CAN_MSGAVAIL == CAN.checkReceive()) { // check if data coming
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned long canId = CAN.getCanId();
if (canId == 849)
{
hiv2 = buf[2];
hiv3 = buf[1];
sped = (hiv2 * 256) + hiv3;
SERIAL_PORT_MONITOR.print(hiv2);
SERIAL_PORT_MONITOR.print("\t");
SERIAL_PORT_MONITOR.print(hiv3);
SERIAL_PORT_MONITOR.print("\t");
SERIAL_PORT_MONITOR.print(sped);
}
SERIAL_PORT_MONITOR.println();
}
}
//END FILE