EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 7
C++ for Embedded Systems and Arduino
Objects and classes without giving up hardware control.
C++ adds classes, which bundle data with the functions that use it. A Led class can hold its pin number and offer on() and off(), so main code reads like plain English.
Beginner boards such as Arduino use C++ behind a friendly layer. On small chips avoid heavy features: dynamic memory (new, malloc) can fragment tiny RAM, and exceptions inflate code size.
Good embedded C++ means classes, templates and const, with all memory allocated up front.
EXAMPLE
class Led {
public:
explicit Led(int p) : pin(p) {}
void on() { digitalWrite(pin, HIGH); }
void off() { digitalWrite(pin, LOW); }
private:
int pin;
};
Led status(13);
void setup() { pinMode(13, OUTPUT); }
void loop() { status.on(); delay(500); status.off(); delay(500); }