Simulate GPIO in qemu-based Raspberry Pi
The script (qemu-rpi-gpio
) present in this repository interacts with qemu
using the built-in qtest
protocol.
Wrapping the protocol and interacting with the memory of the guest operating system, it can set or reset the various GPIOs.
Note: Vanilla qemu (5.1.93) will not handle GPIO interrupts, therefore
loading /sys/class/gpio/gpio$N/direction
and waiting for an interrupt
will not do anything.
To enable interrupt support you'll need to download and compile this qemu fork.
You can install the script via pip with
pip install qemu-rpi-gpio
You need socat
, python3
and pexpect
library to use this
script.
These can be installed under ubuntu with:
sudo apt install python3-pexpect socat
To download raspbian images you'll need 7zip
sudo apt install p7zip-full
Download a raspbian image using
./qemu-pi-setup/setup.sh
Be carefull... before stare you need to define a new user and password. read this https://www.raspberrypi.com/news/raspberry-pi-bullseye-update-april-2022/
echo 'mypassword' | openssl passwd -6 -stdin
$6$HSRPDe6rqSBNxBnC$B3dJSx59Qd4HAPu.t0PwhlydBsyZ21MSplCxpJzMIB05h1I/aIqvNb6MQ35LU28UsVrK3918DHD03hUoCNXbS.
mount -o loop,offset=4194304 /root/raspios_lite_armhf_latest boot
echo 'pi:$6$HSRPDe6rqSBNxBnC$B3dJSx59Qd4HAPu.t0PwhlydBsyZ21MSplCxpJzMIB05h1I/aIqvNb6MQ35LU28UsVrK3918DHD03hUoCNXbS.'> boot/userconf
umount boot/
the new password is 'mypassword'
After this operation, execute the script to load the unix socket and make it available to qemu
./qemu-rpi-gpio
You will be prompted to an interactive shell, you can find the commands available in the Interacting with gpios section.
In another terminal execute the ./qemu-pi-setup/run.sh
script, this will execute a virtual
raspberry pi and attach it to the gpio application.
If you close the raspberry pi you can reload the socket using the command
reload
in the qemu-rpi-gpio prompt.
First of all, you need to export GPIOs in your guest Linux. In a shell on your raspberry pi do:
$ sudo su -
# echo 4 >/sys/class/gpio/export
# echo in >/sys/class/gpio/gpio4/direction
The main commands in the qemu-rpi-gpio
application are:
command | description | example |
---|---|---|
get $N |
get the value of GPIO $N | get 4 |
set $N $V |
set the value of GPIO $N to $V (1 or 0) | set 4 1 |
You can get the full list of commands using help
For instance, let us set the value of the pre-exported gpio 4
(gpio)> set 4 1
Now you can read the value of your gpio
# cat /sys/class/gpio/gpio4/value
1
If we set it to zero, it will be immediately reflected in the guest system
(gpio)> set 4 0
# cat /sys/class/gpio/gpio4/value
0