Middleware code to wait for CAN packet and send out message.


maybe a noob question, but can someone give an example how to correctly code a middleware which waits for a message from a specific ID and then sends out a CAN message?
I am able to log messages, know what to look for and what to send out. But I have no clue how to code this...



In the past days Derek helped me a lot in understanding how middleware works and how to communicate with a car. I want to share here what I learned and hope this will be helpful for others as well.

To receive and send messages you write your own middleware. "ChannelSwap.h" and "ServiceCall.h" are good examples to have a look at in the beginning.

For your own middleware you create a new file "YourMiddleware.h". In "CANBusTriple.ino" you add the following lines:

<code>#include "YourMiddleware.h"</code>
<code>YourMiddleware *yourmiddleware = new YourMiddleware( &writeQueue );</code>

In the <code>Middleware *activeMiddleware[] = {</code> block you add:
to the list.

Then move over to your "YourMiddleware.h" file. It should look like this:

<code>#include "Middleware.h"

class YourMiddleware : public Middleware
QueueArray<Message>* mainQueue;
void tick();
Message process( Message msg );
YourMiddleware( QueueArray<Message> q );
void sendMyMessage();
void commandHandler(byte
bytes, int length);
unsigned long lastMsgSent;

YourMiddleware::YourMiddlware( QueueArray<Message> *q ) {
mainQueue = q;
lastMsgSent = millis();

void YourMiddleware::tick(){
if((millis() > lastMsgSent + 100) || (millis() < lastMsgSent)){ //avoid flooding the bus, only call the sendMyMessage method every 100 milliseconds
lastMsgSent = millis();

void YourMiddleware::commandHandler(byte* bytes, int length){}

Message YourMiddleware::process( Message msg )
//msg.frame_data[0] to msg.frame_data[7] do what ever you want with the messages received...
return msg;

void YourMiddleware::sendMyMessage(){
Message msg;

//msg.frame_data[0] to msg.frame_data[7] put whatever data you want in the message to send...

msg.length = 8;
msg.dispatch = true;


Thanks for sharing Reto. This is a good starting point for others.

Hello everyone. I find it interesting to make the points made in this thread. In my case it would be interested in receiving messages CAN1 can process and send the CAN2. Can anyone give an example of middleware?
Thank you

  • 4
  • 5040
