Useful Code Snippet: AVR and C++11


Despite what a lot of people say about the Arduino crowd and using C++ on a microcontroller, I like it.  Sometimes it incurs a performance or code-size overhead, but I’m not often approaching the RAM or Flash limits of an Atmega 328, or especially an Atmega 2560.  When appropriate features are used, C++ results in more readable code.  Lately, I’ve branched into using templates with some AVR Code.  Here’s a super useful snippet for creating a quick ringbuffer:

No malloc or new to be seen here.  As long as equality operators and copy constructors are sorted, it should work with arbitrary types (although I’ve only tested it with built-ins and simple structs).

C++11 also allows you to typedef templates, like this: typedef AVRRingBuffer<char, 25> SerialBuffer;

Add comment