ESP32-CAN_senderTest.ino (953B)
1 #include <CAN.h> 2 3 const int CAN_TX_PIN = 4; // Any GPIO pin for CAN TX 4 const int CAN_RX_PIN = 5; // Any GPIO pin for CAN RX 5 const int CAN_SPEED = 500E3; // Baud rate for CAN bus communication 6 7 void setup() { 8 Serial.begin(115200); 9 10 CAN.setPins(CAN_RX_PIN, CAN_TX_PIN); 11 12 // Initialize CAN bus at 500 kbps 13 if (!CAN.begin(CAN_SPEED)) { 14 Serial.println("Failed to initialize CAN bus!"); 15 while (1); // Halt if initialization fails 16 } 17 } 18 19 void loop() { 20 if (Serial.available() > 0) { 21 String input = Serial.readStringUntil('\n'); 22 // Print the command to serial monitor 23 Serial.print("Sending command: "); 24 Serial.println(input); 25 // Convert string to byte array 26 uint8_t message[input.length()]; 27 input.getBytes(message, input.length() + 1); 28 // Send the message over CAN bus 29 CAN.beginPacket(0x123); // Assuming 0x123 is the ID for user commands 30 CAN.write(message, input.length()); 31 CAN.endPacket(); 32 } 33 }