Day 9 - GPIO Driver with gpiod and Device Tree¶
๐ฏ Objective¶
Learn how to control real hardware (GPIO) from a Linux kernel driver using:
- Platform driver
- Device Tree (DT)
- Descriptor-based GPIO API (
gpiod_*) - Character device interface (
/dev/mygpio)
๐ง Key Concepts¶
1. From Legacy GPIO to gpiod¶
Old (deprecated):
Problems: - GPIO number is not portable - Platform dependent - Hard to integrate with Device Tree
New (recommended):
Advantages: - No global GPIO number dependency - Works with Device Tree - Portable across platforms
2. Device Tree Binding¶
Device Tree defines hardware mapping:
Driver retrieves GPIO using:
Mapping rule:
| DT property | gpiod_get argument |
|---|---|
led-gpios |
"led" |
3. Platform Driver Flow¶
Device Tree
โ
platform device
โ
driver probe()
โ
gpiod_get()
โ
character device (/dev/mygpio)
4. Character Device Interface¶
User space interacts via:
Driver implements:
write()โ control GPIOread()โ read GPIO state
๐ง Implementation Highlights¶
write()¶
- Accepts
0or1 - Controls GPIO output
read()¶
Returns:
"0\n"or"1\n"
EOF Handling¶
- Required for
catto terminate - Standard char driver pattern
๐งช Testing¶
Setup¶
GPIO Control¶
GPIO Read¶
Live Debug¶
๐ Debug Notes¶
1. Legacy GPIO issue on Raspberry Pi 5¶
Using:
failed because:
- GPIO number โ BCM number
- Requires global GPIO index
- Not reliable on modern platforms
2. "write() not working" false alarm¶
Observed:
- No
GPIO set to Xindmesg - Assumed
write()was not called
Actual cause:
dmesg | tailmissed logs- Driver was reloaded multiple times
- Logs overwritten by probe/remove messages
3. System state inconsistency¶
Repeated:
dtoverlayinsmod / rmmod
caused:
- Multiple probe/remove cycles
- Confusing runtime state
4. Reboot fixed the issue¶
After reboot:
- GPIO behavior returned to normal
- Driver worked as expected
Conclusion:
Issue was caused by stale runtime state, not code logic.
๐ What I Learned¶
- Modern Linux uses
gpiod, notgpio_request - Device Tree defines hardware, driver should not hardcode GPIO
- Platform driver + DT is the standard model
- Char device bridges user space and kernel
- Debugging requires careful log observation (
dmesg -w)
๐ Next Steps¶
- Add interrupt support (GPIO button)
- Learn IRQ handling
- Explore poll / event-driven driver design
๐งฉ Summary¶
Day 9 marks the transition from:
Key achievement:
โ Successfully controlled GPIO via Linux kernel driver
โ Integrated Device Tree + platform driver
โ Implemented read/write interface
โ Understood modern GPIO architecture