Memory Mapped IO vs Port Mapped IO in Embedded C: Key Differences
Memory Mapped IO, device registers are accessed like normal memory locations using regular pointers. In Port Mapped IO, special CPU instructions access device ports separately from memory, often using in and out instructions.Quick Comparison
This table summarizes the main differences between Memory Mapped IO and Port Mapped IO in embedded C.
| Feature | Memory Mapped IO | Port Mapped IO |
|---|---|---|
| Addressing | Uses normal memory addresses | Uses separate IO port addresses |
| Access Method | Accessed via regular load/store instructions | Accessed via special IO instructions (e.g., in/out) |
| CPU Support | Supported by most CPUs | Supported mainly by x86 and some microcontrollers |
| Code Simplicity | Simpler, uses pointers | Requires special instructions or intrinsics |
| Address Space | Shares address space with memory | Separate IO address space |
| Speed | Usually faster due to direct memory access | May be slower due to special instructions |
Key Differences
Memory Mapped IO treats device registers as if they are normal memory locations. This means you can use pointers in C to read or write to these registers just like you do with variables. It simplifies programming because you don't need special instructions; the CPU's normal memory instructions handle the IO.
On the other hand, Port Mapped IO uses a separate address space for IO devices. The CPU has special instructions like in and out to communicate with these ports. This separation can help avoid conflicts between memory and IO addresses but requires special handling in code.
Memory Mapped IO is common in many embedded systems and modern CPUs, while Port Mapped IO is mostly found in older or specific architectures like x86. Choosing between them depends on the hardware design and CPU capabilities.
Code Comparison
Here is how you read a device register at address 0x4000 using Memory Mapped IO in embedded C.
volatile unsigned int *device_reg = (volatile unsigned int *)0x4000; unsigned int read_value = *device_reg; // Use read_value as needed
Port Mapped IO Equivalent
Here is how you read from an IO port 0x20 using Port Mapped IO on x86 with embedded C using inline assembly.
unsigned char port_in(unsigned short port) {
unsigned char value;
__asm__ volatile ("inb %1, %0" : "=a" (value) : "Nd" (port));
return value;
}
unsigned char read_value = port_in(0x20);When to Use Which
Choose Memory Mapped IO when your hardware supports accessing device registers as memory addresses, as it simplifies code and usually offers faster access. It is ideal for most modern embedded systems.
Choose Port Mapped IO when working with CPUs or microcontrollers that have a separate IO address space and special instructions, like x86 architectures. It is useful when you want to keep IO separate from memory or when hardware requires it.