ESP32-CAN_receiverTest.ino (1367B)
1 #include <CAN.h> 2 3 const int CAN_TX_PIN = 4; // Any GPIO pin for CAN TX 4 const int CAN_RX_PIN = 15; // Any GPIO pin for CAN RX 5 const int BEEP_PIN = 16; // Digital pin for triggering the beeping device 6 const int CAN_SPEED = 500E3; // Baud rate for CAN bus communication 7 8 char receivedMessage[64]; // Char array to store the received message 9 10 void setup() { 11 Serial.begin(115200); 12 pinMode(BEEP_PIN, OUTPUT); 13 14 CAN.setPins(CAN_RX_PIN, CAN_TX_PIN); 15 16 // Initialize CAN bus at 500 kbps 17 // Initialize CAN bus at specified baud rate 18 if (!CAN.begin(CAN_SPEED)) { 19 Serial.println("Failed to initialize CAN bus!"); 20 while (1); // Halt if initialization fails 21 } 22 } 23 24 void loop() { 25 // Check if there's a message received 26 if (CAN.parsePacket() > 0) { 27 // Read the message into the char array 28 int messageLength = 0; 29 while (CAN.available() && messageLength < sizeof(receivedMessage)) { 30 receivedMessage[messageLength++] = CAN.read(); 31 } 32 // Null-terminate the char array 33 receivedMessage[messageLength] = '\0'; 34 Serial.println("Received message: " + String(receivedMessage)); 35 36 // Check if the received message is "BEEP" 37 if (strcmp(receivedMessage, "BEEP") == 0) { 38 // Trigger the beeping device 39 digitalWrite(BEEP_PIN, HIGH); 40 delay(1000); // Adjust as needed 41 digitalWrite(BEEP_PIN, LOW); 42 } 43 } 44 }