can-arduino/can/can.ino
2026-03-02 18:35:40 +01:00

91 lines
1.6 KiB
C++

#include <SPI.h>
#include <mcp_can.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
#define CAN_CS 10
MCP_CAN CAN(CAN_CS);
const byte NODE_ID = 0x01; // Change to your Sevcon node ID
const unsigned long timing = 500;
unsigned long previous_time = 0;
unsigned long current_time = 0;
int16_t rpm = 0;
int16_t ubat = 0;
int v = 0;
int ubatr = 0;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("vitesse = ");
lcd.print(" ");
lcd.print(" km/h ");
lcd.setCursor(0, 1);
lcd.print("ubat = ");
lcd.print(" ");
lcd.print(" V ");
Serial.begin(115200);
while (CAN_OK != CAN.begin(MCP_ANY, CAN_500KBPS, MCP_8MHZ)) {
Serial.println("CAN init failed, retrying...");
delay(100);
}
CAN.setMode(MCP_NORMAL);
Serial.println("CAN init OK");
}
void loop() {
if (CAN.checkReceive() == CAN_MSGAVAIL) {
unsigned long rxId;
byte len = 0;
byte buf[8];
CAN.readMsgBuf(&rxId, &len, buf);
switch (rxId) {
case 0x382 : {
if (len >= 2) {
rpm = buf[0] | (buf[1] << 8);
v = rpm * 0.017;
Serial.println(v);
};
break;
}
case 0x209 : {
if (len >= 2) {
ubat = buf[0] | (buf[1] << 8);
ubatr = ubat / 16;
Serial.println(ubatr);
};
break;
}
}
}
current_time = millis();
if( current_time - previous_time >= timing){
lcd.setCursor(0, 0);
lcd.print("Vitesse = ");
lcd.print(v);
lcd.print(" km/h ");
lcd.setCursor(0, 1);
lcd.print("ubat = ");
lcd.print(ubatr);
lcd.print(" V ");
}
}