Skip to content

Instantly share code, notes, and snippets.

@talss89
Created September 7, 2023 22:39
Show Gist options
  • Save talss89/12ac279334574540ec153204fd48053f to your computer and use it in GitHub Desktop.
Save talss89/12ac279334574540ec153204fd48053f to your computer and use it in GitHub Desktop.
ESP-IDF TWAI - Create filter mask
/*
* This function accepts a <min> and <max> CAN ID, and generates a single TWAI acceptance mask that is a
* loose fit for CAN packets with IDs between <min> and <max>.
*
* This may not filter out all other packets, and is imperfect. But a quick solution for a filter range.
*/
void twai_generate_filter(uint16_t min, uint16_t max, twai_filter_config_t* filter) {
uint32_t mask[2] = {~0, ~0};
for(uint16_t i = min; i < max; i ++) {
mask[0] &= i;
mask[1] &= ~i;
}
filter->acceptance_mask = ~((mask[0] | mask[1]) << 21);
filter->acceptance_code = (min & (mask[0] | mask[1])) << 21;
filter->single = true;
}
@Tomblarom
Copy link

Hey, thanks for that snippet! I'm looking for a solution to create a filter for multiple different IDs, like 0x2F7, 0xAF0, 0x10F, ... Is this possible with the ESP hardware filter?

@talss89
Copy link
Author

talss89 commented May 14, 2024

Hey @Tomblarom. It's been a little while since I've worked with the ESP, but I think that should be possible. You'll probably end up with quite a wide range of IDs being passed by the filter though. Depending on bus activity that may / may not be be a problem for your application.

As far as I can remember (and glancing at these docs), the ESP CAN acceptance filter can operate in two modes. The snippet above sets up the filter in single filter mode. dual can offer more flexibility, but does not take into account CAN extended frames. For my use case (modern EFI motorcycle), I needed to filter 29-bit extended IDs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment