Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Embedded-c-cpp

Learn Embedded-c-cpp - 10 Code Examples & CST Typing Practice Test

Embedded C/C++ refers to using the C or C++ programming languages for programming embedded systems. These are resource-constrained devices like microcontrollers, IoT devices, automotive controllers, and real-time systems where direct hardware control and performance are critical.

View all 10 Embedded-c-cpp code examples →
Blink LED (Embedded C, AVR microcontroller)Embedded C++ Class for LED ControlRead Button Input (Embedded C)PWM LED Brightness (Embedded C, AVR)UART Transmit (Embedded C)ADC Read and LED Control (Embedded C)Timer Interrupt Toggle LED (Embedded C)Embedded C++ Motor Control ClassSPI Send Byte (Embedded C)I2C Master Send (Embedded C)

Learn EMBEDDED-C-CPP with Real Code Examples

Updated Nov 27, 2025

Explain

Embedded C/C++ provides low-level access to hardware, memory, and peripherals.

Enables deterministic, real-time execution for embedded systems.

Widely used in microcontrollers, IoT devices, automotive ECUs, and robotics.

Supports both procedural (C) and object-oriented (C++) paradigms.

Highly portable across architectures with proper hardware abstraction.

Core Features

Pointers and direct memory manipulation

Interrupt handling

Timers, counters, and hardware abstraction

Real-time scheduling with RTOS

Standard C/C++ libraries with embedded extensions

Basic Concepts Overview

Registers - memory-mapped peripheral controls

Interrupts - hardware or software triggered events

Timers - schedule periodic or one-shot tasks

Memory (stack, heap, flash, SRAM)

GPIO - General-purpose input/output

Project Structure

src/ - main firmware code

include/ - headers

drivers/ - peripheral interface code

RTOS/ - OS tasks and scheduling

Makefile/CMakeLists.txt or IDE project

Building Workflow

Write low-level driver code in C/C++

Use HAL or SDK for target platform

Implement application logic

Compile and flash to target hardware

Debug using serial output, LEDs, or hardware debugger

Difficulty Use Cases

Beginner: blinking LEDs and basic GPIO

Intermediate: UART, SPI, I2C communication

Advanced: RTOS tasks and timers

Expert: device drivers and real-time synchronization

Architect: multi-core embedded systems and safety-critical ECUs

Comparisons

Embedded C vs SPARK: C is flexible but not formally verifiable

Embedded C++ vs Rust: C++ allows OOP; Rust enforces memory safety

Embedded C vs Python MicroPython: C is faster and deterministic

C vs Arduino Wiring: Arduino is a simplified C++ abstraction

Embedded C vs SCADE-generated C: SCADE provides model-based verification

Versioning Timeline

1970s - C created by Dennis Ritchie

1980s - C++ created by Bjarne Stroustrup

1990s - ANSI/ISO standardization of C/C++

2000s - Embedded-focused compilers expand

2010s - Modern embedded C++ usage with RTOS

2025 - Current embedded toolchains and IoT frameworks

Glossary

MCU - Microcontroller Unit

ISR - Interrupt Service Routine

HAL - Hardware Abstraction Layer

DMA - Direct Memory Access

RTOS - Real-Time Operating System

Installation Setup

Install compiler/toolchain (GCC, IAR, Keil, or PlatformIO)

Install IDE (VS Code, Eclipse, CLion, or vendor IDE)

Set up hardware debugging tools (JTAG/SWD)

Configure build system/project files

Connect target board or microcontroller

Environment Setup

Install compiler toolchain

Set PATH for CLI tools

Install debugger/programmer

Set up IDE and project

Connect development board

Config Files

Makefile or CMakeLists.txt

project.elf / .hex output

linker scripts (.ld)

startup assembly files

device-specific headers

Cli Commands

make or gprbuild - build project

arm-none-eabi-gcc - compile for ARM

openocd - flash/debug via JTAG/SWD

objdump / nm - inspect binaries

gdb - debugging firmware

Internationalization

Code supports Unicode in comments

Embedded libraries portable globally

Toolchains available worldwide

Documentation can be localized

Open-source frameworks support multiple regions

Accessibility

Readable structured code

Well-commented hardware mappings

Clear modular drivers

Consistent naming conventions

Portable across boards

Ui Styling

Embedded C/C++ is mostly backend; UI minimal

LEDs, serial console output

Small displays via SPI/I2C

Custom protocol communication

Debug interfaces for telemetry

State Management

Global/static variables for persistent state

Use volatile for hardware-mapped variables

Critical section protection for concurrency

RTOS task-local state

Stack and heap management

Data Management

Memory-mapped I/O registers

Static vs dynamic allocation

Buffers for communication

Queues and circular buffers

Persistent configuration in flash

Architecture

Bare-metal or RTOS-based execution

Modular firmware with drivers, middleware, and application layers

Hardware abstraction layers (HAL) for portability

Interrupt-driven or polling-based event handling

Memory-mapped peripheral interaction

Rendering Model

Direct memory access

Hardware registers control peripherals

ISR-driven event handling

RTOS scheduling and context switching

Peripheral abstraction through HAL

Architectural Patterns

Bare-metal loop-driven architecture

Interrupt-driven reactive architecture

RTOS-based multi-tasking architecture

Layered HAL + driver + application

State machine-driven designs

Real World Architectures

Automotive ECU firmware

IoT sensor nodes

Industrial PLC controllers

Drone flight control software

Consumer electronics devices

Design Principles

Efficiency

Low-level hardware control

Deterministic behavior

Portability across microcontrollers

Maintainable modular code

Scalability Guide

Use modular drivers and HAL

Design interrupt priorities carefully

Avoid dynamic memory where possible

Segment firmware into tasks

Use RTOS or scheduling for multi-function expansion

Migration Guide

Port compiler flags for target MCU

Adapt hardware-specific registers

Replace deprecated peripheral drivers

Verify timing and interrupts

Test thoroughly on target hardware

Performance Notes

Optimize loops and avoid blocking delays

Use DMA for large data transfers

Minimize ISR execution time

Prefer static memory allocation for determinism

Avoid floating-point operations on MCUs without FPU

Security Notes

Validate input to prevent buffer overflow

Use secure coding practices for pointers

Protect critical sections in multi-threaded code

Encrypt communication for IoT devices

Use watchdog timers for fault recovery

Monitoring Analytics

Runtime logs via UART or SWO

Stack/heap usage monitoring

RTOS task timing statistics

Peripheral status checks

Power consumption analysis

Code Quality

Follow MISRA C/C++ guidelines

Use static analysis tools

Document register maps

Modularize drivers and HAL

Unit test critical functions

Practical Examples

Blink LED using GPIO register

Read sensor via I2C

Control motor using PWM

Implement UART communication with interrupts

Real-time task scheduling on FreeRTOS

Troubleshooting

Check memory boundaries and stack overflow

Validate peripheral clock configurations

Debug ISRs with breakpoints or logic analyzer

Verify RTOS task priorities and scheduling

Use serial/log output for debugging

Testing Guide

Unit tests on host system

Hardware-in-the-loop (HIL) testing

Peripheral simulation for automated testing

Memory and stack usage analysis

Stress and timing tests

Deployment Options

Bare-metal flash on MCU

RTOS-based embedded system

IoT devices with OTA update

Automotive ECU programming

Industrial automation controllers

Tools Ecosystem

GCC ARM / AVR / RISC-V

IAR Embedded Workbench

Keil uVision

PlatformIO

Segger Embedded Studio

Integrations

FreeRTOS or Zephyr RTOS

CMSIS and HAL libraries

RTOS middleware (MQTT, USB stacks)

Debugger (JTAG/SWD, OpenOCD)

Unit test frameworks (Unity, CMock)

Productivity Tips

Use HAL and SDK for faster development

Write reusable peripheral drivers

Use conditional compilation for portability

Document pin mappings and peripherals

Test frequently on hardware

Challenges

Handling hardware timing constraints

Debugging low-level issues

Memory and resource management

Cross-architecture portability

Ensuring deterministic real-time behavior

Learning Path

Learn basic C syntax

Understand memory and pointers

Learn MCU architecture and peripherals

Practice bare-metal programming

Move to RTOS-based embedded applications

Skill Improvement Plan

Week 1: GPIO and timers

Week 2: UART/I2C/SPI interfaces

Week 3: Interrupt handling and DMA

Week 4: RTOS tasks and queues

Week 5: Multi-peripheral integration and debugging

Interview Questions

Explain memory-mapped I/O.

How do you handle interrupts in embedded C?

What is a watchdog timer and why is it important?

Explain RTOS task scheduling.

How do you debug a hard fault on an MCU?

Cheat Sheet

volatile keyword for hardware registers

ISR syntax depends on compiler/MCU

Use bit masks for register configuration

Use static memory to avoid heap fragmentation

Use timers and delays carefully

Books

Embedded C Programming and the Atmel AVR

Programming Embedded Systems in C and C++

Making Embedded Systems

Real-Time C++

Mastering Embedded Systems Programming

Tutorials

Embedded C Programming for Microcontrollers

ARM Cortex-M Bare-Metal C Programming

RTOS Task Scheduling with C

Peripheral Drivers in Embedded C/C++

IoT Device Firmware Development

Official Docs

https://www.gnu.org/software/avr-gcc/

https://www.arm.com/architecture/cortex-m

Community Links

Embedded.com forums

Stack Overflow Embedded

Arduino/STM32/ESP32 communities

Microchip/NXP vendor forums

Embedded Systems Reddit groups

Community Support

Stack Overflow embedded tag

Embedded.com forums

Arduino / STM32 / ESP32 communities

Embedded Systems Programming magazine

Vendor-specific forums (Microchip, NXP, ST)

Monetization

Embedded firmware development services

Industrial automation products

IoT device manufacturing

Automotive software contracts

Consumer electronics embedded design

Future Roadmap

AI-assisted embedded code generation

Better RTOS and multi-core support

Enhanced IoT security frameworks

Integration with cloud and edge platforms

Low-power and energy-efficient designs

When Not To Use

Rapid application prototypes with GUIs

Heavy OS-dependent desktop apps

Systems requiring strict formal proofs

Dynamic memory-heavy applications

Where interpreted languages suffice

Final Summary

Embedded C/C++ is the industry standard for microcontroller and resource-constrained programming.

Offers low-level hardware control, high performance, and deterministic execution.

Requires careful memory and resource management.

Widely used in automotive, industrial, IoT, and robotics.

Flexible, mature, and portable across multiple embedded platforms.

Faq

Can I use C++ for bare-metal? -> Yes, with care for constructors/destructors.

Do I need an RTOS? -> Only if multitasking or real-time scheduling is needed.

How to debug embedded C? -> JTAG/SWD, serial output, logic analyzers.

Are dynamic memory allocations safe? -> Prefer static memory for embedded.

Which IDE is best? -> Depends on MCU vendor and toolchain preference.

Code Sample Descriptions

1

Blink LED (Embedded C, AVR microcontroller)

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= (1 << PB0); // Set PB0 as output
    while(1)
    {
        PORTB ^= (1 << PB0); // Toggle LED
        _delay_ms(500);
    }
}

Classic embedded example toggling a GPIO pin to blink an LED on an AVR microcontroller.

Let’s Try →
2

Embedded C++ Class for LED Control

#include "stm32f4xx.h"

class LED {
public:
    LED(GPIO_TypeDef* port, uint16_t pin) : port(port), pin(pin)
    {
        port->MODER |= (1U << (pin * 2)); // Set as output
    }
    void on() { port->ODR |= (1U << pin); }
    void off() { port->ODR &= ~(1U << pin); }
    void toggle() { port->ODR ^= (1U << pin); }
private:
    GPIO_TypeDef* port;
    uint16_t pin;
};

int main()
{
    LED led(GPIOB, 0);
    while(1)
    {
        led.toggle();
        for(volatile int i=0; i<1000000; ++i);
    }
}

A simple Embedded C++ class encapsulating GPIO operations for LED control on an ARM Cortex-M MCU.

Let’s Try →
3

Read Button Input (Embedded C)

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= (1 << PB0); // LED output
    DDRD &= ~(1 << PD0); // Button input
    while(1)
    {
        if(PIND & (1 << PD0)) PORTB |= (1 << PB0);
        else PORTB &= ~(1 << PB0);
        _delay_ms(50);
    }
}

Reads a push button connected to a GPIO and toggles an LED accordingly on an AVR MCU.

Let’s Try →
4

PWM LED Brightness (Embedded C, AVR)

#include <avr/io.h>

int main(void)
{
    DDRB |= (1 << PB1); // OC1A output
    TCCR1A |= (1 << COM1A1) | (1 << WGM10);
    TCCR1B |= (1 << WGM12) | (1 << CS10); // Fast PWM, no prescaler
    while(1)
    {
        for(uint8_t i=0; i<255; i++) { OCR1A = i; for(volatile int j=0;j<1000;j++); }
    }
}

Generates PWM on an AVR to control LED brightness.

Let’s Try →
5

UART Transmit (Embedded C)

