Link to the video: https://youtu.be/FzxIcNyPZQ0
Github: https://github.com/davidcxw/Rasberry-Pi-LED-Project
Goal:
In this project, I demonstrate how to write a loadable kernel module for the Raspberry Pi and interface with it with a user space program. The LKM lights LEDs to represent the amount of CPU usage across the cores on the Raspberry Pi. My friend David and I both did this quickly, and would suggest it to people interested in writing their first driver for the Raspberry Pi.
Architecture

Pi Setup
- Micro SD Card
- 10 gpio wires, 1 connected to ground, 1 to 3.3 volts
- LEDS, each connected in parallel, also in series with a resistor.
- Resistor: 220 Ohms
- Heatsinks for cooling
- HDMI cable for monitor
- Usbs with mouse and keyboard
- SSH enabled with VNC server setup
- Raspbian OS 9, with a flavor of debian.
- Linux version 4.14.98-v7+ with the kernel headers
We ended buying a lot of the hardware from CanaKit.



Linux Kernel Module (LKM)
Make sure to include the Linux Kernel files not your standard ones.

Init function
Set up the gpios and the driver.

Callback function
Whenever the driver file is written to, the LKM reads that driver file, and updates the LEDs.
Exit function
Where we release the gpios and the driver.

Sysfs file system for device
Created the class, device, and file objects

Destroy them upon exiting the LKM

Makefile

CPU Usage
- Read from /proc/stat file
- Read in user time, nice time, system time, idle time, iowait time
- We specified a write frequency to the sysfs file of about a second
usage: dd if=/dev/zero of=/dev/null as stress test: writing zeros to the abyss

http://www.linuxhowtos.org/System/procstat.htm
We use the first 3 numbers: non-idle_time = user time + nice time + system time
And the next 2 numbers: idle_time = idle time + iowait time
Total = non-idle_time + idle_time
Caclulate the cpu usage as % increase in non-idle time: change in non_idle_time / total_time
Exact code below:

That’s pretty much it! You can wire up your GPIOs however you want. And also replace the userspace code with something else like memory usage or temperature.