Back to this, if nothing in the code within this for loop causes canMsg.can_dlc to change, then it will just keep repeating forever. Only way it could work is if the mcp2515 library is altering the value of canMsg.can_dlc in the background (within an interrupt routine).
Are you still saying that this code works when the Uno is connected via USB but does not when connected to the batteries?
Try this
#include <SPI.h>
#include <mcp2515.h> //https://github.com/autowp/arduino-mcp2515/tree/master
#include <Wire.h> //HL
#include <Adafruit_GFX.h> //HL
#include <Adafruit_SSD1306.h> //HL
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
struct can_frame canMsg;
MCP2515 mcp2515(10);
void setup() {
Serial.begin(115200);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
// Clear the buffer
display.clearDisplay();
mcp2515.reset();
mcp2515.setBitrate(CAN_250KBPS, MCP_8MHZ);
mcp2515.setNormalMode();
canMsg.can_id = 0x60B;
canMsg.can_dlc = 8;
canMsg.data[0] = 0x40;
canMsg.data[1] = 0x81;
canMsg.data[2] = 0x60;
canMsg.data[3] = 0x00;
canMsg.data[4] = 0x00;
canMsg.data[5] = 0x00;
canMsg.data[6] = 0x00;
canMsg.data[7] = 0x00;
}
void loop() {
display.clearDisplay();
mcp2515.sendMessage(&canMsg);
if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
Serial.print(canMsg.can_id, HEX); // print ID
Serial.print(" ");
Serial.print(canMsg.can_dlc, HEX); // print DLC
Serial.print(" ");
for (int i = 0; i < canMsg.can_dlc; i++) { // print the data. HL ändrat 0 till 4 , tagit bort ++ efter i,
Serial.println(canMsg.data[i], HEX); // lagt till ln efter print
Serial.println(canMsg.data[i], DEC); // lagt till ln efter print
Serial.print(" ");
display.display();
display.setTextSize(2); // Draw 2X-scale text
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0); // Start at top-left corner -->middle
display.println("Batt. SoC");
display.println(" ");
display.setCursor(0, 25); // Start at top-left corner -->middle
// display.setTextColor(SSD1306_WHITE);
display.print(" ");
display.setTextSize(4); // Draw 4X-scale text
display.print(canMsg.data[i], DEC);
display.println("%");
display.println(" ");
display.display();
delay(1000); //HL 2s-->1s
}
}
}