#include <avr/io.h>

void uart_init() { UBRR0 = 103; UCSR0B = (1<<TXEN0); }
void uart_send(char c) { while(!(UCSR0A & (1<<UDRE0))); UDR0 = c; }

int main(void) {
    uart_init();
    while(1) { uart_send('A'); }
}

Sends a character over UART on an AVR microcontroller.

Let’s Try →
6

ADC Read and LED Control (Embedded C)

#include <avr/io.h>

int main(void) {
    ADCSRA = (1<<ADEN);
    DDRB |= (1<<PB0);
    while(1) {
        ADCSRA |= (1<<ADSC);
        while(ADCSRA & (1<<ADSC));
        if(ADC > 512) PORTB |= (1<<PB0);
        else PORTB &= ~(1<<PB0);
    }
}

Reads an analog sensor and controls an LED based on threshold on an AVR MCU.

Let’s Try →
7

Timer Interrupt Toggle LED (Embedded C)

#include <avr/io.h>
#include <avr/interrupt.h>
ISR(TIMER0_OVF_vect){ PORTB ^= (1<<PB0); }
int main(void){ DDRB |= (1<<PB0); TIMSK0 |= (1<<TOIE0); sei(); TCCR0B |= (1<<CS02); while(1); }

Uses a timer interrupt to toggle an LED periodically on an AVR.

Let’s Try →
8

Embedded C++ Motor Control Class

class Motor {
public:
    Motor(GPIO_TypeDef* dirPort, uint16_t dirPin, TIM_TypeDef* pwmTimer) : dirPort(dirPort), dirPin(dirPin), pwmTimer(pwmTimer) {}
    void forward() { dirPort->ODR |= (1<<dirPin); }
    void reverse() { dirPort->ODR &= ~(1<<dirPin); }
    void setSpeed(uint8_t duty) { pwmTimer->CCR1 = duty; }
private:
    GPIO_TypeDef* dirPort;
    uint16_t dirPin;
    TIM_TypeDef* pwmTimer;
};

Encapsulates motor control logic using PWM and direction pins on an ARM MCU.

Let’s Try →
9

SPI Send Byte (Embedded C)

#include <avr/io.h>
void spi_init() { DDRB |= (1<<PB3)|(1<<PB5)|(1<<PB2); SPCR = (1<<SPE)|(1<<MSTR); }
void spi_send(uint8_t data){ SPDR = data; while(!(SPSR & (1<<SPIF))); }
int main(){ spi_init(); while(1){ spi_send(0xAA); } }

Sends a byte over SPI on an AVR microcontroller.

Let’s Try →
10

I2C Master Send (Embedded C)

#include <avr/io.h>
#define F_SCL 100000UL
#define TWBR_VAL ((F_CPU/F_SCL-16)/2)
void i2c_init(){ TWBR=TWBR_VAL; }
void i2c_start(){ TWCR=(1<<TWSTA)|(1<<TWEN)|(1<<TWINT); while(!(TWCR&(1<<TWINT))); }
void i2c_send(uint8_t data){ TWDR=data; TWCR=(1<<TWEN)|(1<<TWINT); while(!(TWCR&(1<<TWINT))); }
int main(){ i2c_init(); i2c_start(); i2c_send(0xA0); }

Sends a byte over I2C as a master on AVR.

Let’s Try →

Frequently Asked Questions about Embedded-c-cpp

What is Embedded-c-cpp?

Embedded C/C++ refers to using the C or C++ programming languages for programming embedded systems. These are resource-constrained devices like microcontrollers, IoT devices, automotive controllers, and real-time systems where direct hardware control and performance are critical.

What are the primary use cases for Embedded-c-cpp?

Microcontroller firmware. Real-time operating systems (RTOS) tasks. IoT devices and sensors. Automotive ECU programming. Industrial automation and robotics

What are the strengths of Embedded-c-cpp?

Efficient and performant. Works on resource-constrained devices. Portable across architectures. Mature ecosystem with debugging and profiling tools. Widely taught and industrially adopted

What are the limitations of Embedded-c-cpp?

Manual memory management (risk of leaks, dangling pointers). Hardware-specific code reduces portability. No built-in safety guarantees (unlike SPARK or Rust). Debugging can be difficult on bare-metal targets. Concurrency and real-time issues require careful handling

How can I practice Embedded-c-cpp typing speed?

CodeSpeedTest offers 10+ real Embedded-c-cpp code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.