pigpiod_if2(3)
๐ pigpiod_if2(3) โ pigpio archive ๐
Okay bestie, this is the manual for pigpiod_if2 from the pigpio archive. It's a C library for the Raspberry that lets you control the GPIO via the socket interface to the pigpio daemon. No cap. ๐ซถ
๐ธ NAME ๐ธ
pigpiod_if2 โ A C library to interface to the pigpio daemon.
โจ SYNOPSIS โจ
#include <pigpiod_if2.h>
gcc -Wall -pthread -o prog prog.c -lpigpiod_if2 -lrt
./prog
๐ฆ DESCRIPTION ๐ฆ
pigpiod_if2 is a C library for the Raspberry which allows control of the GPIO via the socket interface to the pigpio daemon. It's giving remote control but for pins. ๐
๐ Features ๐
- hardware timed PWM on any of GPIO 0-31
- hardware timed servo pulses on any of GPIO 0-31
- callbacks when any of GPIO 0-31 change state
- callbacks at timed intervals
- reading/writing all of the GPIO in a bank as one operation
- individually setting GPIO modes, reading and writing
- notifications when any of GPIO 0-31 change state
- the construction of output waveforms with microsecond timing
- rudimentary permission control over GPIO
- a simple interface to start and stop new threads
- I2C, SPI, and serial link wrappers
- creating and running scripts on the pigpio daemon
๐ GPIO ๐
ALL GPIO are identified by their Broadcom number. That's the number, bestie. Remember it. ๐
๐ Notes ๐
The PWM and servo pulses are timed using the DMA and PWM/PCM peripherals.
โจ Usage โจ
Include <pigpiod_if2.h> in your source files.
Assuming your source is in prog.c use the following command to build
gcc -Wall -pthread -o prog prog.c -lpigpiod_if2 -lrt
to run make sure the pigpio daemon is running
sudo pigpiod
./prog # sudo is not required to run programs linked to pigpiod_if2
For examples see x_pigpiod_if2.c within the pigpio archive file.
๐ Notes ๐
All the functions which return an int return < 0 on error.
๐ OVERVIEW ๐
๐ ESSENTIAL ๐
pigpio_startโ Connects to a pigpio daemonpigpio_stopโ Disconnects from a pigpio daemon
๐ง BASIC ๐ง
set_modeโ Set a GPIO modeget_modeโ Get a GPIO modeset_pull_up_downโ Set/clear GPIO pull up/down resistorgpio_readโ Read a GPIOgpio_writeโ Write a GPIO
๐ฅ PWM (overrides servo commands on same GPIO) ๐ฅ
set_PWM_dutycycleโ Start/stop PWM pulses on a GPIOset_PWM_frequencyโ Configure PWM frequency for a GPIOset_PWM_rangeโ Configure PWM range for a GPIOget_PWM_dutycycleโ Get the PWM dutycycle in use on a GPIOget_PWM_frequencyโ Get configured PWM frequency for a GPIOget_PWM_rangeโ Get configured PWM range for a GPIOget_PWM_real_rangeโ Get underlying PWM range for a GPIO
๐ฆ Servo (overrides PWM commands on same GPIO) ๐ฆ
set_servo_pulsewidthโ Start/stop servo pulses on a GPIOget_servo_pulsewidthโ Get the servo pulsewidth in use on a GPIO
๐ซ INTERMEDIATE ๐ซ
gpio_triggerโ Send a trigger pulse to a GPIO.set_watchdogโ Set a watchdog on a GPIO.read_bank_1โ Read all GPIO in bank 1read_bank_2โ Read all GPIO in bank 2clear_bank_1โ Clear selected GPIO in bank 1clear_bank_2โ Clear selected GPIO in bank 2set_bank_1โ Set selected GPIO in bank 1set_bank_2โ Set selected GPIO in bank 2callbackโ Create GPIO level change callbackcallback_exโ Create GPIO level change callback, extendedcallback_cancelโ Cancel a callbackwait_for_edgeโ Wait for GPIO level changestart_threadโ Start a new threadstop_threadโ Stop a previously started thread
๐ ADVANCED ๐
notify_openโ Request a notification handlenotify_beginโ Start notifications for selected GPIOnotify_pauseโ Pause notificationsnotify_closeโ Close a notificationhardware_clockโ Start hardware clock on supported GPIOhardware_PWMโ Start hardware PWM on supported GPIOset_glitch_filterโ Set a glitch filter on a GPIOset_noise_filterโ Set a noise filter on a GPIOset_pad_strengthโ Sets a pads drive strengthget_pad_strengthโ Gets a pads drive strengthshell_โ Executes a shell command
๐จ Custom ๐จ
custom_1โ User custom function 1custom_2โ User custom function 2
โญ Events โญ
event_callbackโ Sets a callback for an eventevent_callback_exโ Sets a callback for an event, extendedevent_callback_cancelโ Cancel an event callbackevent_triggerโ Triggers an eventwait_for_eventโ Wait for an event
๐ Scripts ๐
store_scriptโ Store a scriptrun_scriptโ Run a stored scriptupdate_scriptโ Set a scripts parametersscript_statusโ Get script status and parametersstop_scriptโ Stop a running scriptdelete_scriptโ Delete a stored script
๐ I2C ๐
i2c_openโ Opens an I2C devicei2c_closeโ Closes an I2C devicei2c_write_quickโ smbus write quicki2c_read_byteโ smbus read bytei2c_write_byteโ smbus write bytei2c_read_byte_dataโ smbus read byte datai2c_write_byte_dataโ smbus write byte datai2c_read_word_dataโ smbus read word datai2c_write_word_dataโ smbus write word datai2c_read_block_dataโ smbus read block datai2c_write_block_dataโ smbus write block datai2c_read_i2c_block_dataโ smbus read I2C block datai2c_write_i2c_block_dataโ smbus write I2C block datai2c_read_deviceโ Reads the raw I2C devicei2c_write_deviceโ Writes the raw I2C devicei2c_process_callโ smbus process calli2c_block_process_callโ smbus block process calli2c_zipโ Performs multiple I2C transactions
๐ I2C BIT BANG ๐
bb_i2c_openโ Opens GPIO for bit banging I2Cbb_i2c_closeโ Closes GPIO for bit banging I2Cbb_i2c_zipโ Performs bit banged I2C transactions
๐ I2C/SPI SLAVE ๐
bsc_xferโ I2C/SPI as slave transferbsc_i2cโ I2C as slave transfer
๐ก SERIAL ๐ก
serial_openโ Opens a serial deviceserial_closeโ Closes a serial deviceserial_read_byteโ Reads a byte from a serial deviceserial_write_byteโ Writes a byte to a serial deviceserial_readโ Reads bytes from a serial deviceserial_writeโ Writes bytes to a serial deviceserial_data_availableโ Returns number of bytes ready to be read
๐งต SERIAL BIT BANG (read only) ๐งต
bb_serial_read_openโ Opens a GPIO for bit bang serial readsbb_serial_read_closeโ Closes a GPIO for bit bang serial readsbb_serial_invertโ Invert serial logic (1 invert, 0 normal)bb_serial_readโ Reads bit bang serial data from a GPIO
๐ SPI ๐
spi_openโ Opens a SPI devicespi_closeโ Closes a SPI devicespi_readโ Reads bytes from a SPI devicespi_writeโ Writes bytes to a SPI devicespi_xferโ Transfers bytes with a SPI device
๐ฆ SPI BIT BANG ๐ฆ
bb_spi_openโ Opens GPIO for bit banging SPIbb_spi_closeโ Closes GPIO for bit banging SPIbb_spi_xferโ Transfers bytes with bit banging SPI
๐ FILES ๐
file_openโ Opens a filefile_closeโ Closes a filefile_readโ Reads bytes from a filefile_writeโ Writes bytes to a filefile_seekโ Seeks to a position within a filefile_listโ List files which match a pattern
๐ WAVES ๐
wave_clearโ Deletes all waveformswave_add_newโ Starts a new waveformwave_add_genericโ Adds a series of pulses to the waveformwave_add_serialโ Adds serial data to the waveformwave_createโ Creates a waveform from added datawave_create_and_padโ Creates a waveform of fixed size from added datawave_deleteโ Deletes one or more waveformswave_send_onceโ Transmits a waveform oncewave_send_repeatโ Transmits a waveform repeatedlywave_send_using_modeโ Transmits a waveform in the chosen modewave_chainโ Transmits a chain of waveformswave_tx_atโ Returns the current transmitting waveformwave_tx_busyโ Checks to see if the waveform has endedwave_tx_stopโ Aborts the current waveformwave_get_cbsโ Length in cbs of the current waveformwave_get_high_cbsโ Length of longest waveform so farwave_get_max_cbsโ Absolute maximum allowed cbswave_get_microsโ Length in micros of the current waveformwave_get_high_microsโ Length of longest waveform so farwave_get_max_microsโ Absolute maximum allowed microswave_get_pulsesโ Length in pulses of the current waveformwave_get_high_pulsesโ Length of longest waveform so farwave_get_max_pulsesโ Absolute maximum allowed pulses
๐ ๏ธ UTILITIES ๐ ๏ธ
get_current_tickโ Get current tick (microseconds)get_hardware_revisionโ Get hardware revisionget_pigpio_versionโ Get the pigpio versionpigpiod_if_versionโ Get the pigpiod_if2 versionpigpio_errorโ Get a text description of an error code.time_sleepโ Sleeps for a float number of secondstime_timeโ Float number of seconds since the epoch
๐ฅ FUNCTIONS ๐ฅ
double time_time(void)
Return the current time in seconds since the Epoch.
void time_sleep(double seconds)
Delay execution for a given number of seconds.
- seconds: the number of seconds to delay.
char *pigpio_error(int errnum)
Return a text description for an error code.
- errnum: the error code.
unsigned pigpiod_if_version(void)
Return the pigpiod_if2 version.
pthread_t *start_thread(gpioThreadFunc_t thread_func, void *userdata)
Starts a new thread of execution with thread_func as the main routine.
- thread_func: the main function for the new thread.
- userdata: a pointer to an arbitrary argument.
Returns a pointer to pthread_t if OK, otherwise NULL.
The function is passed the single argument userdata.
The thread can be cancelled by passing the pointer to pthread_t to stop_thread.
void stop_thread(pthread_t *pth)
Cancels the thread pointed at by pth.
- pth: the thread to be stopped.
No value is returned.
The thread to be stopped should have been started with start_thread.
int pigpio_start(char *addrStr, char *portStr)
Connect to the pigpio daemon. Reserving command and notification streams.
So addrStr is like the host or IP address of the Pi that's running the pigpio daemon. It can be NULL, and if it is, localhost is used unless the PIGPIO_ADDR environment variable overrides it. ๐
Then portStr is the port address used by the Pi running the pigpio daemon. It can be NULL, and then "8888" is used unless the PIGPIO_PORT environment variable overrides it. โจ
Returns an integer value greater than or equal to zero if OK. ๐ซถ
This value is passed to the GPIO routines to specify the Pi to be operated on. periodt
void pigpio_stop(int pi) ๐
Terminates the connection to a pigpio daemon and releases resources used by the library. bye bestie
pi: >=0 (as returned bypigpio_start).
int set_mode(int pi, unsigned gpio, unsigned mode) ๐๏ธ
Set the GPIO mode.
pi: >=0 (as returned bypigpio_start).gpio: 0-53.mode:PI_INPUT,PI_OUTPUT,PI_ALT0,PI_ALT1,PI_ALT2,PI_ALT3,PI_ALT4,PI_ALT5.
Returns 0 if OK, otherwise PI_BAD_GPIO, PI_BAD_MODE, or PI_NOT_PERMITTED. ๐ญ
int get_mode(int pi, unsigned gpio) ๐
Get the GPIO mode.
pi: >=0 (as returned bypigpio_start).gpio: 0-53.
Returns the GPIO mode if OK, otherwise PI_BAD_GPIO. slay
int set_pull_up_down(int pi, unsigned gpio, unsigned pud) โฌ๏ธโฌ๏ธ
Set or clear the GPIO pull-up/down resistor.
pi: >=0 (as returned bypigpio_start).gpio: 0-53.pud:PI_PUD_UP,PI_PUD_DOWN,PI_PUD_OFF.
Returns 0 if OK, otherwise PI_BAD_GPIO, PI_BAD_PUD, or PI_NOT_PERMITTED. ๐
int gpio_read(int pi, unsigned gpio) ๐
Read the GPIO level.
pi: >=0 (as returned bypigpio_start).gpio: 0-53.
Returns the GPIO level if OK, otherwise PI_BAD_GPIO. vibe check
int gpio_write(int pi, unsigned gpio, unsigned level) โ๏ธ
Write the GPIO level.
pi: >=0 (as returned bypigpio_start).gpio: 0-53.level: 0, 1.
Returns 0 if OK, otherwise PI_BAD_GPIO, PI_BAD_LEVEL, or PI_NOT_PERMITTED. ๐ฅ
Notes: If PWM or servo pulses are active on the GPIO they are switched off. no cap
int set_PWM_dutycycle(int pi, unsigned user_gpio, unsigned dutycycle) ๐
Start (non-zero dutycycle) or stop (0) PWM pulses on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.dutycycle: 0-range (range defaults to 255).
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_DUTYCYCLE, or PI_NOT_PERMITTED.
Notes: The set_PWM_range function may be used to change the default range of 255. ๐
int get_PWM_dutycycle(int pi, unsigned user_gpio) ๐
Return the PWM dutycycle in use on a GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO or PI_NOT_PWM_GPIO. ๐ญ
For normal PWM the dutycycle will be out of the defined range for the GPIO (see get_PWM_range). iykyk
If a hardware clock is active on the GPIO the reported dutycycle will be 500000 (500k) out of 1000000 (1M). โฐ
If hardware PWM is active on the GPIO the reported dutycycle will be out of a 1000000 (1M). ๐
int set_PWM_range(int pi, unsigned user_gpio, unsigned range) ๐
Set the range of PWM values to be used on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.range: 25-40000.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_DUTYRANGE, or PI_NOT_PERMITTED. โจ
Notes: If PWM is currently active on the GPIO its dutycycle will be scaled to reflect the new range. the way that works
The real range, the number of steps between fully off and fully on for each of the 18 available GPIO frequencies is:
25(#1), 50(#2), 100(#3), 125(#4), 200(#5), 250(#6),
400(#7), 500(#8), 625(#9), 800(#10), 1000(#11), 1250(#12),
2000(#13), 2500(#14), 4000(#15), 5000(#16), 10000(#17), 20000(#18)
The real value set by set_PWM_range is (dutycycle * real range) / range. ๐งฎ
int get_PWM_range(int pi, unsigned user_gpio) ๐
Get the range of PWM values being used on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.
Returns the dutycycle range used for the GPIO if OK, otherwise PI_BAD_USER_GPIO. ๐ธ
If a hardware clock or hardware PWM is active on the GPIO the reported range will be 1000000 (1M). ๐
int get_PWM_real_range(int pi, unsigned user_gpio) ๐
Get the real underlying range of PWM values being used on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.
Returns the real range used for the GPIO if OK, otherwise PI_BAD_USER_GPIO. ๐ฆ
If a hardware clock is active on the GPIO the reported real range will be 1000000 (1M). โฐ
If hardware PWM is active on the GPIO the reported real range will be approximately 250M divided by the set PWM frequency. ๐ฅ
int set_PWM_frequency(int pi, unsigned user_gpio, unsigned frequency) ๐ต
Set the frequency (in Hz) of the PWM to be used on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.frequency: >=0 (Hz).
Returns the numerically closest frequency if OK, otherwise PI_BAD_USER_GPIO or PI_NOT_PERMITTED. โจ
If PWM is currently active on the GPIO it will be switched off and then back on at the new frequency. glow up
Each GPIO can be independently set to one of 18 different PWM frequencies. ๐
The selectable frequencies depend upon the sample rate which may be 1, 2, 4, 5, 8, or 10 microseconds (default 5). The sample rate is set when the pigpio daemon is started. โฑ๏ธ
The frequencies for each sample rate are:
Hertz
1: 40000 20000 10000 8000 5000 4000 2500 2000 1600
1250 1000 800 500 400 250 200 100 50
2: 20000 10000 5000 4000 2500 2000 1250 1000 800
625 500 400 250 200 125 100 50 25
4: 10000 5000 2500 2000 1250 1000 625 500 400
313 250 200 125 100 63 50 25 13
sample
rate
(us) 5: 8000 4000 2000 1600 1000 800 500 400 320
250 200 160 100 80 50 40 20 10
8: 5000 2500 1250 1000 625 500 313 250 200
156 125 100 63 50 31 25 13 6
10: 4000 2000 1000 800 500 400 250 200 160
125 100 80 50 40 25 20 10 5
int get_PWM_frequency(int pi, unsigned user_gpio) ๐ถ
Get the frequency of PWM being used on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.
For normal PWM the frequency will be that defined for the GPIO by set_PWM_frequency. ๐ฏ
If a hardware clock is active on the GPIO the reported frequency will be that set by hardware_clock. โฐ
If hardware PWM is active on the GPIO the reported frequency will be that set by hardware_PWM. ๐
Returns the frequency (in hertz) used for the GPIO if OK, otherwise PI_BAD_USER_GPIO. ๐
int set_servo_pulsewidth(int pi, unsigned user_gpio, unsigned pulsewidth) ๐
Start (500-2500) or stop (0) servo pulses on the GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.pulsewidth: 0 (off), 500 (anti-clockwise) - 2500 (clockwise).
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_PULSEWIDTH or PI_NOT_PERMITTED. ๐ญ
The selected pulsewidth will continue to be transmitted until changed by a subsequent call to set_servo_pulsewidth. ๐
The pulsewidths supported by servos varies and should probably be determined by experiment. A value of 1500 should always be safe and represents the mid-point of rotation. ๐ฏ
You can DAMAGE a servo if you command it to move beyond its limits. fr fr, be careful bestie ๐
OTHER UPDATE RATES:
This function updates servos at 50Hz. If you wish to use a different update frequency you will have to use the PWM functions. ๐ ๏ธ
Update Rate (Hz) 50 100 200 400 500
1E6/Hz 20000 10000 5000 2500 2000
Firstly set the desired PWM frequency using set_PWM_frequency. ๐๏ธ
Then set the PWM range using set_PWM_range to 1E6/Hz. Doing this allows you to use units of microseconds when setting the servo pulsewidth. โฑ๏ธ
E.g. If you want to update a servo connected to GPIO 25 at 400Hz
set_PWM_frequency(25, 400);
set_PWM_range(25, 2500);
Thereafter use the set_PWM_dutycycle function to move the servo, e.g. set_PWM_dutycycle(25, 1500) will set a 1500 us pulse. ๐ฆ
int get_servo_pulsewidth(int pi, unsigned user_gpio) ๐
Return the servo pulsewidth in use on a GPIO.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO or PI_NOT_SERVO_GPIO. ๐ธ
int notify_open(int pi) ๐
Get a free notification handle.
pi: >=0 (as returned bypigpio_start).
Returns a handle greater than or equal to zero if OK, otherwise PI_NO_HANDLE. โจ
A notification is a method for being notified of GPIO state changes via a pipe. ๐ฐ
Pipes are only accessible from the local machine so this function serves no purpose if you are using the library from a remote machine. The in-built (socket) notifications provided by callback should be used instead. iykyk
Notifications for handle x will be available at the pipe named /dev/pigpiox (where x is the handle number). E.g. if the function returns 15 then the notifications must be read from /dev/pigpio15. ๐
int notify_begin(int pi, unsigned handle, uint32_t bits) ๐
Start notifications on a previously opened handle.
pi: >=0 (as returned bypigpio_start).handle: 0-31 (as returned bynotify_open).bits: a mask indicating the GPIO to be notified.
Returns 0 if OK, otherwise PI_BAD_HANDLE. ๐ญ
The notification sends state changes for each GPIO whose corresponding bit in bits is set. ๐ฏ
Each notification occupies 12 bytes in the fifo as follows:
typedef struct
{
uint16_t seqno;
uint16_t flags;
uint32_t tick;
uint32_t level;
} gpioReport_t;
seqno: starts at 0 each time the handle is opened and then increments by one for each report. ๐ข
flags: three flags are defined, PI_NTFY_FLAGS_WDOG, PI_NTFY_FLAGS_ALIVE, and PI_NTFY_FLAGS_EVENT. ๐ฉ
If bit 5 is set (PI_NTFY_FLAGS_WDOG) then bits 0-4 of the flags indicate a GPIO which has had a watchdog timeout. โฐ
Okay so if bit 6 is set (PI_NTFY_FLAGS_ALIVE), that's a keep-alive signal on the pipe/socket โ it gets sent once a minute when nothing else is happening. ๐
If bit 7 is set (PI_NTFY_FLAGS_EVENT), then bits 0-4 of the flags tell you which event got triggered. ๐
tick: the number of microseconds since system boot. It wraps around after 1h12m. โณ
level: shows the level of each GPIO. If bit 1<<x is set, then GPIO x is high. ๐ฅ
int notify_pause(int pi, unsigned handle)
Pauses notifications on a previously opened handle. ๐
pi: >=0 (as returned bypigpio_start).handle: 0-31 (as returned bynotify_open)
Returns 0 if OK, otherwise PI_BAD_HANDLE.
Notifications for the handle are suspended until notify_begin is called again. ๐ค
int notify_close(int pi, unsigned handle)
Stops notifications on a previously opened handle and releases the handle for reuse. โป๏ธ
pi: >=0 (as returned bypigpio_start).handle: 0-31 (as returned bynotify_open)
Returns 0 if OK, otherwise PI_BAD_HANDLE.
int set_watchdog(int pi, unsigned user_gpio, unsigned timeout)
Sets a watchdog for a GPIO. ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.timeout: 0-60000.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO or PI_BAD_WDOG_TIMEOUT.
The watchdog is nominally in milliseconds. โฑ๏ธ
Only one watchdog may be registered per GPIO. ๐ซ
The watchdog may be cancelled by setting timeout to 0. โ
Once a watchdog has been started, callbacks for the GPIO will be triggered every timeout interval after the last GPIO activity. ๐
The callback will receive the special level PI_TIMEOUT. ๐
int set_glitch_filter(int pi, unsigned user_gpio, unsigned steady)
Sets a glitch filter on a GPIO. โจ
Level changes on the GPIO are not reported unless the level has been stable for at least steady microseconds. The level is then reported. Level changes of less than steady microseconds are ignored. ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31steady: 0-300000
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_BAD_FILTER.
This filter affects the GPIO samples returned to callbacks set up with callback, callback_ex and wait_for_edge. ๐ฏ
It does not affect levels read by gpio_read, read_bank_1, or read_bank_2. ๐ซ
Each (stable) edge will be timestamped steady microseconds after it was first detected. โฒ๏ธ
int set_noise_filter(int pi, unsigned user_gpio, unsigned steady,
unsigned active)
Sets a noise filter on a GPIO. ๐
Level changes on the GPIO are ignored until a level which has been stable for steady microseconds is detected. Level changes on the GPIO are then reported for active microseconds after which the process repeats. ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31steady: 0-300000active: 0-1000000
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_BAD_FILTER.
This filter affects the GPIO samples returned to callbacks set up with callback, callback_ex and wait_for_edge. ๐ฏ
It does not affect levels read by gpio_read, read_bank_1, or read_bank_2. ๐ซ
Level changes before and after the active period may be reported. Your software must be designed to cope with such reports. ๐ฌ
uint32_t read_bank_1(int pi)
Read the levels of the bank 1 GPIO (GPIO 0-31). ๐
pi: >=0 (as returned by pigpio_start).
The returned 32 bit integer has a bit set if the corresponding GPIO is logic 1. GPIO n has bit value (1<<n). ๐ข
uint32_t read_bank_2(int pi)
Read the levels of the bank 2 GPIO (GPIO 32-53). ๐
pi: >=0 (as returned by pigpio_start).
The returned 32 bit integer has a bit set if the corresponding GPIO is logic 1. GPIO n has bit value (1<<(n-32)). ๐ข
int clear_bank_1(int pi, uint32_t bits)
Clears GPIO 0-31 if the corresponding bit in bits is set. ๐งน
pi: >=0 (as returned bypigpio_start).bits: a bit mask with 1 set if the corresponding GPIO is to be cleared.
Returns 0 if OK, otherwise PI_SOME_PERMITTED.
A status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the GPIO. ๐ซ
int clear_bank_2(int pi, uint32_t bits)
Clears GPIO 32-53 if the corresponding bit (0-21) in bits is set. ๐งน
pi: >=0 (as returned bypigpio_start).bits: a bit mask with 1 set if the corresponding GPIO is to be cleared.
Returns 0 if OK, otherwise PI_SOME_PERMITTED.
A status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the GPIO. ๐ซ
int set_bank_1(int pi, uint32_t bits)
Sets GPIO 0-31 if the corresponding bit in bits is set. ๐ก
pi: >=0 (as returned bypigpio_start).bits: a bit mask with 1 set if the corresponding GPIO is to be set.
Returns 0 if OK, otherwise PI_SOME_PERMITTED.
A status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the GPIO. ๐ซ
int set_bank_2(int pi, uint32_t bits)
Sets GPIO 32-53 if the corresponding bit (0-21) in bits is set. ๐ก
pi: >=0 (as returned bypigpio_start).bits: a bit mask with 1 set if the corresponding GPIO is to be set.
Returns 0 if OK, otherwise PI_SOME_PERMITTED.
A status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the GPIO. ๐ซ
int hardware_clock(int pi, unsigned gpio, unsigned clkfreq)
Starts a hardware clock on a GPIO at the specified frequency. Frequencies above 30MHz are unlikely to work. โฐ
pi: >=0 (as returned bypigpio_start).gpio: see descriptionfrequency: 0 (off) or 4689-250M (13184-375M for the BCM2711)
Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO, PI_NOT_HCLK_GPIO, PI_BAD_HCLK_FREQ, or PI_BAD_HCLK_PASS.
The same clock is available on multiple GPIO. The latest frequency setting will be used by all GPIO which share a clock. ๐
The GPIO must be one of the following. ๐
4clock 0 All models5clock 1 All models but A and B (reserved for system use)6clock 2 All models but A and B20clock 0 All models but A and B21clock 1 All models but A and Rev.2 B (reserved for system use)32clock 0 Compute module only34clock 0 Compute module only42clock 1 Compute module only (reserved for system use)43clock 2 Compute module only44clock 1 Compute module only (reserved for system use)
Access to clock 1 is protected by a password as its use will likely crash the Pi. The password is given by or'ing 0x5A000000 with the GPIO number. ๐
int hardware_PWM(int pi, unsigned gpio, unsigned PWMfreq, uint32_t
PWMduty)
Starts hardware PWM on a GPIO at the specified frequency and dutycycle. Frequencies above 30MHz are unlikely to work. โก
NOTE: Any waveform started bywave_send_*orwave_chainwill be cancelled. ๐ซ
This function is only valid if the pigpio main clock is PCM. The main clock defaults to PCM but may be overridden when the pigpio daemon is started (option -t). โ๏ธ
pi: >=0 (as returned bypigpio_start).gpio: see descriptonPWMfreq: 0 (off) or 1-125M (1-187.5M for the BCM2711)PWMduty: 0 (off) to 1000000 (1M)(fully on)
Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO, PI_NOT_HPWM_GPIO, PI_BAD_HPWM_DUTY, PI_BAD_HPWM_FREQ, or PI_HPWM_ILLEGAL.
The same PWM channel is available on multiple GPIO. The latest frequency and dutycycle setting will be used by all GPIO which share a PWM channel. ๐
The GPIO must be one of the following. ๐
12PWM channel 0 All models but A and B13PWM channel 1 All models but A and B18PWM channel 0 All models19PWM channel 1 All models but A and B40PWM channel 0 Compute module only41PWM channel 1 Compute module only45PWM channel 1 Compute module only52PWM channel 0 Compute module only53PWM channel 1 Compute module only
The actual number of steps between off and fully on is the integral part of 250M/PWMfreq (375M/PWMfreq for the BCM2711). ๐
The actual frequency set is 250M/steps (375M/steps for the BCM2711). ๐
There will only be a million steps for a PWMfreq of 250 (375 for the BCM2711). Lower frequencies will have more steps and higher frequencies will have fewer steps. PWMduty is automatically scaled to take this into account. ๐ข
uint32_t get_current_tick(int pi)
Gets the current system tick. โฑ๏ธ
pi: >=0 (as returned by pigpio_start).
Tick is the number of microseconds since system boot. โณ
As tick is an unsigned 32 bit quantity it wraps around after 2**32 microseconds, which is approximately 1 hour 12 minutes. ๐
uint32_t get_hardware_revision(int pi)
Get the Pi's hardware revision number. ๐
pi: >=0 (as returned by pigpio_start).
The hardware revision is the last few characters on the Revision line of /proc/cpuinfo. ๐
If the hardware revision can not be found or is not a valid hexadecimal number the function returns 0. โ
The revision number can be used to determine the assignment of GPIO to pins (see gpio). ๐
There are at least three types of board. ๐งฉ
Type 1 boards have hardware revision numbers of 2 and 3. ๐ฅ
Type 2 boards have hardware revision numbers of 4, 5, 6, and 15. ๐ฅ
Type 3 boards have hardware revision numbers of 16 or greater. ๐ฅ
uint32_t get_pigpio_version(int pi)
Returns the pigpio version. ๐ท๏ธ
pi: >=0 (as returned by pigpio_start).
int wave_clear(int pi)
This function clears all waveforms and any data added by calls to the wave_add_* functions. ๐งน
pi: >=0 (as returned by pigpio_start).
Returns 0 if OK.
int wave_add_new(int pi)
This function starts a new empty waveform. You wouldn't normally need to call this function as it is automatically called after a waveform is created with the wave_create function. โจ
pi: >=0 (as returned by pigpio_start).
Returns 0 if OK.
int wave_add_generic(int pi, unsigned numPulses, gpioPulse_t *pulses)
This function adds a number of pulses to the current waveform. ๐
pi: >=0 (as returned bypigpio_start).numPulses: the number of pulses.pulses: an array of pulses.
Returns the new total number of pulses in the current waveform if OK, otherwise PI_TOO_MANY_PULSES.
The pulses get interleaved in time order inside whatever waveform is already chilling there (if there is one). โณ
Merging is the whole point bestie โ it lets you build one waveform in pieces. Add the settings for GPIO#1, then GPIO#2, etc. Little by little. โจ
If the waveform you're adding is meant to start after or within the existing waveform, then the first pulse should be a delay and literally nothing else. No GPIO action, just vibes and waiting. ๐
int wave_add_serial(int pi, unsigned user_gpio, unsigned baud, unsigned data_bits, unsigned stop_bits, unsigned offset, unsigned numBytes, char *str)
This one adds a waveform representing serial data to the existing waveform (if any). The serial data starts offset microseconds from the start of the waveform. ๐
pi:>=0(as returned bypigpio_start).user_gpio:0-31.baud:50-1000000data_bits: number of data bits (1-32)stop_bits: number of stop half bits (2-8)offset:>=0numBytes:>=1str: an array of chars.
Returns the new total number of pulses in the current waveform if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_WAVE_BAUD, PI_BAD_DATABITS, PI_BAD_STOP_BITS, PI_TOO_MANY_CHARS, PI_BAD_SER_OFFSET, or PI_TOO_MANY_PULSES.
NOTES:
The serial data is formatted as one start bit, data_bits data bits, and stop_bits/2 stop bits. That's the shape of it, no cap. ๐ก
It is legal to add serial data streams with different baud rates to the same waveform. Go off, mix those bauds. ๐ฅ
numBytes is the number of bytes of data in str.
The bytes required for each character depend upon data_bits.
- For
data_bits1-8there will be one byte per character. - For
data_bits9-16there will be two bytes per character. - For
data_bits17-32there will be four bytes per character.
int wave_create(int pi)
This function creates a waveform from the data provided by the prior calls to the wave_add_* functions. Upon success a wave id greater than or equal to 0 is returned, otherwise PI_EMPTY_WAVEFORM, PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID. ๐
pi: >=0 (as returned by pigpio_start).
The data provided by the wave_add_* functions is consumed by this function. It's gone, bestie, it got ate. ๐ญ
As many waveforms may be created as there is space available. The wave id is passed to wave_send_* to specify the waveform to transmit.
Normal usage would be:
- Step 1.
wave_clearto clear all waveforms and added data. - Step 2.
wave_add_*calls to supply the waveform data. - Step 3.
wave_createto create the waveform and get a unique id
Repeat steps 2 and 3 as needed.
- Step 4.
wave_send_*with the id of the waveform to transmit.
A waveform comprises one or more pulses. Each pulse consists of a gpioPulse_t structure.
typedef struct
{
uint32_t gpioOn;
uint32_t gpioOff;
uint32_t usDelay;
} gpioPulse_t;
The fields specify:
- the GPIO to be switched on at the start of the pulse.
- the GPIO to be switched off at the start of the pulse.
- the delay in microseconds before the next pulse.
Any or all the fields can be zero. It doesn't make any sense to set all the fields to zero (the pulse will be ignored). Like, why would you. ๐
When a waveform is started each pulse is executed in order with the specified delay between the pulse and the next.
Returns the new waveform id if OK, otherwise PI_EMPTY_WAVEFORM, PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL.
int wave_create_and_pad(int pi, int percent)
This function creates a waveform like wave_create but pads the consumed resources. Where percent gives the percentage of the resources to use (in terms of the theoretical maximum, not the current amount free). This allows the reuse of deleted waves while a transmission is active. Iconic behaviour, honestly. โจ
pi:>=0(as returned bypigpio_start).percent:0-100, size of waveform as percentage of maximum available.
The data provided by the wave_add_* functions are consumed by this function.
As many waveforms may be created as there is space available. The wave id is passed to wave_send_* to specify the waveform to transmit.
A usage would be the creation of two waves where one is filled while the other is being transmitted. Each wave is assigned 50% of the resources. This buffer structure allows the transmission of infinite wave sequences. ๐ซ
Normal usage:
- Step 1.
wave_clearto clear all waveforms and added data. - Step 2.
wave_add_*calls to supply the waveform data. - Step 3.
wave_create_and_padto create a waveform of uniform size. - Step 4.
wave_send_*with the id of the waveform to transmit.
Repeat steps 2-4 as needed.
- Step 5. Any wave id can now be deleted and another wave of the same size can be created in its place.
Returns the new waveform id if OK, otherwise PI_EMPTY_WAVEFORM, PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL.
int wave_delete(int pi, unsigned wave_id)
This function deletes the waveform with id wave_id. Bye bestie, you won't be missed. ๐ฆ
pi:>=0(as returned bypigpio_start).wave_id:>=0, as returned bywave_create.
Wave ids are allocated in order, 0, 1, 2, etc.
The wave is flagged for deletion. The resources used by the wave will only be reused when either of the following apply.
- all waves with higher numbered wave ids have been deleted or have been flagged for deletion.
- a new wave is created which uses exactly the same resources as the current wave (see the C source for
gpioWaveCreatefor details).
Returns 0 if OK, otherwise PI_BAD_WAVE_ID.
int wave_send_once(int pi, unsigned wave_id)
This function transmits the waveform with id wave_id. The waveform is sent once. One and done, periodt. ๐
NOTE: Any hardware PWM started by hardware_PWM will be cancelled. Yes, it's giving cancelled. ๐
pi:>=0(as returned bypigpio_start).wave_id:>=0, as returned bywave_create.
Returns the number of DMA control blocks in the waveform if OK, otherwise PI_BAD_WAVE_ID, or PI_BAD_WAVE_MODE.
int wave_send_repeat(int pi, unsigned wave_id)
This function transmits the waveform with id wave_id. The waveform cycles until cancelled (either by the sending of a new waveform or by wave_tx_stop). Round and round and round, main character energy. ๐
NOTE: Any hardware PWM started by hardware_PWM will be cancelled.
pi:>=0(as returned bypigpio_start).wave_id:>=0, as returned bywave_create.
Returns the number of DMA control blocks in the waveform if OK, otherwise PI_BAD_WAVE_ID, or PI_BAD_WAVE_MODE.
int wave_send_using_mode(int pi, unsigned wave_id, unsigned mode)
Transmits the waveform with id wave_id using mode mode.
pi:>=0(as returned bypigpio_start).wave_id:>=0, as returned bywave_create.mode:PI_WAVE_MODE_ONE_SHOT,PI_WAVE_MODE_REPEAT,PI_WAVE_MODE_ONE_SHOT_SYNC, orPI_WAVE_MODE_REPEAT_SYNC.PI_WAVE_MODE_ONE_SHOT: same aswave_send_once.PI_WAVE_MODE_REPEATsame aswave_send_repeat.PI_WAVE_MODE_ONE_SHOT_SYNCsame aswave_send_oncebut tries to sync with the previous waveform.PI_WAVE_MODE_REPEAT_SYNCsame aswave_send_repeatbut tries to sync with the previous waveform.
WARNING: bad things may happen if you delete the previous waveform before it has been synced to the new waveform. Like, actually bad things. Do not. ๐ญ
NOTE: Any hardware PWM started by hardware_PWM will be cancelled.
Returns the number of DMA control blocks in the waveform if OK, otherwise PI_BAD_WAVE_ID, or PI_BAD_WAVE_MODE.
int wave_chain(int pi, char *buf, unsigned bufSize)
This function transmits a chain of waveforms. It's a whole playlist, fr fr. ๐ถ
NOTE: Any hardware PWM started by hardware_PWM will be cancelled.
The waves to be transmitted are specified by the contents of buf which contains an ordered list of wave_ids and optional command codes and related data.
pi:>=0(as returned bypigpio_start).buf: pointer to thewave_idsand optional command codesbufSize: the number of bytes inbuf
Returns 0 if OK, otherwise PI_CHAIN_NESTING, PI_CHAIN_LOOP_CNT, PI_BAD_CHAIN_LOOP, PI_BAD_CHAIN_CMD, PI_CHAIN_COUNTER, PI_BAD_CHAIN_DELAY, PI_CHAIN_TOO_BIG, or PI_BAD_WAVE_ID.
Each wave is transmitted in the order specified. A wave may occur multiple times per chain.
A blocks of waves may be transmitted multiple times by using the loop commands. The block is bracketed by loop start and end commands. Loops may be nested. Loops within loops within loops, inception vibes. ๐ธ
Delays between waves may be added with the delay command.
The following command codes are supported:
- Loop Start โ Cmd & Data
255 0โ identify start of a wave block - Loop Repeat โ Cmd & Data
255 1 x yโ loopx + y*256times - Delay โ Cmd & Data
255 2 x yโ delayx + y*256microseconds - Loop Forever โ Cmd & Data
255 3โ loop forever
If present Loop Forever must be the last entry in the chain.
The code is currently dimensioned to support a chain with roughly 600 entries and 20 loop counters.
Example
#include <stdio.h>
#include <pigpiod_if2.h>
#define WAVES 5
#define GPIO 4
int main(int argc, char *argv[])
{
int i, pi, wid[WAVES];
pi = pigpio_start(0, 0);
if (pi<0) return -1;
set_mode(pi, GPIO, PI_OUTPUT);
for (i=0; i<WAVES; i++)
{
wave_add_generic(pi, 2, (gpioPulse_t[])
{{1<<GPIO, 0, 20},
{0, 1<<GPIO, (i+1)*200}});
wid[i] = wave_create(pi);
}
wave_chain(pi, (char []) {
wid[4], wid[3], wid[2], // transmit waves 4+3+2
255, 0, // loop start
wid[0], wid[0], wid[0], // transmit waves 0+0+0
255, 0, // loop start
wid[0], wid[1], // transmit waves 0+1
255, 2, 0x88, 0x13, // delay 5000us
255, 1, 30, 0, // loop end (repeat 30 times)
255, 0, // loop start
wid[2], wid[3], wid[0], // transmit waves 2+3+0
wid[3], wid[1], wid[2], // transmit waves 3+1+2
255, 1, 10, 0, // loop end (repeat 10 times)
255, 1, 5, 0, // loop end (repeat 5 times)
wid[4], wid[4], wid[4], // transmit waves 4+4+4
255, 2, 0x20, 0x4E, // delay 20000us
wid[0], wid[0], wid[0], // transmit waves 0+0+0
}, 46);
while (wave_tx_busy(pi)) time_sleep(0.1);
for (i=0; i<WAVES; i++) wave_delete(pi, wid[i]);
pigpio_stop(pi);
}
int wave_tx_at(int pi)
Bestie, this one tells you the id of the waveform that's currently being transmitted by wave_send*. Chained waves are not supported. So if you're chaining, this is not the vibe check for you, sorry babe ๐
pi: >=0 (as returned bypigpio_start).
It returns the waveform id, or one of these special little guys:
PI_WAVE_NOT_FOUND(9998) โ transmitted wave not found.PI_NO_TX_WAVE(9999) โ no wave being transmitted.
int wave_tx_busy(int pi)
Checks whether a waveform is currently being transmitted. Are we busy or are we โจfreeโจ?
pi: >=0 (as returned bypigpio_start).
Returns 1 if a waveform is currently being transmitted, otherwise 0.
int wave_tx_stop(int pi)
Stops the transmission of the current waveform. Say it with me: stop, bestie. ๐
pi: >=0 (as returned bypigpio_start).
Returns 0 if OK.
This function is intended to stop a waveform started with the repeat mode. iykyk ๐
int wave_get_micros(int pi)
Returns the length in microseconds of the current waveform.
pi: >=0 (as returned bypigpio_start).
int wave_get_high_micros(int pi)
Returns the length in microseconds of the longest waveform created since the pigpio daemon was started. Hall of fame energy ๐
pi: >=0 (as returned bypigpio_start).
int wave_get_max_micros(int pi)
Returns the maximum possible size of a waveform in microseconds. This is the ceiling, the limit, the no-more-than-this ๐
pi: >=0 (as returned bypigpio_start).
int wave_get_pulses(int pi)
Returns the length in pulses of the current waveform.
pi: >=0 (as returned bypigpio_start).
int wave_get_high_pulses(int pi)
Returns the length in pulses of the longest waveform created since the pigpio daemon was started.
pi: >=0 (as returned bypigpio_start).
int wave_get_max_pulses(int pi)
Returns the maximum possible size of a waveform in pulses.
pi: >=0 (as returned bypigpio_start).
int wave_get_cbs(int pi)
Returns the length in DMA control blocks of the current waveform.
pi: >=0 (as returned bypigpio_start).
int wave_get_high_cbs(int pi)
Returns the length in DMA control blocks of the longest waveform created since the pigpio daemon was started.
pi: >=0 (as returned bypigpio_start).
int wave_get_max_cbs(int pi)
Returns the maximum possible size of a waveform in DMA control blocks.
pi: >=0 (as returned bypigpio_start).
int gpio_trigger(int pi, unsigned user_gpio, unsigned pulseLen, unsigned level)
Sends a trigger pulse to a GPIO ๐ฏ The GPIO is set to level for pulseLen microseconds and then reset to not level.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.pulseLen: 1-100.level: 0,1.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_LEVEL, PI_BAD_PULSELEN, or PI_NOT_PERMITTED.
int store_script(int pi, char *script)
Stores a script for later execution. Save it for later, bestie ๐พ
See http://abyz.me.uk/rpi/pigpio/pigs.html#Scripts for details.
pi: >=0 (as returned bypigpio_start).script: the text of the script.
The function returns a script id if the script is valid, otherwise PI_BAD_SCRIPT.
int run_script(int pi, unsigned script_id, unsigned numPar, uint32_t *param)
Runs a stored script. Go go go ๐โ๏ธโจ
pi: >=0 (as returned bypigpio_start).script_id: >=0, as returned bystore_script.numPar: 0-10, the number of parameters.param: an array of parameters.
The function returns 0 if OK, otherwise PI_BAD_SCRIPT_ID, or PI_TOO_MANY_PARAM
param is an array of up to 10 parameters which may be referenced in the script as p0 to p9.
int update_script(int pi, unsigned script_id, unsigned numPar, uint32_t *param)
Sets the parameters of a script. The script may or may not be running โ either way, we're updating ๐ซถ The first numPar parameters of the script are overwritten with the new values.
pi: >=0 (as returned bypigpio_start).script_id: >=0, as returned bystore_script.numPar: 0-10, the number of parameters.param: an array of parameters.
The function returns 0 if OK, otherwise PI_BAD_SCRIPT_ID, or PI_TOO_MANY_PARAM.
param is an array of up to 10 parameters which may be referenced in the script as p0 to p9.
int script_status(int pi, unsigned script_id, uint32_t *param)
Returns the run status of a stored script, plus the current values of parameters 0 to 9. It's giving full report card ๐
pi: >=0 (as returned bypigpio_start).script_id: >=0, as returned bystore_script.param: an array to hold the returned 10 parameters.
The function returns greater than or equal to 0 if OK, otherwise PI_BAD_SCRIPT_ID.
The run status may be
PI_SCRIPT_INITINGPI_SCRIPT_HALTEDPI_SCRIPT_RUNNINGPI_SCRIPT_WAITINGPI_SCRIPT_FAILED
The current value of script parameters 0 to 9 are returned in param.
int stop_script(int pi, unsigned script_id)
Stops a running script. โ that's enough, diva.
pi: >=0 (as returned bypigpio_start).script_id: >=0, as returned bystore_script.
The function returns 0 if OK, otherwise PI_BAD_SCRIPT_ID.
int delete_script(int pi, unsigned script_id)
Deletes a stored script. Gone, and honestly? Not missed ๐๏ธ๐
pi: >=0 (as returned bypigpio_start).script_id: >=0, as returned bystore_script.
The function returns 0 if OK, otherwise PI_BAD_SCRIPT_ID.
int bb_serial_read_open(int pi, unsigned user_gpio, unsigned baud, unsigned data_bits)
Opens a GPIO for bit bang reading of serial data. We're doing it the manual way, bestie ๐ง
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.baud: 50-250000data_bits: 1-32
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_WAVE_BAUD, or PI_GPIO_IN_USE.
The serial data is returned in a cyclic buffer and is read using bb_serial_read.
It is the caller's responsibility to read data from the cyclic buffer in a timely fashion. Don't leave it sitting there, okay?? The buffer does not wait for you ๐ญ
int bb_serial_read(int pi, unsigned user_gpio, void *buf, size_t bufSize)
Copies up to bufSize bytes of data read from the bit bang serial cyclic buffer to the buffer starting at buf.
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31, previously opened withbb_serial_read_open.buf: an array to receive the read bytes.bufSize: >=0
Returns the number of bytes copied if OK, otherwise PI_BAD_USER_GPIO or PI_NOT_SERIAL_GPIO.
The bytes returned for each character depend upon the number of data bits data_bits specified in the bb_serial_read_open command.
- For
data_bits1-8 there will be one byte per character. - For
data_bits9-16 there will be two bytes per character. - For
data_bits17-32 there will be four bytes per character.
int bb_serial_read_close(int pi, unsigned user_gpio)
Closes a GPIO for bit bang reading of serial data. Pack it up, we're done here ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31, previously opened withbb_serial_read_open.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_SERIAL_GPIO.
int bb_serial_invert(int pi, unsigned user_gpio, unsigned invert)
Inverts serial logic for big bang serial reads. Flip the whole vibe upside down ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31, previously opened withbb_serial_read_open.invert: 0-1,1invert,0normal.
Returns 0 if OK, otherwise PI_NOT_SERIAL_GPIO or PI_BAD_SER_INVERT.
int i2c_open(int pi, unsigned i2c_bus, unsigned i2c_addr, unsigned i2c_flags)
This returns a handle for the device at address i2c_addr on bus i2c_bus ๐
pi: >=0 (as returned bypigpio_start).i2c_bus: >=0.i2c_addr: 0-0x7F.i2c_flags: 0.
No flags are currently defined. This parameter should be set to zero. Don't be creative here, bestie ๐
Physically buses 0 and 1 are available on the Pi. Higher numbered buses will be available if a kernel supported bus multiplexor is being used.
The GPIO used are given in the following table.
SDA SCL
I2C 0 0 1
I2C 1 2 3
Returns a handle (>=0) if OK, otherwise PI_BAD_I2C_BUS, PI_BAD_I2C_ADDR, PI_BAD_FLAGS, PI_NO_HANDLE, or PI_I2C_OPEN_FAILED.
For the SMBus commands the low level transactions are shown at the end of the function description. The following abbreviations are used.
S(1 bit) : Start bitP(1 bit) : Stop bitRd/Wr(1 bit) : Read/Write bit.Rdequals 1,Wrequals 0.A, NA(1 bit) : Accept and not accept bit.Addr(7 bits): I2C 7 bit address.i2c_reg(8 bits): A byte which often selects a register.Data(8 bits): A data byte.Count(8 bits): A byte defining the length of a block operation.
[..]: Data sent by the device.
int i2c_close(int pi, unsigned handle)
Closes the I2C device associated with the handle. Bye bye, handle ๐ซถ
pi: >=0 (as returned bypigpio_start).handle: >=0, as returned by a call toi2c_open.
Returns 0 if OK, otherwise PI_BAD_HANDLE.
int i2c_write_quick(int pi, unsigned handle, unsigned bit)
Sends a single bit (in the Rd/Wr bit) to the device associated with handle. One single bit, that's the whole entire message โจ
pi: >=0 (as returned bypigpio_start).handle: >=0, as returned by a call toi2c_open.bit: 0-1, the value to write.
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
Quick command. SMBus 2.0 5.5.1
S Addr bit [A] P
int i2c_write_byte(int pi, unsigned handle, unsigned bVal)
Sends a single byte to the device associated with handle.
pi: >=0 (as returned bypigpio_start).handle: >=0, as returned by a call toi2c_open.bVal: 0-0xFF, the value to write.
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
Send byte. SMBus 2.0 5.5.2
S Addr Wr [A] bVal [A] P
int i2c_read_byte(int pi, unsigned handle)
Reads a single byte from the device associated with handle. Gimme one byte, please and thank you ๐
pi: >=0 (as returned bypigpio_start).handle: >=0, as returned by a call toi2c_open.
Returns the byte read (>=0) if OK, otherwise PI_BAD_HANDLE, or PI_I2C_READ_FAILED.
Receive byte. SMBus 2.0 5.5.3
S Addr Rd [A] [Data] NA P
๐ธ i2c_write_byte_data โ drop one lil byte in a register
int i2c_write_byte_data(int pi, unsigned handle, unsigned i2c_reg, unsigned bVal)
okay so this one writes a single byte to the register you pick on the device that handle is pointing at. one byte. that's it. slay.
piโ>=0(the value you got back frompigpio_start)handleโ>=0, the one you got fromi2c_openi2c_regโ0-255, the register you're writing tobValโ0-0xFF, the value you're writing
Returns 0 if it worked, otherwise one of PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
That's a Write byte, SMBus 2.0 5.5.4. on the wire it looks like:
S Addr Wr [A] i2c_reg [A] bVal [A] P
โจ i2c_write_word_data โ same vibe, but 16 bits
int i2c_write_word_data(int pi, unsigned handle, unsigned i2c_reg, unsigned wVal)
writes a single 16 bit word to the register on the device tied to handle.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to writewValโ0-0xFFFF, the value to write
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
Write word, SMBus 2.0 5.5.4:
S Addr Wr [A] i2c_reg [A] wval_Low [A] wVal_High [A] P
๐ฆ i2c_read_byte_data โ gimme one byte back
int i2c_read_byte_data(int pi, unsigned handle, unsigned i2c_reg)
reads a single byte from the register of the device associated with handle. bestie it literally just hands you the byte.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to read
Returns the byte read (>=0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
Read byte, SMBus 2.0 5.5.5:
S Addr Wr [A] i2c_reg [A] S Addr Rd [A] [Data] NA P
๐ i2c_read_word_data โ gimme a whole word back
int i2c_read_word_data(int pi, unsigned handle, unsigned i2c_reg)
reads a single 16 bit word from that register.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to read
Returns the word read (>=0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
Read word, SMBus 2.0 5.5.5:
S Addr Wr [A] i2c_reg [A]
S Addr Rd [A] [DataLow] A [DataHigh] NA P
๐ฅ i2c_process_call โ write a word, get a word back
int i2c_process_call(int pi, unsigned handle, unsigned i2c_reg, unsigned wVal)
this one writes 16 bits of data to the register and and reads 16 bits of data in return. a whole conversation. iconic.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to write/readwValโ0-0xFFFF, the value to write
Returns the word read (>=0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
Process call, SMBus 2.0 5.5.6:
S Addr Wr [A] i2c_reg [A] wVal_Low [A] wVal_High [A]
S Addr Rd [A] [DataLow] A [DataHigh] NA P
๐ i2c_write_block_data โ up to 32 bytes at once
int i2c_write_block_data(int pi, unsigned handle, unsigned i2c_reg, char *buf, unsigned count)
writes up to 32 bytes to the register. glow up for bulk data fr fr.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to writebufโ an array with the data to sendcountโ1-32, the number of bytes to write
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
Block write, SMBus 2.0 5.5.7:
S Addr Wr [A] i2c_reg [A] count [A] buf0 [A] buf1 [A] ...
[A] bufn [A] P
๐ i2c_read_block_data โ read a whole block back
int i2c_read_block_data(int pi, unsigned handle, unsigned i2c_reg, char *buf)
reads a block of up to 32 bytes from the register of the device associated with handle.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to readbufโ an array to receive the read data
The amount of returned data is set by the device. (the device is the main character here, not you ๐ )
Returns the number of bytes read (>=0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
Block read, SMBus 2.0 5.5.7:
S Addr Wr [A] i2c_reg [A]
S Addr Rd [A] [Count] A [buf0] A [buf1] A ... A [bufn] NA P
โญ i2c_block_process_call โ block out, block back
int i2c_block_process_call(int pi, unsigned handle, unsigned i2c_reg, char *buf, unsigned count)
writes data bytes to the register and reads a device specified number of bytes of data in return.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to write/readbufโ an array with the data to send and to receive the read datacountโ1-32, the number of bytes to write
Returns the number of bytes read (>=0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
The smbus 2.0 documentation states that a minimum of 1 byte may be sent and a minimum of 1 byte may be received. The total number of bytes sent/received must be 32 or less.
Block write-block read, SMBus 2.0 5.5.8:
S Addr Wr [A] i2c_reg [A] count [A] buf0 [A] ...
S Addr Rd [A] [Count] A [Data] ... A P
๐ i2c_read_i2c_block_data โ you pick how many bytes
int i2c_read_i2c_block_data(int pi, unsigned handle, unsigned i2c_reg, char *buf, unsigned count)
reads count bytes from the register of the device associated with handle. The count may be 1-32.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to readbufโ an array to receive the read datacountโ1-32, the number of bytes to read
Returns the number of bytes read (>0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
S Addr Wr [A] i2c_reg [A]
S Addr Rd [A] [buf0] A [buf1] A ... A [bufn] NA P
๐ซถ i2c_write_i2c_block_data โ you pick how many bytes to send
int i2c_write_i2c_block_data(int pi, unsigned handle, unsigned i2c_reg, char *buf, unsigned count)
writes 1 to 32 bytes to the register of the device associated with handle.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openi2c_regโ0-255, the register to writebufโ the data to writecountโ1-32, the number of bytes to write
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
S Addr Wr [A] i2c_reg [A] buf0 [A] buf1 [A] ... [A] bufn [A] P
๐ง i2c_read_device โ raw device read, no register shenanigans
int i2c_read_device(int pi, unsigned handle, char *buf, unsigned count)
reads count bytes from the raw device into buf. no register, just vibes.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openbufโ an array to receive the read data bytescountโ>0, the number of bytes to read
Returns count (>0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_READ_FAILED.
S Addr Rd [A] [buf0] A [buf1] A ... A [bufn] NA P
๐ i2c_write_device โ raw device write
int i2c_write_device(int pi, unsigned handle, char *buf, unsigned count)
writes count bytes from buf to the raw device.
piโ>=0(frompigpio_start)handleโ>=0, fromi2c_openbufโ an array containing the data bytes to writecountโ>0, the number of bytes to write
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_I2C_WRITE_FAILED.
S Addr Wr [A] buf0 [A] buf1 [A] ... [A] bufn [A] P
๐ i2c_zip โ the power move, a whole sequence of I2C ops in one call
int i2c_zip(int pi, unsigned handle, char *inBuf, unsigned inLen, char *outBuf, unsigned outLen)
bestie. this function executes a sequence of I2C operations. the operations to be performed are specified by the contents of inBuf, which contains the concatenated command codes and associated data. it's giving scripted choreography.
piโ>=0(frompigpio_start)handleโ>=0, from a call toi2cOpeninBufโ pointer to the concatenated I2C commands, see belowinLenโ size of command bufferoutBufโ pointer to buffer to hold returned dataoutLenโ size of output buffer
Returns >= 0 if OK (the number of bytes read), otherwise PI_BAD_HANDLE, PI_BAD_POINTER, PI_BAD_I2C_CMD, PI_BAD_I2C_RLEN. PI_BAD_I2C_WLEN, or PI_BAD_I2C_SEG.
The following command codes are supported:
Endโ Cmd & Data0โ No more commandsEscapeโ Cmd & Data1โ Next P is two bytesOnโ Cmd & Data2โ Switch combined flag onOffโ Cmd & Data3โ Switch combined flag offAddressโ Cmd & Data4 Pโ Set I2C address to PFlagsโ Cmd & Data5 lsb msbโ Set I2C flags to lsb + (msb << 8)Readโ Cmd & Data6 Pโ Read P bytes of dataWriteโ Cmd & Data7 P ...โ Write P bytes of data
The address, read, and write commands take a parameter P. Normally P is one byte (0-255). If the command is preceded by the Escape command then P is two bytes (0-65535, least significant byte first).
The address defaults to that associated with the handle. The flags default to 0. The address and flags maintain their previous value until updated.
The returned I2C data is stored in consecutive locations of outBuf.
Example
Set address 0x53, write 0x32, read 6 bytes Set address 0x1E, write 0x03, read 6 bytes Set address 0x68, write 0x1B, read 8 bytes End
0x04 0x53 0x07 0x01 0x32 0x06 0x06
0x04 0x1E 0x07 0x01 0x03 0x06 0x06
0x04 0x68 0x07 0x01 0x1B 0x06 0x08
0x00
๐ธ bb_i2c_open โ bit bang I2C on any two GPIO you want
int bb_i2c_open(int pi, unsigned SDA, unsigned SCL, unsigned baud)
this function selects a pair of GPIO for bit banging I2C at a specified baud rate.
Bit banging I2C allows for certain operations which are not possible with the standard I2C driver.
- baud rates as low as 50
- repeated starts
- clock stretching
- I2C on any pair of spare GPIO
piโ>=0(frompigpio_start)SDAโ0-31SCLโ0-31baudโ50-500000
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_I2C_BAUD, or PI_GPIO_IN_USE.
NOTE: The GPIO used for SDA and SCL must have pull-ups to 3V3 connected. As a guide the hardware pull-ups on pins 3 and 5 are 1k8 in value.
โจ bb_i2c_close โ wrap it up
int bb_i2c_close(int pi, unsigned SDA)
this function stops bit banging I2C on a pair of GPIO previously opened with bb_i2c_open.
piโ>=0(frompigpio_start)SDAโ0-31, the SDA GPIO used in a prior call tobb_i2c_open
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_I2C_GPIO.
๐ bb_i2c_zip
int bb_i2c_zip(int pi, unsigned SDA, char *inBuf, unsigned inLen, char *outBuf, unsigned outLen)
This function runs a whole little choreography of bit-banged I2C moves, one after another, no cap. The operations you want it to perform are spelled out by whatever's sitting in inBuf, which is just the concatenated command codes plus their data all smooshed together. ๐ซ
pi:>=0(as returned bypigpio_start).SDA:0-31(as used in a prior call tobb_i2c_open).inBuf: pointer to the concatenated I2C commands, see below.inLen: size of command buffer.outBuf: pointer to buffer to hold returned data.outLen: size of output buffer.
Returns >= 0 if OK (the number of bytes read), otherwise PI_BAD_USER_GPIO, PI_NOT_I2C_GPIO, PI_BAD_POINTER, PI_BAD_I2C_CMD, PI_BAD_I2C_RLEN, PI_BAD_I2C_WLEN, PI_I2C_READ_FAILED, or PI_I2C_WRITE_FAILED.
Here's the command code menu, bestie โ these are the little instructions you can stack up in inBuf:
Endโ0โ no more commands, we're done here.Escapeโ1โ the nextPis two bytes.Startโ2โ start condition.Stopโ3โ stop condition.Addressโ4 Pโ set I2C address toP.Flagsโ5 lsb msbโ set I2C flags tolsb + (msb << 8).Readโ6 Pโ readPbytes of data.Writeโ7 P ...โ writePbytes of data.
The address, read, and write commands all take a parameter P. Normally P is one byte (0-255). But if the command is preceded by the Escape command, then P is two bytes (0-65535, least significant byte first). Sneaky little glow-up. โจ
The address and flags default to 0. And the address and flags keep their previous value until they get updated โ they're loyal like that. ๐
No flags are currently defined.
The returned I2C data gets stored in consecutive locations of outBuf.
Example
Set address 0x53, start, write 0x32, (re)start, read 6 bytes, stop. Then set address 0x1E, start, write 0x03, (re)start, read 6 bytes, stop. Then set address 0x68, start, write 0x1B, (re)start, read 8 bytes, stop. End.
0x04 0x53
0x02 0x07 0x01 0x32 0x02 0x06 0x06 0x03
0x04 0x1E
0x02 0x07 0x01 0x03 0x02 0x06 0x06 0x03
0x04 0x68
0x02 0x07 0x01 0x1B 0x02 0x06 0x08 0x03
0x00
int bb_spi_open(int pi, unsigned CS, unsigned MISO, unsigned MOSI, unsigned SCLK, unsigned baud, unsigned spi_flags)
This one picks out a set of GPIO for bit banging SPI at whatever baud rate you ask for. Iconic. ๐ฆ
pi:>=0(as returned bypigpio_start).CS:0-31.MISO:0-31.MOSI:0-31.SCLK:0-31.baud:50-250000.spi_flags: see below.
spi_flags consists of the least significant 22 bits.
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 R T 0 0 0 0 0 0 0 0 0 0 0 p m m
mm defines the SPI mode, and it defaults to 0.
- Mode
0: CPOL0, CPHA0 - Mode
1: CPOL0, CPHA1 - Mode
2: CPOL1, CPHA0 - Mode
3: CPOL1, CPHA1
p is 0 if CS is active low (that's the default, btw) and 1 for active high.
T is 1 if the least significant bit is transmitted on MOSI first. The default (0) shifts the most significant bit out first.
R is 1 if the least significant bit is received on MISO first. The default (0) receives the most significant bit first.
The other bits in flags should be set to zero.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_SPI_BAUD, or PI_GPIO_IN_USE.
Heads up bestie: if more than one device is connected to the SPI bus (defined bySCLK,MOSI, andMISO) then each one has to have its own CS. No sharing, no borrowing. ๐ โโ๏ธ
Example
bb_spi_open(pi,10, MISO, MOSI, SCLK, 10000, 0); // device 1
bb_spi_open(pi,11, MISO, MOSI, SCLK, 20000, 3); // device 2
int bb_spi_close(int pi, unsigned CS)
This function stops bit banging SPI on a set of GPIO that got opened with bbSPIOpen.
pi:>=0(as returned bypigpio_start).CS:0-31, the CS GPIO used in a prior call tobb_spi_open.
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_SPI_GPIO.
int bb_spi_xfer(int pi, unsigned CS, char *txBuf, char *rxBuf, unsigned count)
This one executes a bit banged SPI transfer. Go off. ๐ฅ
pi:>=0(as returned bypigpio_start).CS:0-31(as used in a prior call tobb_spi_open).txBuf: pointer to buffer to hold data to be sent.rxBuf: pointer to buffer to hold returned data.count: size of data transfer.
Returns >= 0 if OK (the number of bytes read), otherwise PI_BAD_USER_GPIO, PI_NOT_SPI_GPIO or PI_BAD_POINTER.
Example
// gcc -Wall -pthread -o bb_spi_x_test bb_spi_x_test.c -lpigpiod_if2
// ./bb_spi_x_test
#include <stdio.h>
#include "pigpiod_if2.h"
#define CE0 5
#define CE1 6
#define MISO 13
#define MOSI 19
#define SCLK 12
int main(int argc, char *argv[])
{
int i, pi, count, set_val, read_val;
unsigned char inBuf[3];
char cmd1[] = {0, 0};
char cmd2[] = {12, 0};
char cmd3[] = {1, 128, 0};
if ((pi = pigpio_start(0, 0)) < 0)
{
fprintf(stderr, "pigpio initialisation failed (%d).0, pi);
return 1;
}
bb_spi_open(pi, CE0, MISO, MOSI, SCLK, 10000, 0); // MCP4251 DAC
bb_spi_open(pi, CE1, MISO, MOSI, SCLK, 20000, 3); // MCP3008 ADC
for (i=0; i<256; i++)
{
cmd1[1] = i;
count = bb_spi_xfer(pi, CE0, cmd1, (char *)inBuf, 2); // > DAC
if (count == 2)
{
count = bb_spi_xfer(pi, CE0, cmd2, (char *)inBuf, 2); // < DAC
if (count == 2)
{
set_val = inBuf[1];
count = bb_spi_xfer(pi, CE1, cmd3, (char *)inBuf, 3); // < ADC
if (count == 3)
{
read_val = ((inBuf[1]&3)<<8) | inBuf[2];
printf("%d %d0, set_val, read_val);
}
}
}
}
bb_spi_close(pi, CE0);
bb_spi_close(pi, CE1);
pigpio_stop(pi);
}
int spi_open(int pi, unsigned spi_channel, unsigned baud, unsigned spi_flags)
This function hands you back a handle for the SPI device on the channel. Data gets transferred at baud bits per second. And the flags? They can be used to modify the default behaviour of 4-wire operation, mode 0, active low chip select. ๐ธ
The Pi has two SPI peripherals: main and auxiliary.
The main SPI has two chip selects (channels), and the auxiliary has three.
The auxiliary SPI is available on all models but the A and B.
The GPIO used are given in the following table.
MISO MOSI SCLK CE0 CE1 CE2
Main SPI 9 10 11 8 7 -
Aux SPI 19 20 21 18 17 16
pi:>=0(as returned bypigpio_start).spi_channel:0-1(0-2for the auxiliary SPI).baud:32K-125M(values above30Mare unlikely to work).spi_flags: see below.
Returns a handle (>=0) if OK, otherwise PI_BAD_SPI_CHANNEL, PI_BAD_SPI_SPEED, PI_BAD_FLAGS, PI_NO_AUX_SPI, or PI_SPI_OPEN_FAILED.
spi_flags consists of the least significant 22 bits.
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m
mm defines the SPI mode.
Warning bestie: modes1and3do not appear to work on the auxiliary SPI. Like, at all. ๐ญ
- Mode
0: POL0, PHA0 - Mode
1: POL0, PHA1 - Mode
2: POL1, PHA0 - Mode
3: POL1, PHA1
px is 0 if CEx is active low (that's the default, periodt) and 1 for active high.
ux is 0 if the CEx GPIO is reserved for SPI (also the default) and 1 otherwise.
A is 0 for the main SPI, 1 for the auxiliary SPI.
W is 0 if the device is not 3-wire, 1 if the device is 3-wire. Main SPI only.
nnnn defines the number of bytes (0-15) to write before switching the MOSI line to MISO to read data. This field is ignored if W is not set. Main SPI only.
T is 1 if the least significant bit is transmitted on MOSI first. The default (0) shifts the most significant bit out first. Auxiliary SPI only.
R is 1 if the least significant bit is received on MISO first. The default (0) receives the most significant bit first. Auxiliary SPI only.
bbbbbb defines the word size in bits (0-32). The default (0) sets 8 bits per word. Auxiliary SPI only.
The spi_read, spi_write, and spi_xfer functions transfer data packed into 1, 2, or 4 bytes according to the word size in bits.
- For bits
1-8there will be one byte per character. - For bits
9-16there will be two bytes per character. - For bits
17-32there will be four bytes per character.
Multi-byte transfers are made in least significant byte first order.
E.g. to transfer 32 11-bit words buf should contain 64 bytes and count should be 64.
E.g. to transfer the 14 bit value 0x1ABC send the bytes 0xBC followed by 0x1A.
The other bits in flags should be set to zero.
int spi_close(int pi, unsigned handle)
This function closes the SPI device identified by the handle.
pi:>=0(as returned bypigpio_start).handle:>=0, as returned by a call tospi_open.
Returns 0 if OK, otherwise PI_BAD_HANDLE.
int spi_read(int pi, unsigned handle, char *buf, unsigned count)
This function reads count bytes of data from the SPI device associated with the handle.
pi:>=0(as returned bypigpio_start).handle:>=0, as returned by a call tospi_open.buf: an array to receive the read data bytes.count: the number of bytes to read.
Returns the number of bytes transferred if OK, otherwise PI_BAD_HANDLE, PI_BAD_SPI_COUNT, or PI_SPI_XFER_FAILED.
int spi_write(int pi, unsigned handle, char *buf, unsigned count)
This function writes count bytes of data from buf to the SPI device associated with the handle.
pi:>=0(as returned bypigpio_start).handle:>=0, as returned by a call tospi_open.buf: the data bytes to write.count: the number of bytes to write.
Returns the number of bytes transferred if OK, otherwise PI_BAD_HANDLE, PI_BAD_SPI_COUNT, or PI_SPI_XFER_FAILED.
int spi_xfer(int pi, unsigned handle, char *txBuf, char *rxBuf, unsigned count)
This function transfers count bytes of data from txBuf to the SPI device associated with the handle. Simultaneously, count bytes of data are read from the device and placed in rxBuf. Two things at once, main character energy fr fr. ๐
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call tospi_open.txBufโ the data bytes to write.rxBufโ the received data bytes.countโ the number of bytes to transfer.
Returns the number of bytes transferred if OK, otherwise PI_BAD_HANDLE, PI_BAD_SPI_COUNT, or PI_SPI_XFER_FAILED. that's it bestie, that's the whole transfer ๐
โจ SERIAL STUFF โจ
serial_open
int serial_open(int pi, char *ser_tty, unsigned baud, unsigned ser_flags)
Okay so this one opens a serial device, at a baud rate you pick, with flags you pick. Heads up tho: the device name must start with /dev/tty or /dev/serial. No exceptions, no cap. ๐ซ
piโ>=0(as returned bypigpio_start).ser_ttyโ the serial device to open.baudโ the baud rate in bits per second, see below.ser_flagsโ0.
Returns a handle (>=0) if OK, otherwise PI_NO_HANDLE, or PI_SER_OPEN_FAILED.
The baud rate has to be one of these, like literally pick from this list: 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, or 230400. that's the whole menu, no substitutions ๐
No flags are currently defined. This parameter should be set to zero.
serial_close
int serial_close(int pi, unsigned handle)
Closes the serial device associated with handle. bye bestie ๐
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call toserial_open.
Returns 0 if OK, otherwise PI_BAD_HANDLE.
serial_write_byte
int serial_write_byte(int pi, unsigned handle, unsigned bVal)
Writes bVal to the serial port associated with handle. one lil byte, so cute ๐
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call toserial_open.
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_SER_WRITE_FAILED.
serial_read_byte
int serial_read_byte(int pi, unsigned handle)
Reads a byte from the serial port associated with handle. โจ
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call toserial_open.
Returns the read byte (>=0) if OK, otherwise PI_BAD_HANDLE, PI_SER_READ_NO_DATA, or PI_SER_READ_FAILED.
If no data is ready PI_SER_READ_NO_DATA is returned. she's just not ready yet, give her a sec ๐ญ
serial_write
int serial_write(int pi, unsigned handle, char *buf, unsigned count)
Writes count bytes from buf to the the serial port associated with handle.
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call toserial_open.bufโ the array of bytes to write.countโ the number of bytes to write.
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, or PI_SER_WRITE_FAILED.
serial_read
int serial_read(int pi, unsigned handle, char *buf, unsigned count)
Reads up to count bytes from the the serial port associated with handle and writes them to buf. up to!! she stops when she stops bestie, don't come for her ๐ธ
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call toserial_open.bufโ an array to receive the read data.countโ the maximum number of bytes to read.
Returns the number of bytes read (>=0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, PI_SER_READ_NO_DATA, or PI_SER_WRITE_FAILED.
If no data is ready zero is returned.
serial_data_available
int serial_data_available(int pi, unsigned handle)
Returns the number of bytes available to be read from the device associated with handle. the vibe check of serial ports ๐ฆ
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned by a call toserial_open.
Returns the number of bytes of data available (>=0) if OK, otherwise PI_BAD_HANDLE.
๐ CUSTOM FUNCTIONS ๐
custom_1
int custom_1(int pi, unsigned arg1, unsigned arg2, char *argx, unsigned argc)
This function is available for user customisation. it's YOURS, do whatever, main character energy ๐
It returns a single integer value.
piโ>=0(as returned bypigpio_start).arg1โ>=0arg2โ>=0argxโ extra (byte) argumentsargcโ number of extra arguments
Returns >= 0 if OK, less than 0 indicates a user defined error.
custom_2
int custom_2(int pi, unsigned arg1, char *argx, unsigned argc, char *retBuf, unsigned retMax)
This function is available for user customisation.
It differs from custom_1 in that it returns an array of bytes rather than just an integer. glow up fr fr โจ
The return value is an integer indicating the number of returned bytes.
piโ>=0(as returned bypigpio_start).arg1โ>=0argcโ extra (byte) argumentscountโ number of extra argumentsretBufโ buffer for returned dataretMaxโ maximum number of bytes to return
Returns >= 0 if OK, less than 0 indicates a user defined error.
Note, the number of returned bytes will be retMax or less. never more, she knows her limits ๐
๐ PAD STRENGTH ๐
get_pad_strength
int get_pad_strength(int pi, unsigned pad)
Returns the pad drive strength in mA. โก
piโ>=0(as returned bypigpio_start).padโ0-2, the pad to get.
Returns the pad drive strength if OK, otherwise PI_BAD_PAD.
Pad โ GPIO mapping:
0โ0-271โ28-452โ46-53
Example
strength = get_pad_strength(pi, 0); // get pad 0 strength
set_pad_strength
int set_pad_strength(int pi, unsigned pad, unsigned padStrength)
Sets the pad drive strength in mA. โก
piโ>=0(as returned bypigpio_start).padโ0-2, the pad to set.padStrengthโ1-16mA.
Returns 0 if OK, otherwise PI_BAD_PAD, or PI_BAD_STRENGTH.
Pad โ GPIO mapping:
0โ0-271โ28-452โ46-53
Example
set_pad_strength(pi, 0, 10); // set pad 0 strength to 10 mA
๐ SHELL TIME ๐
shell_
int shell_(int pi, char *scriptName, char *scriptString)
This function uses the system call to execute a shell script with the given string as its parameter.
piโ>=0(as returned bypigpio_start).scriptNameโ the name of the script, only alphanumeric characters,'-'and'_'are allowed in the name.scriptStringโ the string to pass to the script.
The exit status of the system call is returned if OK, otherwise PI_BAD_SHELL_STATUS.
scriptName must exist in /opt/pigpio/cgi and must be executable. if it's not there or not executable, she's not running, periodt ๐ซ
The returned exit status is normally 256 times that set by the shell script exit function. If the script can't be found 32512 will be returned.
Some example returned statuses, for the girlies who like receipts:
- script exit status
1โ returned system call status256 - script exit status
5โ returned system call status1280 - script exit status
10โ returned system call status2560 - script exit status
200โ returned system call status51200 - script not found โ returned system call status
32512
Example
// pass two parameters, hello and world
status = shell_(pi, "scr1", "hello world");
// pass three parameters, hello, string with spaces, and world
status = shell_(pi, "scr1", "hello 'string with spaces' world");
// pass one parameter, hello string with spaces world
status = shell_(pi, "scr1", "
๐ FILE STUFF ๐
file_open
int file_open(int pi, char *file, unsigned mode)
Returns a handle to a file opened in a specified mode. ๐๏ธ
piโ>=0(as returned bypigpio_start).fileโ the file to open.modeโ the file open mode.
Returns a handle (>=0) if OK, otherwise PI_NO_HANDLE, PI_NO_FILE_ACCESS, PI_BAD_FILE_MODE, PI_FILE_OPEN_FAILED, or PI_FILE_IS_A_DIR.
File
A file may only be opened if permission is granted by an entry in /opt/pigpio/access. This is intended to allow remote access to files in a more or less controlled manner. gatekeeping but make it secure ๐
Each entry in /opt/pigpio/access takes the form of a file path which may contain wildcards followed by a single letter permission. The permission may be R for read, W for write, U for read/write, and N for no access.
Where more than one entry matches a file the most specific rule applies. If no entry matches a file then access is denied. no match = no entry, bestie, that's the rule ๐ช
Suppose /opt/pigpio/access contains the following entries:
/home/* n
/home/pi/shared/dir_1/* w
/home/pi/shared/dir_2/* r
/home/pi/shared/dir_3/* u
/home/pi/shared/dir_1/file.txt n
- Files may be written in directory
dir_1with the exception offile.txt. - Files may be read in directory
dir_2. - Files may be read and written in directory
dir_3.
If a directory allows read, write, or read/write access then files may be created in that directory.
In an attempt to prevent risky permissions the following paths are ignored in /opt/pigpio/access:
- a path containing
.. - a path containing only wildcards (
*?) - a path containing less than two non-wildcard parts
Mode
The mode may have the following values.
PI_FILE_READ=1โ open file for readingPI_FILE_WRITE=2โ open file for writingPI_FILE_RW=3โ open file for reading and writing
The following values may be or'd into the mode.
PI_FILE_APPEND=4โ Writes append data to the end of the filePI_FILE_CREATE=8โ The file is created if it doesn't existPI_FILE_TRUNC=16โ The file is truncated
Newly created files are owned by root with permissions owner read and write. root said "my file, my rules" ๐
Example
#include <stdio.h>
#include <pigpiod_if2.h>
int main(int argc, char *argv[])
{
int pi, handle, c;
char buf[60000];
pi = pigpio_start(NULL, NULL);
if (pi < 0) return 1;
// assumes /opt/pigpio/access contains the following line
// /ram/*.c r
handle = file_open(pi, "/ram/pigpio.c", PI_FILE_READ);
if (handle >= 0)
{
while ((c=file_read(pi, handle, buf, sizeof(buf)-1)))
{
buf[c] = 0;
printf("%s", buf);
}
file_close(pi, handle);
}
pigpio_stop(pi);
}
file_close
int file_close(int pi, unsigned handle)
Closes the file associated with handle. ๐ซถ
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned byfile_open.
Returns 0 if OK, otherwise PI_BAD_HANDLE.
Example
file_close(pi, handle);
file_write
int file_write(int pi, unsigned handle, char *buf, unsigned count)
Writes count bytes from buf to the the file associated with handle.
piโ>=0(as returned bypigpio_start).handleโ>=0, as returned byfile_open.bufโ the array of bytes to write.countโ the number of bytes to write.
Returns 0 if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, PI_FILE_NOT_WOPEN, or PI_BAD_FILE_WRITE.
Example
if (file_write(pi, handle, buf, 100) == 0)
{
// file written okay
}
else
{
// error
}
๐ธ file_read ๐ธ
int file_read(int pi, unsigned handle, char *buf, unsigned count)
Bestie, this one reads up to count bytes from the file tied to handle and drops them into buf. It's giving "read the vibes from the file, put them in your array."
pi: >=0 (as returned bypigpio_start).handle: >=0 (as returned byfile_open).buf: an array to receive the read data.count: the maximum number of bytes to read.
Returns the number of bytes read (>0) if OK, otherwise PI_BAD_HANDLE, PI_BAD_PARAM, PI_FILE_NOT_ROPEN, or PI_BAD_FILE_WRITE.
Example, no cap:
bytes = file_read(pi, handle, buf, sizeof(buf));
if (bytes >= 0)
{
// process read data
}
๐ฆ file_seek ๐ฆ
int file_seek(int pi, unsigned handle, int32_t seekOffset, int seekFrom)
This function seeks to a position within the file associated with handle. Like sliding into the exact spot in the file you wanna be at. ๐
pi: >=0 (as returned bypigpio_start).handle: >=0 (as returned byfile_open).seekOffset: the number of bytes to move. Positive offsets move forward, negative offsets backwards.seekFrom: one ofPI_FROM_START(0),PI_FROM_CURRENT(1), orPI_FROM_END(2).
Returns the new byte position within the file (>=0) if OK, otherwise PI_BAD_HANDLE, or PI_BAD_FILE_SEEK.
Examples, periodt:
file_seek(pi, handle, 123, PI_FROM_START); // Start plus 123
size = file_seek(pi, handle, 0, PI_FROM_END); // End, return size
pos = file_seek(pi, handle, 0, PI_FROM_CURRENT); // Current position
๐ file_list ๐
int file_list(int pi, char *fpat, char *buf, unsigned count)
This function returns a list of files which match a pattern. It's like a little file lineup. โจ
pi: >=0 (as returned bypigpio_start).fpat: file pattern to match.buf: an array to receive the matching file names.count: the maximum number of bytes to read.
Returns the number of returned bytes if OK, otherwise PI_NO_FILE_ACCESS, or PI_NO_FILE_MATCH.
The pattern must match an entry in /opt/pigpio/access. The pattern may contain wildcards. See file_open.
NOTE โ The returned value is not the number of files, it is the number of bytes in the buffer. The file names are separated by newline characters. Don't get it twisted, bestie. ๐ญ
Example:
#include <stdio.h>
#include <pigpiod_if2.h>
int main(int argc, char *argv[])
{
int pi, handle, c;
char buf[60000];
pi = pigpio_start(NULL, NULL);
if (pi < 0) return 1;
// assumes /opt/pigpio/access contains the following line
// /ram/*.c r
c = file_list(pi, "/ram/p*.c", buf, sizeof(buf));
if (c >= 0)
{
buf[c] = 0;
printf("%s", buf);
}
pigpio_stop(pi);
}
๐ callback ๐
int callback(int pi, unsigned user_gpio, unsigned edge, CBFunc_t f)
This function initialises a new callback. It's the main character of GPIO event watching. ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.edge:RISING_EDGE,FALLING_EDGE, orEITHER_EDGE.f: the callback function.
The function returns a callback id if OK, otherwise pigif_bad_malloc, pigif_duplicate_callback, or pigif_bad_callback.
The callback is called with the GPIO, edge, and tick, whenever the GPIO has the identified edge.
Parameter tea โ:
GPIO:0-31โ The GPIO which has changed stateedge:0-2โ0= change to low (a falling edge);1= change to high (a rising edge);2= no level change (a watchdog timeout)tick:32 bitโ The number of microseconds since boot. WARNING: this wraps around from4294967295to0roughly every72minutes
The GPIO are sampled at a rate set when the pigpio daemon is started (default 5 us).
The number of samples per second is given in the following table. Sample rate (us) โ samples per sec:
1โ1,000,0002โ500,0004โ250,0005โ200,0008โ125,00010โ100,000
GPIO level changes shorter than the sample rate may be missed. Lowkey tragic but that's the deal.
The daemon software which generates the callbacks is triggered 1000 times per second. The callbacks will be called once per level change since the last time they were called. i.e. The callbacks will get all level changes but there will be a latency.
If you want to track the level of more than one GPIO do so by maintaining the state in the callback. Do not use gpio_read. Remember the event that triggered the callback may have happened several milliseconds before and the GPIO may have changed level many times since then. So keep that state, bestie. ๐ซถ
โจ callback_ex โจ
int callback_ex(int pi, unsigned user_gpio, unsigned edge, CBFuncEx_t f, void *userdata)
This function initialises a new callback. It's the same vibe as callback, but with a little extra userdata sprinkle. ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.edge:RISING_EDGE,FALLING_EDGE, orEITHER_EDGE.f: the callback function.userdata: a pointer to arbitrary user data.
The function returns a callback id if OK, otherwise pigif_bad_malloc, pigif_duplicate_callback, or pigif_bad_callback.
The callback is called with the GPIO, edge, tick, and the userdata pointer, whenever the GPIO has the identified edge.
Parameter tea โ:
GPIO:0-31โ The GPIO which has changed stateedge:0-2โ0= change to low (a falling edge);1= change to high (a rising edge);2= no level change (a watchdog timeout)tick:32 bitโ The number of microseconds since boot. WARNING: this wraps around from4294967295to0roughly every72minutesuserdata:pointerโ Pointer to an arbitrary object
๐ callback_cancel ๐
int callback_cancel(unsigned callback_id)
This function cancels a callback identified by its id. It's giving "okay bye, we're done here." ๐
callback_id: >=0, as returned by a call tocallbackorcallback_ex.
The function returns 0 if OK, otherwise pigif_callback_not_found.
๐ง wait_for_edge ๐ง
int wait_for_edge(int pi, unsigned user_gpio, unsigned edge, double timeout)
This function waits for an edge on the GPIO for up to timeout seconds. It's like waiting for your bestie to text back, but for GPIO. ๐
pi: >=0 (as returned bypigpio_start).user_gpio: 0-31.edge:RISING_EDGE,FALLING_EDGE, orEITHER_EDGE.timeout: >=0.
The function returns when the edge occurs or after the timeout.
Do not use this function for precise timing purposes, the edge is only checked 20 times a second. Whenever you need to know the accurate time of GPIO events use a callback function.
The function returns 1 if the edge occurred, otherwise 0.
๐ bsc_xfer ๐
int bsc_xfer(int pi, bsc_xfer_t *bscxfer)
This function provides a low-level interface to the SPI/I2C Slave peripheral on the BCM chip. It's highkey iconic but also a lot. ๐ญ
This peripheral allows the Pi to act as a hardware slave device on an I2C or SPI bus.
This is not a bit bang version and as such is OS timing independent. The bus timing is handled directly by the chip.
The output process is simple. You simply append data to the FIFO buffer on the chip. This works like a queue, you add data to the queue and the master removes it.
Ngl, the original author literally says: "I can't get SPI to work properly. I tried with a control word of 0x303 and swapped MISO and MOSI." So yeah, that's a thing. ๐
The function sets the BSC mode, writes any data in the transmit buffer to the BSC transmit FIFO, and copies any data in the BSC receive FIFO to the receive buffer.
pi: >=0 (as returned bypigpio_start).bscxfer: a structure defining the transfer.
typedef struct
{
uint32_t control; // Write
int rxCnt; // Read only
char rxBuf[BSC_FIFO_SIZE]; // Read only
int txCnt; // Write
char txBuf[BSC_FIFO_SIZE]; // Write
} bsc_xfer_t;
To start a transfer set control (see below), copy the bytes to be added to the transmit FIFO (if any) to txBuf and set txCnt to the number of copied bytes.
Upon return rxCnt will be set to the number of received bytes placed in rxBuf.
The returned function value is the status of the transfer (see below).
If there was an error the status will be less than zero (and will contain the error code).
The most significant word of the returned status contains the number of bytes actually copied from txBuf to the BSC transmit FIFO (may be less than requested if the FIFO already contained untransmitted data).
Note that the control word sets the BSC mode. The BSC will stay in that mode until a different control word is sent.
GPIO used for models other than those based on the BCM2711:
- I2C: SDA
18, SCL19, MOSI-, SCLK-, MISO-, CE- - SPI: SDA
-, SCL-, MOSI18, SCLK19, MISO20, CE21
GPIO used for models based on the BCM2711 (e.g. the Pi4B):
- I2C: SDA
10, SCL11, MOSI-, SCLK-, MISO-, CE- - SPI: SDA
-, SCL-, MOSI10, SCLK11, MISO9, CE8
When a zero control word is received the used GPIO will be reset to INPUT mode.
control consists of the following bits.
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
a a a a a a a - - IT HC TF IR RE TE BK EC ES PL PH I2 SP EN
Bits 0-13 are copied unchanged to the BSC CR register. See pages 163-165 of the Broadcom peripherals document for full details.
aaaaaaaโ defines the I2C slave address (only relevant in I2C mode)ITโ invert transmit status flagsHCโ enable host controlTFโ enable test FIFOIRโ invert receive status flagsREโ enable receiveTEโ enable transmitBKโ abort operation and clear FIFOsECโ send control register as first I2C byteESโ send status register as first I2C bytePLโ set SPI polarity highPHโ set SPI phase highI2โ enable I2C modeSPโ enable SPI modeENโ enable BSC peripheral
The returned status has the following format:
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
S S S S S R R R R R T T T T T RB TE RF TF RE TB
Bits 0-15 are copied unchanged from the BSC FR register. See pages 165-166 of the Broadcom peripherals document for full details. No cap, that's the whole vibe. ๐
SSSSSโ number of bytes successfully copied to transmit FIFORRRRRโ number of bytes in receive FIFOTTTTTโ number of bytes in transmit FIFORBโ receive busyTEโ transmit FIFO emptyRFโ receive FIFO fullTFโ transmit FIFO fullREโ receive FIFO emptyTBโ transmit busy
The following example shows how to configure the BSC peripheral as an I2C slave with address 0x13 and send four bytes. Iconic. โจ
Example
bsc_xfer_t xfer;
xfer.control = (0x13<<16) | 0x305;
memcpy(xfer.txBuf, "ABCD", 4);
xfer.txCnt = 4;
status = bsc_xfer(pi, &xfer);
if (status >= 0)
{
// process transfer
}
int bsc_i2c(int pi, int i2c_addr, bsc_xfer_t *bscxfer)
This function allows the Pi to act as a slave I2C device. Main character energy fr fr. ๐
This function is not available on the BCM2711 (e.g. as used in the Pi4B). So if you're on a Pi 4B, this one's a no-go, bestie. ๐ญ
The data bytes (if any) are written to the BSC transmit FIFO and the bytes in the BSC receive FIFO are returned.
pi:>=0(as returned bypigpio_start).i2c_addr:0-0x7F.bscxfer: a structure defining the transfer.
typedef struct
{
uint32_t control; // N/A
int rxCnt; // Read only
char rxBuf[BSC_FIFO_SIZE]; // Read only
int txCnt; // Write
char txBuf[BSC_FIFO_SIZE]; // Write
} bsc_xfer_t;
txCnt is set to the number of bytes to be transmitted, possibly zero. The data itself should be copied to txBuf.
Any received data will be written to rxBuf with rxCnt set.
See bsc_xfer for details of the returned status value.
If there was an error the status will be less than zero (and will contain the error code).
Note that ani2c_addressof0may be used to close the BSC device and reassign the used GPIO as inputs.
int event_callback(int pi, unsigned event, evtCBFunc_t f)
This function initialises an event callback. Set it up, bestie. ๐
pi:>=0(as returned bypigpio_start).event:0-31.f: the callback function.
The function returns a callback id if OK, otherwise pigif_bad_malloc, pigif_duplicate_callback, or pigif_bad_callback.
The callback is called with the event id, and tick, whenever the event occurs.
int event_callback_ex(int pi, unsigned event, evtCBFuncEx_t f, void *userdata)
This function initialises an event callback. Extra edition, with userdata. โจ
pi:>=0(as returned bypigpio_start).event:0-31.f: the callback function.userdata: a pointer to arbitrary user data.
The function returns a callback id if OK, otherwise pigif_bad_malloc, pigif_duplicate_callback, or pigif_bad_callback.
The callback is called with the event id, the tick, and the userdata pointer whenever the event occurs.
int event_callback_cancel(unsigned callback_id)
This function cancels an event callback identified by its id. Bye-bye, callback. ๐
callback_id: >=0, as returned by a call to event_callback or event_callback_ex.
The function returns 0 if OK, otherwise pigif_callback_not_found.
int wait_for_event(int pi, unsigned event, double timeout)
This function waits for an event for up to timeout seconds. Chill and wait, bestie. ๐ฆ
pi:>=0(as returned bypigpio_start).event:0-31.timeout:>=0.
The function returns when the event occurs or after the timeout.
The function returns 1 if the event occurred, otherwise 0.
int event_trigger(int pi, unsigned event)
This function signals the occurrence of an event. Trigger warning? No, trigger the event. โญ
pi:>=0(as returned bypigpio_start).event:0-31.
Returns 0 if OK, otherwise PI_BAD_EVENT_ID.
An event is a signal used to inform one or more consumers to start an action. Each consumer which has registered an interest in the event (e.g. by calling event_callback) will be informed by a callback.
One event, PI_EVENT_BSC (31) is predefined. This event is auto generated on BSC slave activity.
The meaning of other events is arbitrary.
Note that other than its id and its tick there is no data associated with an event.
โจ PARAMETERS โจ
active:0-1000000โ the number of microseconds level changes are reported for once a noise filter has been triggered (by steady microseconds of a stable level). ๐*addrStrโ a string specifying the host or IP address of the Pi running the pigpio daemon. It may beNULL, in which case localhost is used unless overridden by thePIGPIO_ADDRenvironment variable. ๐arg1โ an unsigned argument passed to a user customised function. Its meaning is defined by the customiser.arg2โ an unsigned argument passed to a user customised function. Its meaning is defined by the customiser.argcโ the count of bytes passed to a user customised function.*argxโ a pointer to an array of bytes passed to a user customised function. Its meaning and content is defined by the customiser.baudโ the speed of serial communication (I2C, SPI, serial link, waves) in bits per second.bitโ a value of0or1.bitsโ a value used to select GPIO. If bitnofbitsis set then GPIOnis selected.
A convenient way to set bit n is to or in (1<<n).
e.g. to select bits 5, 9, 23 you could use (1<<5) | (1<<9) | (1<<23).
bsc_xfer_tโ bestie, it's this struct:
typedef struct
{
uint32_t control; // Write
int rxCnt; // Read only
char rxBuf[BSC_FIFO_SIZE]; // Read only
int txCnt; // Write
char txBuf[BSC_FIFO_SIZE]; // Write
} bsc_xfer_t;
*bscxferโ a pointer to absc_xfer_tobject used to control a BSC transfer.*bufโ a buffer to hold data being sent or being received.bufSizeโ the size in bytes of a buffer.bVal:0-255(Hex0x0-0xFF, Octal0-0377) โ an 8-bit byte value.callback_idโ a value>=0, as returned by a call to a callback function, one of:callbackcallback_exevent_callbackevent_callback_ex
The id is passed to callback_cancel or event_callback_cancel to cancel the callback.
CBFunc_tโ this typedef:
typedef void (*CBFunc_t)
(int pi, unsigned user_gpio, unsigned level, uint32_t tick);
CBFuncEx_tโ this typedef:
typedef void (*CBFuncEx_t)
(int pi, unsigned user_gpio, unsigned level, uint32_t tick, void * userdata);
charโ a single character, an 8 bit quantity able to store0-255.clkfreq:4689-250M(13184-375Mfor the BCM2711) โ the hardware clock frequency.countโ the number of bytes to be transferred in a file, I2C, SPI, or serial command.CSโ the GPIO used for the slave select signal when bit banging SPI.data_bits:1-32โ the number of data bits in each character of serial data.
#define PI_MIN_WAVE_DATABITS 1
#define PI_MAX_WAVE_DATABITS 32
doubleโ a floating point number.dutycycle:0-rangeโ a number representing the ratio of on time to off time for PWM.
The number may vary between 0 and range (default 255) where 0 is off and range is fully on.
edgeโ used to identify a GPIO level transition of interest. A rising edge is a level change from0to1. A falling edge is a level change from1to0.RISING_EDGE 0FALLING_EDGE 1EITHER_EDGE. 2
errnumโ a negative number indicating a function call failed and the nature of the error.event:0-31โ an event is a signal used to inform one or more consumers to start an action.evtCBFunc_tโ this typedef:
typedef void (*evtCBFunc_t)
(int pi, unsigned event, uint32_t tick);
evtCBFuncEx_tโ this typedef:
typedef void (*evtCBFuncEx_t)
(int pi, unsigned event, uint32_t tick, void *userdata);
fโ a function.*fileโ a full file path. To be accessible the path must match an entry in/opt/pigpio/access.*fpatโ a file path which may contain wildcards. To be accessible the path must match an entry in/opt/pigpio/access.frequency:>=0โ the number of times a GPIO is switched on and off per second. This can be set per GPIO and may be as little as5Hzor as much as40KHz. The GPIO will be on for a proportion of the time as defined by itsdutycycle.gpioโ a Broadcom numbered GPIO, in the range0-53.
There are 54 General Purpose Input Outputs (GPIO) named GPIO0 through GPIO53.
They are split into two banks. Bank 1 consists of GPIO0 through GPIO31. Bank 2 consists of GPIO32 through GPIO53.
All the GPIO which are safe for the user to read and write are in bank 1. Not all GPIO in bank 1 are safe though. Type 1 boards have 17 safe GPIO. Type 2 boards have 21. Type 3 boards have 26.
See get_hardware_revision.
The user GPIO are marked with an X in the following table. The original table is giving spreadsheet, so here's the list version, bestie: ๐
- Type 1 โ
Xfor GPIO0,1,4,7,8,9,10,11,14,15,17,18,21,22,23,24,25. - Type 2 โ
Xfor GPIO2,3,4,7,8,9,10,11,14,15,17,18,22,23,24,25,27,28,29,30,31. - Type 3 โ
Xfor GPIO2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27. (GPIO0and1are blank for Type 3 in the original table.)
The rest are marked - (not safe) in the original table. So don't come for them. ๐ญ
gpioPulse_tโ this struct:
typedef struct
{
uint32_t gpioOn;
uint32_t gpioOff;
uint32_t usDelay;
} gpioPulse_t;
gpioThreadFunc_tโ this typedef:
typedef void *(gpioThreadFunc_t) (void *);
handle:>=0โ a number referencing an object opened by one of:file_openi2c_opennotify_openserial_openspi_open
i2c_addr:0-0x7Fโ the address of a device on the I2C bus.i2c_bus:>=0โ an I2C bus number.i2c_flags:0โ flags which modify an I2C open command. None are currently defined.i2c_reg:0-255โ a register of an I2C device.*inBufโ a buffer used to pass data to a function.inLenโ the number of bytes of data in a buffer.intโ a whole number, negative or positive.int32_tโ a 32-bit signed value.invertโ a flag used to set normal or inverted bit bang serial data level logic.levelโ the level of a GPIO. Low or High.PI_OFF 0PI_ON 1PI_CLEAR 0PI_SET 1PI_LOW 0PI_HIGH 1
There is one exception. If a watchdog expires on a GPIO the level will be reported as PI_TIMEOUT. See set_watchdog.
PI_TIMEOUT 2
MISOโ the GPIO used for the MISO signal when bit banging SPI.modeโ 1. The operational mode of a GPIO, normallyINPUTorOUTPUT.
PI_INPUT 0
PI_OUTPUT 1
PI_ALT0 4
PI_ALT1 5
PI_ALT2 6
PI_ALT3 7
PI_ALT4 3
PI_ALT5 2
โฆand that's the rest of that first little family of values, periodt ๐
- The mode of waveform transmission. Slay, here's the whole squad:
PI_WAVE_MODE_ONE_SHOT 0
PI_WAVE_MODE_REPEAT 1
PI_WAVE_MODE_ONE_SHOT_SYNC 2
PI_WAVE_MODE_REPEAT_SYNC 3
- A file open mode. Yes queen, the basic ones:
PI_FILE_READ 1
PI_FILE_WRITE 2
PI_FILE_RW 3
And bestie, these next values can be or'd into the mode. Stack 'em, it's giving combos โจ
PI_FILE_APPEND 4
PI_FILE_CREATE 8
PI_FILE_TRUNC 16
MOSIโ the GPIO you're using for the MOSI signal when you're bit banging SPI ๐ ๏ธnumBytesโ how many bytes it takes to store characters in a string. Depending on how many bits per character you've got, it could be 1, 2, or 4 bytes per character. Math is mathing ๐งฎnumPar: 0-10 โ how many parameters you're passing to a script ๐numPulsesโ the number of pulses you're adding to a waveform ๐offsetโ the associated data starts this many microseconds from the start of the waveform โฑ๏ธ*outBufโ a buffer used to return data from a function, iykyk ๐คoutLenโ the size in bytes of an output bufferpad: 0-2 โ a set of GPIO that share common drivers. The lineup:
Pad GPIO
0 0-27
1 28-45
2 46-53
padStrength: 1-16 โ the mA you can draw from each GPIO while still guaranteeing the high and low levels. Don't get greedy ๐*paramโ an array of script parameterspercent: 0-100 โ the size of the waveform, as a percentage of the max available ๐piโ an integer defining a connected Pi. This is the valuepigpio_starthands back to you on success ๐ซถ*portStrโ a string with the port address used by the Pi running the pigpio daemon. It may beNULL, and in that case"8888"is used โ unless thePIGPIO_PORTenvironment variable overrides it ๐*pthโ a thread identifier, returned bystart_thread๐งตpthread_tโ a thread identifier (the type, bestie)pud: 0-2 โ the setting of the pull up/down resistor for a GPIO. It can be off, pull-up, or pull-down:
PI_PUD_OFF 0
PI_PUD_DOWN 1
PI_PUD_UP 2
pulseLenโ 1-100, the length of a trigger pulse in microseconds โก*pulsesโ an array of pulses to be added to a waveformpulsewidth: 0, 500-2500
PI_SERVO_OFF 0
PI_MIN_SERVO_PULSEWIDTH 500
PI_MAX_SERVO_PULSEWIDTH 2500
PWMduty: 0-1000000 (1M) โ the hardware PWM dutycycle. That's a whole million, no cap ๐ญ
#define PI_HW_PWM_RANGE 1000000
PWMfreq: 1-125M (1-187.5M for the BCM2711) โ the hardware PWM frequency ๐
#define PI_HW_PWM_MIN_FREQ 1
#define PI_HW_PWM_MAX_FREQ 125000000
#define PI_HW_PWM_MAX_FREQ_2711 187500000
range: 25-40000 โ the permissible dutycycle values are0-range๐ฏ
PI_MIN_DUTYCYCLE_RANGE 25
PI_MAX_DUTYCYCLE_RANGE 40000
*retBufโ a buffer to hold a number of bytes returned to a used customised function ๐ฅretMaxโ the maximum number of bytes a user customised function should return*rxBufโ a pointer to a buffer to receive dataSCLโ the user GPIO to use for the clock when bit banging I2C ๐ฐ๏ธSCLKโ the GPIO used for the SCLK signal when bit banging SPI*scriptโ a pointer to the text of a scriptscript_idโ an id of a stored script, as returned bystore_script*scriptNameโ the name of ashell_script to be executed. The script must be present in/opt/pigpio/cgiand must have execute permission. No exceptions, bestie ๐จ*scriptStringโ the string to be passed to ashell_script to be executedSDAโ the user GPIO to use for data when bit banging I2Csecondsโ the number of seconds โณseekFromโ where you're seeking from:
PI_FROM_START 0
PI_FROM_CURRENT 1
PI_FROM_END 2
seekOffsetโ the number of bytes to move forward (positive) or backwards (negative) from the seek position (start, current, or end of file). Yes, negative numbers are valid here, go off โก๏ธโฌ ๏ธser_flagsโ flags which modify a serial open command. None are currently defined. That's it, that's the whole flag set ๐*ser_ttyโ the name of a serial tty device, e.g./dev/ttyAMA0,/dev/ttyUSB0,/dev/tty1๐size_tโ a standard type used to indicate the size of an object in bytesspi_channelโ a SPI channel, 0-2spi_flagsโ seespi_openandbb_spi_open๐steady: 0-300000 โ the number of microseconds the level changes must be stable for before reporting the level changed (set_glitch_filter) or before triggering the active part of a noise filter (set_noise_filter) ๐งstop_bits: 2-8 โ the number of (half) stop bits to be used when adding serial data to a waveform
#define PI_MIN_WAVE_HALFSTOPBITS 2
#define PI_MAX_WAVE_HALFSTOPBITS 8
*strโ an array of characters ๐คthread_funcโ a function of typegpioThreadFunc_tused as the main function of a threadtimeoutโ a GPIO watchdog timeout in milliseconds โฐ
PI_MIN_WDOG_TIMEOUT 0
PI_MAX_WDOG_TIMEOUT 60000
*txBufโ an array of bytes to transmit ๐กuint32_t: 0-0-4,294,967,295 (Hex 0x0-0xFFFFFFFF) โ a 32-bit unsigned value. (Yes, that range is written exactly like that in the source, and yes, it's iconic in a chaotic way ๐)unsignedโ a whole number>= 0user_gpioโ 0-31, a Broadcom numbered GPIO. Seegpio๐*userdataโ a pointer to arbitrary user data. This may be used to identify the instance.
You must ensure that the pointer is in scope at the time it is processed. If it's a pointer to a global, that's automatic. Do not pass the address of a local variable ๐ซ. If you want to pass a transient object, then use this technique:
In the calling function:
user_type *userdata;
user_type my_userdata;
userdata = malloc(sizeof(user_type));
*userdata = my_userdata;
In the receiving function:
user_type my_userdata = *(user_type*)userdata;
free(userdata);
voidโ denoting no parameter is requiredwave_add_*โ one of
wave_add_new
wave_add_generic
wave_add_serial
wave_idโ a number representing a waveform created bywave_createwave_send_*โ one of
wave_send_once
wave_send_repeat
wVal: 0-65535 (Hex 0x0-0xFFFF, Octal 0-0177777) โ a 16-bit word value ๐ข
โจ pigpiod_if2 Error Codes โจ
Okay so these are the error codes the library can hand you back, bestie. Meet the whole villain lineup ๐ญ
typedef enum
{
pigif_bad_send = -2000,
pigif_bad_recv = -2001,
pigif_bad_getaddrinfo = -2002,
pigif_bad_connect = -2003,
pigif_bad_socket = -2004,
pigif_bad_noib = -2005,
pigif_duplicate_callback = -2006,
pigif_bad_malloc = -2007,
pigif_bad_callback = -2008,
pigif_notify_failed = -2009,
pigif_callback_not_found = -2010,
pigif_unconnected_pi = -2011,
pigif_too_many_pis = -2012,
} pigifError_t;
๐ SEE ALSO ๐
pigpiod(1), pig2vcd(1), pigs(1), pigpio(3), pigpiod_if(3)
Go read those too, they're the rest of the friend group ๐ซถ
๐ธ AUTHOR ๐ธ
joan@abyz.me.uk
and that's a wrap on the whole page, bestie!! ๐ you read every single line, every flag, every hex value and every error code, and honestly? that's main character energy ๐
โจ this gorgeous thing lives in the Linux manual, dated 2012-2020, and it's filed under pigpiod_if2(3) โ go forth and bit bang responsibly, mwah ๐ฆ๐
๐ฆ where this page comes from
- debian bookworm: libpigpiod-if-dev 1.78-1 ยท unlicense
- debian trixie: libpigpiod-if-dev 1.78-1.1 ยท unlicense
- ubuntu jammy: libpigpiod-if-dev 1.78-1 ยท unlicense
- ubuntu noble: libpigpiod-if-dev 1.78-1.1build1 ยท unlicense
- ubuntu resolute: libpigpiod-if-dev 1.78-1.1build1 ยท unlicense
- ubuntu stonking: libpigpiod-if-dev 1.78-1.1build1 ยท unlicense
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms