API Reference¶
SimulRPi.GPIO
¶
Module that partly fakes RPi.GPIO and simulates some I/O devices.
It simulates these I/O devices connected to a Raspberry Pi:
push buttons by listening to pressed keyboard keys and
LEDs by displaying small circles blinking on the terminal along with their GPIO pin number.
When a LED is turned on, it is shown as a small red circle on the terminal. The package pynput is used to monitor the keyboard for any pressed key.
Example: terminal output
o [11] o [9] o [10]
where each circle represents a LED (here they are all turned off) and the number between brackets is the associated GPIO pin number.
Important
This library is not a Raspberry Pi emulator nor a complete mock-up of RPi.GPIO, only the most important functions that I needed for my Darth-Vader-RPi project were added.
If there is enough interest in this library, I will eventually mock more functions from RPi.GPIO. Thus, let me know through SimulRPi’s issues page if you want me to add more things to this library.
-
class
GPIO.
Manager
[source]¶ Bases:
object
Class that manages the pin database (
PinDB
) and the threads responsible for displaying “LEDs” on the terminal and listening for keys pressed/released.The threads are not started right away in
__init__()
but ininput()
for the listener thread andoutput()
for the displaying thread.They are eventually stopped in
cleanup()
.- Variables
mode (
int
) – Numbering system used to identify the I/O pins on an RPi: BOARD or BCM. Default value isNone
.warnings (
bool
) – Whether to show warnings when using a pin other than the default GPIO function (input). Default value is True.enable_printing (
bool
) – Whether to enable printing on the terminal. Default value is True.pin_db (
PinDB
) – APin
database. SeePinDB
on how to access it.key_to_channel_map (
dict
) – A dictionary that maps keyboard keys (string
) to GPIO channel numbers (int
). By default, it takes the keys and values defined inSimulRPi.mapping
’s keymapdefault_key_to_channel_map
.channel_to_key_map (
dict
) – The reverse dictionary ofkey_to_channel_map
. It maps channels to keys.nb_prints (
int
) – Number of times the displaying threadth_display_leds
has printed blinking circles on the terminal. It is used when debugging the displaying thread.th_display_leds (
threading.Thread
) – Thread responsible for displaying small blinking circles on the terminal as to simulate LEDs connected to an RPi.th_listener (
keyboard.Listener
) –Thread responsible for listening on any pressed or released key as to simulate push buttons connected to an RPi.
Note
A keyboard listener is a
threading.Thread
, and all callbacks will be invoked from the thread.Ref.: https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard
Important
If the module
pynput.keyboard
couldn’t be imported, the listener threadth_listener
will not be created and the parts of theSimulRPi
library that monitors the keyboard for any pressed or released key will be ignored. Only the threadth_display_leds
that displays “LEDs” on the terminal will be created.This is necessary for example in the case we are running tests on travis and we don’t want travis to install
pynput
in a headless setup because an exception will get raised:Xlib.error.DisplayNameError: Bad display name ""
The tests involving
pynput
will be performed with a mock version ofpynput
.-
add_pin
(channel, gpio_function, pull_up_down=None, initial=None)[source]¶ Add an input or output pin to the pin database.
An instance of
Pin
is created with the given arguments and added to the pin databasePinDB
.- Parameters
channel (
int
) – GPIO channel number associated with thePin
to be added in the pin database.gpio_function (
int
) – Function of a GPIO channel: 1 (GPIO.INPUT) or 0 (GPIO.OUTPUT).pull_up_down (
int
orNone
, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value isNone
.initial (
int
orNone
, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value isNone
.
-
display_leds
()[source]¶ Simulate LEDs on an RPi by blinking small circles on a terminal.
In order to simulate LEDs turning on/off on an RPi, small circles are blinked on the terminal along with their GPIO pin number.
When a LED is turned on, it is shown as a small red circle on the terminal.
Example: terminal output
o [11] o [9] o [10]
where each circle represents a LED (here they are all turned off) and the number between brackets is the associated GPIO pin number.
Note
If
enable_printing
is set to True, the terminal’s cursor will be hidden. It will be eventually shown again incleanup()
which is called by the main program when it is exiting.The reason is to avoid messing with the display of LEDs by the displaying thread
th_display_leds
.Important
display_leds()
should be run by a thread and eventually stopped from the main thread by setting itsdo_run
attribute to False to let the thread exit from its target function.For example:
th = threading.Thread(target=self.display_leds, args=()) th.start() # Your other code ... # Time to stop thread th.do_run = False th.join()
-
static
get_key_name
(key)[source]¶ Get the name of a keyboard key as a string.
The name of the special or alphanumeric key is given by the package pynput.
- Parameters
key (
pynput.keyboard.Key
orpynput.keyboard.KeyCode
) – The keyboard key (frompynput.keyboard
) whose name will be returned.- Returns
key_name – Returns the name of the given keyboard key if one was found by pynput. Otherwise, it returns
None
.- Return type
-
on_press
(key)[source]¶ When a valid keyboard key is pressed, set its state to GPIO.LOW.
Callback invoked from the thread
GPIO.Manager.th_listener
.This thread is used to monitor the keyboard for any valid pressed key. Only keys defined in the pin database are treated, i.e. keys that were configured with
GPIO.setup()
are further processed.Once a valid key is detected as pressed, its state is changed to GPIO.LOW.
- Parameters
key (
pynput.keyboard.Key
,pynput.keyboard.KeyCode
, orNone
) –The key parameter passed to callbacks is
a
pynput.keyboard.Key
for special keys,a
pynput.keyboard.KeyCode
for normal alphanumeric keys, orNone
for unknown keys.
Ref.: https://bit.ly/3k4whEs
-
on_release
(key)[source]¶ When a valid keyboard key is released, set its state to GPIO.HIGH.
Callback invoked from the thread
GPIO.Manager.th_listener
.This thread is used to monitor the keyboard for any valid released key. Only keys defined in the pin database are treated, i.e. keys that were configured with
GPIO.setup()
are further processed.Once a valid key is detected as released, its state is changed to GPIO.HIGH.
- Parameters
key (
pynput.keyboard.Key
,pynput.keyboard.KeyCode
, orNone
) –The key parameter passed to callbacks is
a
pynput.keyboard.Key
for special keys,a
pynput.keyboard.KeyCode
for normal alphanumeric keys, orNone
for unknown keys.
Ref.: https://bit.ly/3k4whEs
-
update_keymap
(new_keymap)[source]¶ Update the default dictionary mapping keys and GPIO channels.
new_keymap
is a dictionary mapping some keys to their new GPIO channels, and will be used to update the default key-channel mapping defined inSimulRPi.mapping
.- Parameters
new_keymap (
dict
) –Dictionary that maps keys (
str
) to their new GPIO channels (int
).For example:
"key_to_channel_map": { "f": 24, "g": 25, "h": 23 }
Note
If a key is associated to a channel that is already taken by another key, both keys’ channels will be swapped. However, if a key is being linked to a
None
channel, then it will take on the maximum channel number available + 1.
-
static
validate_key
(key)[source]¶ Validate if a key is recognized by pynput
A valid key can either be:
a
pynput.keyboard.Key
for special keys (e.g.tab
orup
), ora
pynput.keyboard.KeyCode
for normal alphanumeric keys.
- Parameters
key (
str
) – The key (e.g. ‘tab’) that will be validated.- Returns
retval – Returns True if it’s a valid key. Otherwise, it returns False.
- Return type
References
pynput
reference: https://pynput.readthedocs.io/en/latest/keyboard.html#referenceSee also
SimulRPi.mapping
for a list of special keys supported by pynput.
-
class
GPIO.
Pin
(channel, gpio_function, key=None, pull_up_down=None, initial=None)[source]¶ Bases:
object
Class that represents a GPIO pin.
- Parameters
channel (
int
) – GPIO channel number based on the numbering system you have specified (BOARD or BCM).gpio_function (
int
) – Function of a GPIO channel: 1 (GPIO.INPUT) or 0 (GPIO.OUTPUT).key (
str
orNone
, optional) – Key associated with the GPIO channel, e.g. “k”.pull_up_down (
int
orNone
, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value isNone
.initial (
int
orNone
, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value isNone
.
- Variables
state (
int
) – State of the GPIO channel: 1 (HIGH) or 0 (LOW).
-
class
GPIO.
PinDB
[source]¶ Bases:
object
Class for storing and modifying
Pin
s.Each instance of
GPIO.Pin
is saved in a dictionary that maps it to its channel number.Note
The dictionary (a “database” of
Pin
s) must be accessed through the different methods available inPinDB
, e.g.get_pin_from_channel()
.-
create_pin
(channel, gpio_function, key=None, pull_up_down=None, initial=None)[source]¶ Create an instance of
GPIO.Pin
and save it in a dictionary.Based on the given arguments, an instance of
GPIO.Pin
is created and added to a dictionary that acts like a database of pins with key being the pin’s channel and the value is an instance ofPin
.- Parameters
channel (
int
) – GPIO channel number based on the numbering system you have specified (BOARD or BCM).gpio_function (
int
) – Function of a GPIO channel: 1 (GPIO.INPUT) or 0 (GPIO.OUTPUT).key (
str
orNone
, optional) – Key associated with the GPIO channel, e.g. “k”.pull_up_down (
int
orNone
, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value isNone
.initial (
int
orNone
, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value isNone
.
-
get_pin_state
(channel)[source]¶ Get a
Pin
’s state from a given channel.The state associated with a
Pin
can either be 1 (HIGH) or 0 (LOW).
-
set_pin_key_from_channel
(channel, key)[source]¶ Set a
Pin
’s key from a given channel.A
Pin
is retrieved based on a given channel, then itskey
is set with key.
-
set_pin_state_from_channel
(channel, state)[source]¶ Set a
Pin
’s state from a given channel.A
Pin
is retrieved based on a given channel, then itsstate
is set with state.- Parameters
- Returns
retval – Returns True if the
Pin
was successfully set with state. Otherwise, it returns False because the pin doesn’t exist based on the given channel.- Return type
-
set_pin_state_from_key
(key, state)[source]¶ Set a
Pin
’s state from a given key.A
Pin
is retrieved based on a given key, then itsstate
is set with state.- Parameters
- Returns
retval – Returns True if the
Pin
was successfully set with state. Otherwise, it returns False because the pin doesn’t exist based on the given key.- Return type
-
-
GPIO.
cleanup
()[source]¶ Clean up any resources (e.g. GPIO channels).
At the end of any program, it is good practice to clean up any resources you might have used. This is no different with RPi.GPIO. By returning all channels you have used back to inputs with no pull up/down, you can avoid accidental damage to your RPi by shorting out the pins. [Ref: RPi.GPIO wiki]
Also, the two threads responsible for displaying “LEDs” on the terminal and listening for pressed/released keys are stopped.
Note
On an RPi,
cleanup()
will:only clean up GPIO channels that your script has used
also clear the pin numbering system in use (BOARD or BCM)
Ref.: RPi.GPIO wiki
When using the package
SimulRPi
,cleanup()
will:stop the displaying thread
Manager.th_display_leds
stop the listener thread
Manager.th_listener
show the cursor again which was hidden in
Manager.display_leds()
reset the
GPIO.manager
’s attributes (an instance ofManager
)
-
GPIO.
input
(channel)[source]¶ Read the value of a GPIO pin.
- Parameters
channel (
int
) – Input GPIO channel number based on the numbering system you have specified (BOARD or BCM).- Returns
state – If no
Pin
could be retrieved based on the given channel number, thenNone
is returned. Otherwise, thePin
’s state is returned: 1 (HIGH) or 0 (LOW).- Return type
Note
The listener thread (for monitoring pressed key) is started if it is not alive, i.e. it is not already running.
-
GPIO.
output
(channel, state)[source]¶ Set the output state of a GPIO pin.
- Parameters
Note
The displaying thread (for showing “LEDs” on the terminal) is started if it is not alive, i.e. it is not already running.
-
GPIO.
setkeymap
(key_to_channel_map)[source]¶ Set the keymap dictionary with new keys and channels.
The default dictionary
default_key_to_channel_map
(defined inSimulRPi.mapping
) that maps keyboard keys to GPIO channels can be modified by providing your own mappingkey_to_channel_map
containing only the keys and channels that you want to be modified.- Parameters
key_to_channel_map (
dict
) –A dictionary mapping keys (
str
) and GPIO channels (int
) that will be used to update the default keymap found inSimulRPi.mapping
.For example:
key_to_channel_map: { "q": 23, "w": 24, "e": 25 }
-
GPIO.
setmode
(mode)[source]¶ Set the numbering system used to identify the I/O pins on an RPi within RPi.GPIO.
There are two ways of numbering the I/O pins on a Raspberry Pi within RPi.GPIO:
The BOARD numbering system: refers to the pin numbers on the P1 header of the Raspberry Pi board
The BCM numbers: refers to the channel numbers on the Broadcom SOC.
- Parameters
mode (
int
) – Numbering system used to identify the I/O pins on an RPi: BOARD or BCM.
References
Function description and more info from RPi.GPIO wiki.
-
GPIO.
setprinting
(enable_printing)[source]¶ Enable printing on the terminal.
If printing is enabled, small blinking red circles will be shown on the terminal, simulating LEDs connected to a Raspberry Pi. Otherwise, nothing will be printed on the terminal.
- Parameters
enable_printing (
bool
) – Whether to enable printing on the terminal.
-
GPIO.
setup
(channel, gpio_function, pull_up_down=None, initial=None)[source]¶ Setup a GPIO channel as an input or output.
To configure a channel as an input:
GPIO.setup(channel, GPIO.IN)
To configure a channel as an output:
GPIO.setup(channel, GPIO.OUT)
You can also specify an initial value for your output channel:
GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH)
- Parameters
channel (
int
) – GPIO channel number based on the numbering system you have specified (BOARD or BCM).gpio_function (
int
) – Function of a GPIO channel: 1 (GPIO.INPUT) or 0 (GPIO.OUTPUT).pull_up_down (
int
orNone
, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value isNone
.initial (
int
orNone
, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value isNone
.
References
-
GPIO.
setwarnings
(show_warnings)[source]¶ Set warnings when configuring a GPIO pin other than the default (input).
It is possible that you have more than one script/circuit on the GPIO of your Raspberry Pi. As a result of this, if RPi.GPIO detects that a pin has been configured to something other than the default (input), you get a warning when you try to configure a script. [Ref: RPi.GPIO wiki]
- Parameters
show_warnings (
bool
) – Whether to show warnings when using a pin other than the default GPIO function (input).
SimulRPi.mapping
¶
Module that defines the dictionary that maps keys and GPIO channels.
This module defines the default mapping between keyboard keys and GPIO
channels. It is used by GPIO
when monitoring the keyboard with the
package pynput for any pressed/released key as to simulate a push button
connected to a Raspberry Pi.
Notes
In early RPi models, there are 17 GPIO channels and in late RPi models, there are 28 GPIO channels.
By default, 28 GPIO channels (from 0 to 27) are mapped to alphanumeric and special keys. See the content of the default keymap.
Here is the full list of special keys you can use with info about some of them (taken from pynput reference):
alt
alt_gr
alt_l
alt_r
backspace
caps_lock
cmd
: A generic command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key.
cmd_l
: The left command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key.
cmd_r
: The right command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key.
ctrl
: A generic Ctrl key.
ctrl_l
ctrl_r
delete
down
end
enter
esc
f1
: The function keys. F1 to F20 are defined.
home
insert
: The Insert key. This may be undefined for some platforms.
left
media_next
media_play_pause
media_previous
media_volume_down
media_volume_mute
media_volume_up
menu
: The Menu key. This may be undefined for some platforms.
num_lock
: The NumLock key. This may be undefined for some platforms.
page_down
page_up
pause
: The Pause/Break key. This may be undefined for some platforms.
print_screen
: The PrintScreen key. This may be undefined for some platforms.
right
scroll_lock
shift
shift_l
shift_r
space
tab
up
References
RPi Header: https://bit.ly/30ZM2Uj
pynput: https://pynput.readthedocs.io/
Important
GPIO.setkeymap()
allows you to modify the default keymap.The keys for the default keymap
default_key_to_channel_map
must be strings and their values (the channels) should be integers.
Content of the default keymap dictionary (key: keyboard key as
string
, value: GPIO channel as int
):
default_key_to_channel_map = {
"0": 0, # sudo on mac
"1": 1, # sudo on mac
"2": 2, # sudo on mac
"3": 3, # sudo on mac
"4": 4, # sudo on mac
"5": 5, # sudo on mac
"6": 6, # sudo on mac
"7": 7, # sudo on mac
"8": 8, # sudo on mac
"9": 9, # sudo on mac
"q": 10, # sudo on mac
"alt": 11, # left alt on mac
"alt_l": 12, # not recognized on mac
"alt_r": 13,
"alt_gr": 14,
"cmd": 15, # left cmd on mac
"cmd_l": 16, # not recognized on mac
"cmd_r": 17,
"ctrl": 18, # left ctrl on mac
"ctrl_l": 19, # not recognized on mac
"ctrl_r": 20,
"media_play_pause": 21,
"media_volume_down": 22,
"media_volume_mute": 23,
"media_volume_up": 24,
"shift": 25, # left shift on mac
"shift_l": 26, # not recognized on mac
"shift_r": 27,
}
Important
There are some platform limitations on using some of the keyboard keys with
pynput
.
For instance, on macOS some keyboard keys may require that you run your
script with sudo. All alphanumeric keys and some special keys
(e.g. backspace
and right
) require sudo. In the content of
default_key_to_channel_map shown
previously, I commented those keyboard keys that need sudo on macOS. The
others don’t need sudo on macOS such as cmd_r
and shift
.
For more information about those platform limitations, see pynput documentation.
Warning
If you want to be able to run your python script with sudo in order to use
some keys that require it, you might need to edit /etc/sudoers to add
your PYTHONPATH
if your script makes use of your PYTHONPATH
as
setup in the ~/.bashrc file. However, I don’t recommend editing
/etc/sudoers since you might break your sudo command (e.g.
sudo: /etc/sudoers is owned by uid 501, should be 0
).
Instead, use the keys that don’t requre sudo such as cmd_r
and
shift
on macOS.
Note
On macOS, if the left keys alt_l
, ctrl_l
, cmd_l
, and
shift_l
are not recognized, use their generic counterparts instead:
alt
, ctrl
, cmd
, and shift
.
SimulRPi.run_examples
¶
Script for executing code examples on a Raspberry Pi or computer (simulation).
This script allows you to run different code examples on your Raspberry Pi (RPi) or computer in which case it will make use of the library SimulRPi which partly fakes RPi.GPIO.
The code examples test different parts of the library SimulRPi
in order to
show what it is capable of simulating from an RPi:
Turn on/off LEDs
Detect pressed button and perform an action
Usage¶
Once the SimulRPi package is installed, you should have access to
the run_examples
script:
$ run_examples -h
run_examples [-h] [-v] -e EXAMPLE_NUMBER [-m {BOARD,BCM}] [-s]
[-l [LED_CHANNEL [LED_CHANNEL ...]]]
[-b BUTTON_CHANNEL] [-k KEY_NAME]
[-t TOTAL_TIME_BLINKING] [--on TIME_LED_ON]
[--off TIME_LED_OFF]
Run the script on the RPi:
$ run_examples
Run the code for example #1 on your computer using SimulRPi.GPIO which simulates RPi.GPIO: and default values for the options -l (channel 10) and --on (1 second):
$ run_examples -s -e 1
-
run_examples.
ex1_turn_on_led
(channel, time_led_on=3)[source]¶ Example 1: Turn ON a LED for some specified time.
A LED will be turned on for
time_led_on
seconds.
-
run_examples.
ex2_turn_on_many_leds
(channels, time_led_on=3)[source]¶ Example 2: Turn ON multiple LEDs for some specified time.
All LEDs will be turned on for
time_led_on
seconds.
Example 3: Detect if a button is pressed.
The function waits for the button to be pressed associated with the given
channel
. As soon as the button is pressed, a message is printed and the function exits.- Parameters
channel (
int
) – Input GPIO channel number based on the numbering system you have specified (BOARD or BCM).
Note
If the simulation mode is enabled (-s), the specified keyboard key will be detected if pressed. The keyboard key can be specified through the command line options -b (button channel) or -k (the key name, e.g. ‘ctrl’). See script’s usage.
-
run_examples.
ex4_blink_led
(channel, total_time_blinking=4, time_led_on=0.5, time_led_off=0.5)[source]¶ Example 4: Blink a LED for some specified time.
The led will blink for a total of
total_time_blinking
seconds. The LED will stay turned on fortime_led_on
seconds before turning off fortime_led_off
seconds, and so on untiltotal_time_blinking
seconds elapse.Press
ctrl
+c
to stop the blinking completely and exit from the function.- Parameters
channel (
int
) – Output GPIO channel number based on the numbering system you have specified (BOARD or BCM).total_time_blinking (
float
, optional) – Total time in seconds the LED will be blinking. The default value is 4 seconds.time_led_on (
float
, optional) – Time in seconds the LED will stay turned ON at a time. The default value is 0.5 seconds.time_led_off (
float
, optional) – Time in seconds the LED will stay turned OFF at a time. The default value is 0.5 seconds.
Example 5: If a button is pressed, blink a LED for some specified time.
As soon as the button from the given
button_channel
is pressed, the LED will blink for a total oftotal_time_blinking
seconds.The LED will stay turned on for
time_led_on
seconds before turning off fortime_led_off
seconds, and so on untiltotal_time_blinking
seconds elapse.Press
ctrl
+c
to stop the blinking completely and exit from the function.- Parameters
led_channel (
int
) – Output GPIO channel number based on the numbering system you have specified (BOARD or BCM).button_channel (
int
) – Input GPIO channel number based on the numbering system you have specified (BOARD or BCM).total_time_blinking (
float
, optional) – Total time in seconds the LED will be blinking. The default value is 4 seconds.time_led_on (
float
, optional) – Time in seconds the LED will stay turned ON at a time. The default value is 0.5 seconds.time_led_off (
float
, optional) – Time in seconds the LED will stay turned OFF at a time. The default value is 0.5 seconds.
Note
If the simulation mode is enabled (-s), the specified keyboard key will be detected if pressed. The keyboard key can be specified through the command line options -b (button channel) or -k (the key name, e.g. ‘ctrl’). See script’s usage.
-
run_examples.
main
()[source]¶ Main entry-point to the script.
According to the user’s choice of action, the script might run one of the specified code examples.
If the simulation flag (-s) is used, then the module SimulRPi.GPIO will be used which partly fakes RPi.GPIO.
Notes
Only one action at a time can be performed.
-
run_examples.
setup_argparser
()[source]¶ Setup the argument parser for the command-line script.
The script allows you to run a code example on your RPi or on your computer. In the latter case, it will make use of the module SimulRPi.GPIO which partly fakes RPi.GPIO.
- Returns
args – Simple class used by default by
parse_args()
to create an object holding attributes and return it 1.- Return type
References
SimulRPi.utils
¶
Collection of utility functions used for the SimulRPi library.
-
utils.
blink_led
(channel, time_led_on, time_led_off)[source]¶ Blink one LED.
A LED on the given
channel
will be turned ON and OFF fortime_led_on
seconds andtime_led_off
seconds, respectively.