Coverage for /usr/lib/python3/dist-packages/pigpio.py: 44%
1021 statements
« prev ^ index » next coverage.py v7.2.7, created at 2024-02-10 12:38 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2024-02-10 12:38 +0000
1"""
2pigpio is a Python module for the Raspberry which talks to
3the pigpio daemon to allow control of the general purpose
4input outputs (GPIO).
6[http://abyz.me.uk/rpi/pigpio/python.html]
8*Features*
10o the pigpio Python module can run on Windows, Macs, or Linux
12o controls one or more Pi's
14o hardware timed PWM on any of GPIO 0-31
16o hardware timed servo pulses on any of GPIO 0-31
18o callbacks when any of GPIO 0-31 change state
20o creating and transmitting precisely timed waveforms
22o reading/writing GPIO and setting their modes
24o wrappers for I2C, SPI, and serial links
26o creating and running scripts on the pigpio daemon
28*GPIO*
30ALL GPIO are identified by their Broadcom number.
32*Notes*
34Transmitted waveforms are accurate to a microsecond.
36Callback level changes are time-stamped and will be
37accurate to within a few microseconds.
39*Settings*
41A number of settings are determined when the pigpio daemon is started.
43o the sample rate (1, 2, 4, 5, 8, or 10 us, default 5 us).
45o the set of GPIO which may be updated (generally written to). The
46 default set is those available on the Pi board revision.
48o the available PWM frequencies (see [*set_PWM_frequency*]).
50*Exceptions*
52By default a fatal exception is raised if you pass an invalid
53argument to a pigpio function.
55If you wish to handle the returned status yourself you should set
56pigpio.exceptions to False.
58You may prefer to check the returned status in only a few parts
59of your code. In that case do the following:
61...
62pigpio.exceptions = False
64# Code where you want to test the error status.
66pigpio.exceptions = True
67...
69*Usage*
71This module uses the services of the C pigpio library. pigpio
72must be running on the Pi(s) whose GPIO are to be manipulated.
74The normal way to start pigpio is as a daemon (during system
75start).
77sudo pigpiod
79Your Python program must import pigpio and create one or more
80instances of the pigpio.pi class. This class gives access to
81a specified Pi's GPIO.
83...
84pi1 = pigpio.pi() # pi1 accesses the local Pi's GPIO
85pi2 = pigpio.pi('tom') # pi2 accesses tom's GPIO
86pi3 = pigpio.pi('dick') # pi3 accesses dick's GPIO
88pi1.write(4, 0) # set local Pi's GPIO 4 low
89pi2.write(4, 1) # set tom's GPIO 4 to high
90pi3.read(4) # get level of dick's GPIO 4
91...
93The later example code snippets assume that pi is an instance of
94the pigpio.pi class.
96OVERVIEW
98ESSENTIAL
100pigpio.pi Initialise Pi connection
101stop Stop a Pi connection
103BASIC
105set_mode Set a GPIO mode
106get_mode Get a GPIO mode
108set_pull_up_down Set/clear GPIO pull up/down resistor
110read Read a GPIO
111write Write a GPIO
113PWM_(overrides_servo_commands_on_same_GPIO)
115set_PWM_dutycycle Start/stop PWM pulses on a GPIO
116set_PWM_frequency Set PWM frequency of a GPIO
117set_PWM_range Configure PWM range of a GPIO
119get_PWM_dutycycle Get PWM dutycycle set on a GPIO
120get_PWM_frequency Get PWM frequency of a GPIO
121get_PWM_range Get configured PWM range of a GPIO
123get_PWM_real_range Get underlying PWM range for a GPIO
125Servo_(overrides_PWM_commands_on_same_GPIO)
127set_servo_pulsewidth Start/Stop servo pulses on a GPIO
129get_servo_pulsewidth Get servo pulsewidth set on a GPIO
131INTERMEDIATE
133gpio_trigger Send a trigger pulse to a GPIO
135set_watchdog Set a watchdog on a GPIO
137read_bank_1 Read all bank 1 GPIO
138read_bank_2 Read all bank 2 GPIO
140clear_bank_1 Clear selected GPIO in bank 1
141clear_bank_2 Clear selected GPIO in bank 2
143set_bank_1 Set selected GPIO in bank 1
144set_bank_2 Set selected GPIO in bank 2
146callback Create GPIO level change callback
148wait_for_edge Wait for GPIO level change
150ADVANCED
152notify_open Request a notification handle
153notify_begin Start notifications for selected GPIO
154notify_pause Pause notifications
155notify_close Close a notification
157hardware_clock Start hardware clock on supported GPIO
159hardware_PWM Start hardware PWM on supported GPIO
161set_glitch_filter Set a glitch filter on a GPIO
162set_noise_filter Set a noise filter on a GPIO
164set_pad_strength Sets a pads drive strength
165get_pad_strength Gets a pads drive strength
167shell Executes a shell command
169Custom
171custom_1 User custom function 1
172custom_2 User custom function 2
174Events
176event_callback Sets a callback for an event
178event_trigger Triggers an event
180wait_for_event Wait for an event
182Scripts
184store_script Store a script
185run_script Run a stored script
186update_script Set a scripts parameters
187script_status Get script status and parameters
188stop_script Stop a running script
189delete_script Delete a stored script
191I2C
193i2c_open Opens an I2C device
194i2c_close Closes an I2C device
196i2c_write_quick SMBus write quick
198i2c_read_byte SMBus read byte
199i2c_write_byte SMBus write byte
201i2c_read_byte_data SMBus read byte data
202i2c_write_byte_data SMBus write byte data
204i2c_read_word_data SMBus read word data
205i2c_write_word_data SMBus write word data
207i2c_read_block_data SMBus read block data
208i2c_write_block_data SMBus write block data
210i2c_read_i2c_block_data SMBus read I2C block data
211i2c_write_i2c_block_data SMBus write I2C block data
213i2c_read_device Reads the raw I2C device
214i2c_write_device Writes the raw I2C device
216i2c_process_call SMBus process call
217i2c_block_process_call SMBus block process call
219i2c_zip Performs multiple I2C transactions
221I2C_BIT_BANG
223bb_i2c_open Opens GPIO for bit banging I2C
224bb_i2c_close Closes GPIO for bit banging I2C
226bb_i2c_zip Performs multiple bit banged I2C transactions
228I2C/SPI_SLAVE
230bsc_xfer I2C/SPI as slave transfer
231bsc_i2c I2C as slave transfer
233SERIAL
235serial_open Opens a serial device
236serial_close Closes a serial device
238serial_read_byte Reads a byte from a serial device
239serial_write_byte Writes a byte to a serial device
241serial_read Reads bytes from a serial device
242serial_write Writes bytes to a serial device
244serial_data_available Returns number of bytes ready to be read
246SERIAL_BIT_BANG_(read_only)
248bb_serial_read_open Open a GPIO for bit bang serial reads
249bb_serial_read_close Close a GPIO for bit bang serial reads
251bb_serial_invert Invert serial logic (1 invert, 0 normal)
253bb_serial_read Read bit bang serial data from a GPIO
255SPI
257spi_open Opens a SPI device
258spi_close Closes a SPI device
260spi_read Reads bytes from a SPI device
261spi_write Writes bytes to a SPI device
262spi_xfer Transfers bytes with a SPI device
264SPI_BIT_BANG
266bb_spi_open Opens GPIO for bit banging SPI
267bb_spi_close Closes GPIO for bit banging SPI
268bb_spi_xfer Transfers bytes with bit banging SPI
270FILES
272file_open Opens a file
273file_close Closes a file
275file_read Reads bytes from a file
276file_write Writes bytes to a file
278file_seek Seeks to a position within a file
280file_list List files which match a pattern
282WAVES
284wave_clear Deletes all waveforms
286wave_add_new Starts a new waveform
287wave_add_generic Adds a series of pulses to the waveform
288wave_add_serial Adds serial data to the waveform
290wave_create Creates a waveform from added data
291wave_create_and_pad Creates a waveform of fixed size from added data
292wave_delete Deletes a waveform
294wave_send_once Transmits a waveform once
295wave_send_repeat Transmits a waveform repeatedly
296wave_send_using_mode Transmits a waveform in the chosen mode
298wave_chain Transmits a chain of waveforms
300wave_tx_at Returns the current transmitting waveform
302wave_tx_busy Checks to see if a waveform has ended
304wave_tx_stop Aborts the current waveform
306wave_get_cbs Length in cbs of the current waveform
307wave_get_max_cbs Absolute maximum allowed cbs
309wave_get_micros Length in microseconds of the current waveform
310wave_get_max_micros Absolute maximum allowed micros
312wave_get_pulses Length in pulses of the current waveform
313wave_get_max_pulses Absolute maximum allowed pulses
315UTILITIES
317get_current_tick Get current tick (microseconds)
319get_hardware_revision Get hardware revision
320get_pigpio_version Get the pigpio version
322pigpio.error_text Gets error text from error number
323pigpio.tickDiff Returns difference between two ticks
324"""
326import sys
327import socket
328import struct
329import time
330import threading
331import os
332import atexit
334VERSION = "1.78" # sync minor number to pigpio library version
336exceptions = True
338# GPIO levels
340OFF = 0
341LOW = 0
342CLEAR = 0
344ON = 1
345HIGH = 1
346SET = 1
348TIMEOUT = 2
350# GPIO edges
352RISING_EDGE = 0
353FALLING_EDGE = 1
354EITHER_EDGE = 2
356# GPIO modes
358INPUT = 0
359OUTPUT = 1
360ALT0 = 4
361ALT1 = 5
362ALT2 = 6
363ALT3 = 7
364ALT4 = 3
365ALT5 = 2
367# GPIO Pull Up Down
369PUD_OFF = 0
370PUD_DOWN = 1
371PUD_UP = 2
373# script run status
375PI_SCRIPT_INITING=0
376PI_SCRIPT_HALTED =1
377PI_SCRIPT_RUNNING=2
378PI_SCRIPT_WAITING=3
379PI_SCRIPT_FAILED =4
381# notification flags
383NTFY_FLAGS_EVENT = (1 << 7)
384NTFY_FLAGS_ALIVE = (1 << 6)
385NTFY_FLAGS_WDOG = (1 << 5)
386NTFY_FLAGS_GPIO = 31
388# wave modes
390WAVE_MODE_ONE_SHOT =0
391WAVE_MODE_REPEAT =1
392WAVE_MODE_ONE_SHOT_SYNC=2
393WAVE_MODE_REPEAT_SYNC =3
395WAVE_NOT_FOUND = 9998 # Transmitted wave not found.
396NO_TX_WAVE = 9999 # No wave being transmitted.
398FILE_READ=1
399FILE_WRITE=2
400FILE_RW=3
402FILE_APPEND=4
403FILE_CREATE=8
404FILE_TRUNC=16
406FROM_START=0
407FROM_CURRENT=1
408FROM_END=2
410SPI_MODE_0 = 0
411SPI_MODE_1 = 1
412SPI_MODE_2 = 2
413SPI_MODE_3 = 3
415SPI_CPHA = 1 << 0
416SPI_CPOL = 1 << 1
418SPI_CS_HIGH_ACTIVE = 1 << 2
420SPI_TX_LSBFIRST = 1 << 14
421SPI_RX_LSBFIRST = 1 << 15
423EVENT_BSC = 31
425_SOCK_CMD_LEN = 16
427# pigpio command numbers
429_PI_CMD_MODES= 0
430_PI_CMD_MODEG= 1
431_PI_CMD_PUD= 2
432_PI_CMD_READ= 3
433_PI_CMD_WRITE= 4
434_PI_CMD_PWM= 5
435_PI_CMD_PRS= 6
436_PI_CMD_PFS= 7
437_PI_CMD_SERVO= 8
438_PI_CMD_WDOG= 9
439_PI_CMD_BR1= 10
440_PI_CMD_BR2= 11
441_PI_CMD_BC1= 12
442_PI_CMD_BC2= 13
443_PI_CMD_BS1= 14
444_PI_CMD_BS2= 15
445_PI_CMD_TICK= 16
446_PI_CMD_HWVER=17
448_PI_CMD_NO= 18
449_PI_CMD_NB= 19
450_PI_CMD_NP= 20
451_PI_CMD_NC= 21
453_PI_CMD_PRG= 22
454_PI_CMD_PFG= 23
455_PI_CMD_PRRG= 24
456_PI_CMD_HELP= 25
457_PI_CMD_PIGPV=26
459_PI_CMD_WVCLR=27
460_PI_CMD_WVAG= 28
461_PI_CMD_WVAS= 29
462_PI_CMD_WVGO= 30
463_PI_CMD_WVGOR=31
464_PI_CMD_WVBSY=32
465_PI_CMD_WVHLT=33
466_PI_CMD_WVSM= 34
467_PI_CMD_WVSP= 35
468_PI_CMD_WVSC= 36
470_PI_CMD_TRIG= 37
472_PI_CMD_PROC= 38
473_PI_CMD_PROCD=39
474_PI_CMD_PROCR=40
475_PI_CMD_PROCS=41
477_PI_CMD_SLRO= 42
478_PI_CMD_SLR= 43
479_PI_CMD_SLRC= 44
481_PI_CMD_PROCP=45
482_PI_CMD_MICRO=46
483_PI_CMD_MILLI=47
484_PI_CMD_PARSE=48
486_PI_CMD_WVCRE=49
487_PI_CMD_WVDEL=50
488_PI_CMD_WVTX =51
489_PI_CMD_WVTXR=52
490_PI_CMD_WVNEW=53
492_PI_CMD_I2CO =54
493_PI_CMD_I2CC =55
494_PI_CMD_I2CRD=56
495_PI_CMD_I2CWD=57
496_PI_CMD_I2CWQ=58
497_PI_CMD_I2CRS=59
498_PI_CMD_I2CWS=60
499_PI_CMD_I2CRB=61
500_PI_CMD_I2CWB=62
501_PI_CMD_I2CRW=63
502_PI_CMD_I2CWW=64
503_PI_CMD_I2CRK=65
504_PI_CMD_I2CWK=66
505_PI_CMD_I2CRI=67
506_PI_CMD_I2CWI=68
507_PI_CMD_I2CPC=69
508_PI_CMD_I2CPK=70
510_PI_CMD_SPIO =71
511_PI_CMD_SPIC =72
512_PI_CMD_SPIR =73
513_PI_CMD_SPIW =74
514_PI_CMD_SPIX =75
516_PI_CMD_SERO =76
517_PI_CMD_SERC =77
518_PI_CMD_SERRB=78
519_PI_CMD_SERWB=79
520_PI_CMD_SERR =80
521_PI_CMD_SERW =81
522_PI_CMD_SERDA=82
524_PI_CMD_GDC =83
525_PI_CMD_GPW =84
527_PI_CMD_HC =85
528_PI_CMD_HP =86
530_PI_CMD_CF1 =87
531_PI_CMD_CF2 =88
533_PI_CMD_NOIB =99
535_PI_CMD_BI2CC=89
536_PI_CMD_BI2CO=90
537_PI_CMD_BI2CZ=91
539_PI_CMD_I2CZ =92
541_PI_CMD_WVCHA=93
543_PI_CMD_SLRI =94
545_PI_CMD_CGI =95
546_PI_CMD_CSI =96
548_PI_CMD_FG =97
549_PI_CMD_FN =98
551_PI_CMD_WVTXM=100
552_PI_CMD_WVTAT=101
554_PI_CMD_PADS =102
555_PI_CMD_PADG =103
557_PI_CMD_FO =104
558_PI_CMD_FC =105
559_PI_CMD_FR =106
560_PI_CMD_FW =107
561_PI_CMD_FS =108
562_PI_CMD_FL =109
563_PI_CMD_SHELL=110
565_PI_CMD_BSPIC=111
566_PI_CMD_BSPIO=112
567_PI_CMD_BSPIX=113
569_PI_CMD_BSCX =114
571_PI_CMD_EVM =115
572_PI_CMD_EVT =116
574_PI_CMD_PROCU=117
575_PI_CMD_WVCAP=118
577# pigpio error numbers
579_PI_INIT_FAILED =-1
580PI_BAD_USER_GPIO =-2
581PI_BAD_GPIO =-3
582PI_BAD_MODE =-4
583PI_BAD_LEVEL =-5
584PI_BAD_PUD =-6
585PI_BAD_PULSEWIDTH =-7
586PI_BAD_DUTYCYCLE =-8
587_PI_BAD_TIMER =-9
588_PI_BAD_MS =-10
589_PI_BAD_TIMETYPE =-11
590_PI_BAD_SECONDS =-12
591_PI_BAD_MICROS =-13
592_PI_TIMER_FAILED =-14
593PI_BAD_WDOG_TIMEOUT =-15
594_PI_NO_ALERT_FUNC =-16
595_PI_BAD_CLK_PERIPH =-17
596_PI_BAD_CLK_SOURCE =-18
597_PI_BAD_CLK_MICROS =-19
598_PI_BAD_BUF_MILLIS =-20
599PI_BAD_DUTYRANGE =-21
600_PI_BAD_SIGNUM =-22
601_PI_BAD_PATHNAME =-23
602PI_NO_HANDLE =-24
603PI_BAD_HANDLE =-25
604_PI_BAD_IF_FLAGS =-26
605_PI_BAD_CHANNEL =-27
606_PI_BAD_PRIM_CHANNEL=-27
607_PI_BAD_SOCKET_PORT =-28
608_PI_BAD_FIFO_COMMAND=-29
609_PI_BAD_SECO_CHANNEL=-30
610_PI_NOT_INITIALISED =-31
611_PI_INITIALISED =-32
612_PI_BAD_WAVE_MODE =-33
613_PI_BAD_CFG_INTERNAL=-34
614PI_BAD_WAVE_BAUD =-35
615PI_TOO_MANY_PULSES =-36
616PI_TOO_MANY_CHARS =-37
617PI_NOT_SERIAL_GPIO =-38
618_PI_BAD_SERIAL_STRUC=-39
619_PI_BAD_SERIAL_BUF =-40
620PI_NOT_PERMITTED =-41
621PI_SOME_PERMITTED =-42
622PI_BAD_WVSC_COMMND =-43
623PI_BAD_WVSM_COMMND =-44
624PI_BAD_WVSP_COMMND =-45
625PI_BAD_PULSELEN =-46
626PI_BAD_SCRIPT =-47
627PI_BAD_SCRIPT_ID =-48
628PI_BAD_SER_OFFSET =-49
629PI_GPIO_IN_USE =-50
630PI_BAD_SERIAL_COUNT =-51
631PI_BAD_PARAM_NUM =-52
632PI_DUP_TAG =-53
633PI_TOO_MANY_TAGS =-54
634PI_BAD_SCRIPT_CMD =-55
635PI_BAD_VAR_NUM =-56
636PI_NO_SCRIPT_ROOM =-57
637PI_NO_MEMORY =-58
638PI_SOCK_READ_FAILED =-59
639PI_SOCK_WRIT_FAILED =-60
640PI_TOO_MANY_PARAM =-61
641PI_SCRIPT_NOT_READY =-62
642PI_BAD_TAG =-63
643PI_BAD_MICS_DELAY =-64
644PI_BAD_MILS_DELAY =-65
645PI_BAD_WAVE_ID =-66
646PI_TOO_MANY_CBS =-67
647PI_TOO_MANY_OOL =-68
648PI_EMPTY_WAVEFORM =-69
649PI_NO_WAVEFORM_ID =-70
650PI_I2C_OPEN_FAILED =-71
651PI_SER_OPEN_FAILED =-72
652PI_SPI_OPEN_FAILED =-73
653PI_BAD_I2C_BUS =-74
654PI_BAD_I2C_ADDR =-75
655PI_BAD_SPI_CHANNEL =-76
656PI_BAD_FLAGS =-77
657PI_BAD_SPI_SPEED =-78
658PI_BAD_SER_DEVICE =-79
659PI_BAD_SER_SPEED =-80
660PI_BAD_PARAM =-81
661PI_I2C_WRITE_FAILED =-82
662PI_I2C_READ_FAILED =-83
663PI_BAD_SPI_COUNT =-84
664PI_SER_WRITE_FAILED =-85
665PI_SER_READ_FAILED =-86
666PI_SER_READ_NO_DATA =-87
667PI_UNKNOWN_COMMAND =-88
668PI_SPI_XFER_FAILED =-89
669_PI_BAD_POINTER =-90
670PI_NO_AUX_SPI =-91
671PI_NOT_PWM_GPIO =-92
672PI_NOT_SERVO_GPIO =-93
673PI_NOT_HCLK_GPIO =-94
674PI_NOT_HPWM_GPIO =-95
675PI_BAD_HPWM_FREQ =-96
676PI_BAD_HPWM_DUTY =-97
677PI_BAD_HCLK_FREQ =-98
678PI_BAD_HCLK_PASS =-99
679PI_HPWM_ILLEGAL =-100
680PI_BAD_DATABITS =-101
681PI_BAD_STOPBITS =-102
682PI_MSG_TOOBIG =-103
683PI_BAD_MALLOC_MODE =-104
684_PI_TOO_MANY_SEGS =-105
685_PI_BAD_I2C_SEG =-106
686PI_BAD_SMBUS_CMD =-107
687PI_NOT_I2C_GPIO =-108
688PI_BAD_I2C_WLEN =-109
689PI_BAD_I2C_RLEN =-110
690PI_BAD_I2C_CMD =-111
691PI_BAD_I2C_BAUD =-112
692PI_CHAIN_LOOP_CNT =-113
693PI_BAD_CHAIN_LOOP =-114
694PI_CHAIN_COUNTER =-115
695PI_BAD_CHAIN_CMD =-116
696PI_BAD_CHAIN_DELAY =-117
697PI_CHAIN_NESTING =-118
698PI_CHAIN_TOO_BIG =-119
699PI_DEPRECATED =-120
700PI_BAD_SER_INVERT =-121
701_PI_BAD_EDGE =-122
702_PI_BAD_ISR_INIT =-123
703PI_BAD_FOREVER =-124
704PI_BAD_FILTER =-125
705PI_BAD_PAD =-126
706PI_BAD_STRENGTH =-127
707PI_FIL_OPEN_FAILED =-128
708PI_BAD_FILE_MODE =-129
709PI_BAD_FILE_FLAG =-130
710PI_BAD_FILE_READ =-131
711PI_BAD_FILE_WRITE =-132
712PI_FILE_NOT_ROPEN =-133
713PI_FILE_NOT_WOPEN =-134
714PI_BAD_FILE_SEEK =-135
715PI_NO_FILE_MATCH =-136
716PI_NO_FILE_ACCESS =-137
717PI_FILE_IS_A_DIR =-138
718PI_BAD_SHELL_STATUS =-139
719PI_BAD_SCRIPT_NAME =-140
720PI_BAD_SPI_BAUD =-141
721PI_NOT_SPI_GPIO =-142
722PI_BAD_EVENT_ID =-143
723PI_CMD_INTERRUPTED =-144
724PI_NOT_ON_BCM2711 =-145
725PI_ONLY_ON_BCM2711 =-146
727# pigpio error text
729_errors=[
730 [_PI_INIT_FAILED , "pigpio initialisation failed"],
731 [PI_BAD_USER_GPIO , "GPIO not 0-31"],
732 [PI_BAD_GPIO , "GPIO not 0-53"],
733 [PI_BAD_MODE , "mode not 0-7"],
734 [PI_BAD_LEVEL , "level not 0-1"],
735 [PI_BAD_PUD , "pud not 0-2"],
736 [PI_BAD_PULSEWIDTH , "pulsewidth not 0 or 500-2500"],
737 [PI_BAD_DUTYCYCLE , "dutycycle not 0-range (default 255)"],
738 [_PI_BAD_TIMER , "timer not 0-9"],
739 [_PI_BAD_MS , "ms not 10-60000"],
740 [_PI_BAD_TIMETYPE , "timetype not 0-1"],
741 [_PI_BAD_SECONDS , "seconds < 0"],
742 [_PI_BAD_MICROS , "micros not 0-999999"],
743 [_PI_TIMER_FAILED , "gpioSetTimerFunc failed"],
744 [PI_BAD_WDOG_TIMEOUT , "timeout not 0-60000"],
745 [_PI_NO_ALERT_FUNC , "DEPRECATED"],
746 [_PI_BAD_CLK_PERIPH , "clock peripheral not 0-1"],
747 [_PI_BAD_CLK_SOURCE , "DEPRECATED"],
748 [_PI_BAD_CLK_MICROS , "clock micros not 1, 2, 4, 5, 8, or 10"],
749 [_PI_BAD_BUF_MILLIS , "buf millis not 100-10000"],
750 [PI_BAD_DUTYRANGE , "dutycycle range not 25-40000"],
751 [_PI_BAD_SIGNUM , "signum not 0-63"],
752 [_PI_BAD_PATHNAME , "can't open pathname"],
753 [PI_NO_HANDLE , "no handle available"],
754 [PI_BAD_HANDLE , "unknown handle"],
755 [_PI_BAD_IF_FLAGS , "ifFlags > 4"],
756 [_PI_BAD_CHANNEL , "DMA channel not 0-14"],
757 [_PI_BAD_SOCKET_PORT , "socket port not 1024-30000"],
758 [_PI_BAD_FIFO_COMMAND , "unknown fifo command"],
759 [_PI_BAD_SECO_CHANNEL , "DMA secondary channel not 0-14"],
760 [_PI_NOT_INITIALISED , "function called before gpioInitialise"],
761 [_PI_INITIALISED , "function called after gpioInitialise"],
762 [_PI_BAD_WAVE_MODE , "waveform mode not 0-1"],
763 [_PI_BAD_CFG_INTERNAL , "bad parameter in gpioCfgInternals call"],
764 [PI_BAD_WAVE_BAUD , "baud rate not 50-250000(RX)/1000000(TX)"],
765 [PI_TOO_MANY_PULSES , "waveform has too many pulses"],
766 [PI_TOO_MANY_CHARS , "waveform has too many chars"],
767 [PI_NOT_SERIAL_GPIO , "no bit bang serial read in progress on GPIO"],
768 [PI_NOT_PERMITTED , "no permission to update GPIO"],
769 [PI_SOME_PERMITTED , "no permission to update one or more GPIO"],
770 [PI_BAD_WVSC_COMMND , "bad WVSC subcommand"],
771 [PI_BAD_WVSM_COMMND , "bad WVSM subcommand"],
772 [PI_BAD_WVSP_COMMND , "bad WVSP subcommand"],
773 [PI_BAD_PULSELEN , "trigger pulse length not 1-100"],
774 [PI_BAD_SCRIPT , "invalid script"],
775 [PI_BAD_SCRIPT_ID , "unknown script id"],
776 [PI_BAD_SER_OFFSET , "add serial data offset > 30 minute"],
777 [PI_GPIO_IN_USE , "GPIO already in use"],
778 [PI_BAD_SERIAL_COUNT , "must read at least a byte at a time"],
779 [PI_BAD_PARAM_NUM , "script parameter id not 0-9"],
780 [PI_DUP_TAG , "script has duplicate tag"],
781 [PI_TOO_MANY_TAGS , "script has too many tags"],
782 [PI_BAD_SCRIPT_CMD , "illegal script command"],
783 [PI_BAD_VAR_NUM , "script variable id not 0-149"],
784 [PI_NO_SCRIPT_ROOM , "no more room for scripts"],
785 [PI_NO_MEMORY , "can't allocate temporary memory"],
786 [PI_SOCK_READ_FAILED , "socket read failed"],
787 [PI_SOCK_WRIT_FAILED , "socket write failed"],
788 [PI_TOO_MANY_PARAM , "too many script parameters (> 10)"],
789 [PI_SCRIPT_NOT_READY , "script initialising"],
790 [PI_BAD_TAG , "script has unresolved tag"],
791 [PI_BAD_MICS_DELAY , "bad MICS delay (too large)"],
792 [PI_BAD_MILS_DELAY , "bad MILS delay (too large)"],
793 [PI_BAD_WAVE_ID , "non existent wave id"],
794 [PI_TOO_MANY_CBS , "No more CBs for waveform"],
795 [PI_TOO_MANY_OOL , "No more OOL for waveform"],
796 [PI_EMPTY_WAVEFORM , "attempt to create an empty waveform"],
797 [PI_NO_WAVEFORM_ID , "No more waveform ids"],
798 [PI_I2C_OPEN_FAILED , "can't open I2C device"],
799 [PI_SER_OPEN_FAILED , "can't open serial device"],
800 [PI_SPI_OPEN_FAILED , "can't open SPI device"],
801 [PI_BAD_I2C_BUS , "bad I2C bus"],
802 [PI_BAD_I2C_ADDR , "bad I2C address"],
803 [PI_BAD_SPI_CHANNEL , "bad SPI channel"],
804 [PI_BAD_FLAGS , "bad i2c/spi/ser open flags"],
805 [PI_BAD_SPI_SPEED , "bad SPI speed"],
806 [PI_BAD_SER_DEVICE , "bad serial device name"],
807 [PI_BAD_SER_SPEED , "bad serial baud rate"],
808 [PI_BAD_PARAM , "bad i2c/spi/ser parameter"],
809 [PI_I2C_WRITE_FAILED , "I2C write failed"],
810 [PI_I2C_READ_FAILED , "I2C read failed"],
811 [PI_BAD_SPI_COUNT , "bad SPI count"],
812 [PI_SER_WRITE_FAILED , "ser write failed"],
813 [PI_SER_READ_FAILED , "ser read failed"],
814 [PI_SER_READ_NO_DATA , "ser read no data available"],
815 [PI_UNKNOWN_COMMAND , "unknown command"],
816 [PI_SPI_XFER_FAILED , "SPI xfer/read/write failed"],
817 [_PI_BAD_POINTER , "bad (NULL) pointer"],
818 [PI_NO_AUX_SPI , "no auxiliary SPI on Pi A or B"],
819 [PI_NOT_PWM_GPIO , "GPIO is not in use for PWM"],
820 [PI_NOT_SERVO_GPIO , "GPIO is not in use for servo pulses"],
821 [PI_NOT_HCLK_GPIO , "GPIO has no hardware clock"],
822 [PI_NOT_HPWM_GPIO , "GPIO has no hardware PWM"],
823 [PI_BAD_HPWM_FREQ , "invalid hardware PWM frequency"],
824 [PI_BAD_HPWM_DUTY , "hardware PWM dutycycle not 0-1M"],
825 [PI_BAD_HCLK_FREQ , "invalid hardware clock frequency"],
826 [PI_BAD_HCLK_PASS , "need password to use hardware clock 1"],
827 [PI_HPWM_ILLEGAL , "illegal, PWM in use for main clock"],
828 [PI_BAD_DATABITS , "serial data bits not 1-32"],
829 [PI_BAD_STOPBITS , "serial (half) stop bits not 2-8"],
830 [PI_MSG_TOOBIG , "socket/pipe message too big"],
831 [PI_BAD_MALLOC_MODE , "bad memory allocation mode"],
832 [_PI_TOO_MANY_SEGS , "too many I2C transaction segments"],
833 [_PI_BAD_I2C_SEG , "an I2C transaction segment failed"],
834 [PI_BAD_SMBUS_CMD , "SMBus command not supported"],
835 [PI_NOT_I2C_GPIO , "no bit bang I2C in progress on GPIO"],
836 [PI_BAD_I2C_WLEN , "bad I2C write length"],
837 [PI_BAD_I2C_RLEN , "bad I2C read length"],
838 [PI_BAD_I2C_CMD , "bad I2C command"],
839 [PI_BAD_I2C_BAUD , "bad I2C baud rate, not 50-500k"],
840 [PI_CHAIN_LOOP_CNT , "bad chain loop count"],
841 [PI_BAD_CHAIN_LOOP , "empty chain loop"],
842 [PI_CHAIN_COUNTER , "too many chain counters"],
843 [PI_BAD_CHAIN_CMD , "bad chain command"],
844 [PI_BAD_CHAIN_DELAY , "bad chain delay micros"],
845 [PI_CHAIN_NESTING , "chain counters nested too deeply"],
846 [PI_CHAIN_TOO_BIG , "chain is too long"],
847 [PI_DEPRECATED , "deprecated function removed"],
848 [PI_BAD_SER_INVERT , "bit bang serial invert not 0 or 1"],
849 [_PI_BAD_EDGE , "bad ISR edge value, not 0-2"],
850 [_PI_BAD_ISR_INIT , "bad ISR initialisation"],
851 [PI_BAD_FOREVER , "loop forever must be last chain command"],
852 [PI_BAD_FILTER , "bad filter parameter"],
853 [PI_BAD_PAD , "bad pad number"],
854 [PI_BAD_STRENGTH , "bad pad drive strength"],
855 [PI_FIL_OPEN_FAILED , "file open failed"],
856 [PI_BAD_FILE_MODE , "bad file mode"],
857 [PI_BAD_FILE_FLAG , "bad file flag"],
858 [PI_BAD_FILE_READ , "bad file read"],
859 [PI_BAD_FILE_WRITE , "bad file write"],
860 [PI_FILE_NOT_ROPEN , "file not open for read"],
861 [PI_FILE_NOT_WOPEN , "file not open for write"],
862 [PI_BAD_FILE_SEEK , "bad file seek"],
863 [PI_NO_FILE_MATCH , "no files match pattern"],
864 [PI_NO_FILE_ACCESS , "no permission to access file"],
865 [PI_FILE_IS_A_DIR , "file is a directory"],
866 [PI_BAD_SHELL_STATUS , "bad shell return status"],
867 [PI_BAD_SCRIPT_NAME , "bad script name"],
868 [PI_BAD_SPI_BAUD , "bad SPI baud rate, not 50-500k"],
869 [PI_NOT_SPI_GPIO , "no bit bang SPI in progress on GPIO"],
870 [PI_BAD_EVENT_ID , "bad event id"],
871 [PI_CMD_INTERRUPTED , "pigpio command interrupted"],
872 [PI_NOT_ON_BCM2711 , "not available on BCM2711"],
873 [PI_ONLY_ON_BCM2711 , "only available on BCM2711"],
874]
876_except_a = "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n{}"
878_except_z = "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
880_except_1 = """
881Did you start the pigpio daemon? E.g. sudo pigpiod
883Did you specify the correct Pi host/port in the environment
884variables PIGPIO_ADDR/PIGPIO_PORT?
885E.g. export PIGPIO_ADDR=soft, export PIGPIO_PORT=8888
887Did you specify the correct Pi host/port in the
888pigpio.pi() function? E.g. pigpio.pi('soft', 8888)"""
890_except_2 = """
891Do you have permission to access the pigpio daemon?
892Perhaps it was started with sudo pigpiod -nlocalhost"""
894_except_3 = """
895Can't create callback thread.
896Perhaps too many simultaneous pigpio connections."""
898class _socklock:
899 """
900 A class to store socket and lock.
901 """
902 def __init__(self):
903 self.s = None
904 self.l = threading.Lock()
906class error(Exception):
907 """pigpio module exception"""
908 def __init__(self, value):
909 self.value = value
910 def __str__(self):
911 return repr(self.value)
913class pulse:
914 """
915 A class to store pulse information.
916 """
918 def __init__(self, gpio_on, gpio_off, delay):
919 """
920 Initialises a pulse.
922 gpio_on:= the GPIO to switch on at the start of the pulse.
923 gpio_off:= the GPIO to switch off at the start of the pulse.
924 delay:= the delay in microseconds before the next pulse.
926 """
927 self.gpio_on = gpio_on
928 self.gpio_off = gpio_off
929 self.delay = delay
931def error_text(errnum):
932 """
933 Returns a text description of a pigpio error.
935 errnum:= <0, the error number
937 ...
938 print(pigpio.error_text(-5))
939 level not 0-1
940 ...
941 """
942 for e in _errors:
943 if e[0] == errnum:
944 return e[1]
945 return "unknown error ({})".format(errnum)
947def tickDiff(t1, t2):
948 """
949 Returns the microsecond difference between two ticks.
951 t1:= the earlier tick
952 t2:= the later tick
954 ...
955 print(pigpio.tickDiff(4294967272, 12))
956 36
957 ...
958 """
959 tDiff = t2 - t1
960 if tDiff < 0:
961 tDiff += (1 << 32)
962 return tDiff
964# A couple of hacks to cope with different string handling
965# between various Python versions
966# 3 != 2.7.8 != 2.7.3
968if sys.hexversion < 0x03000000: 968 ↛ 969line 968 didn't jump to line 969, because the condition on line 968 was never true
969 def _b(x):
970 return x
971else:
972 def _b(x):
973 return x.encode('latin-1')
975if sys.hexversion < 0x02070800: 975 ↛ 976line 975 didn't jump to line 976, because the condition on line 975 was never true
976 def _str(x):
977 return buffer(x)
978else:
979 def _str(x):
980 return x
982def u2i(uint32):
983 """
984 Converts a 32 bit unsigned number to signed.
986 uint32:= an unsigned 32 bit number
988 ...
989 print(u2i(4294967272))
990 -24
991 print(u2i(37))
992 37
993 ...
994 """
995 mask = (2 ** 32) - 1
996 if uint32 & (1 << 31):
997 v = uint32 | ~mask
998 else:
999 v = uint32 & mask
1000 return v
1002def _u2i(uint32):
1003 """
1004 Converts a 32 bit unsigned number to signed. If the number
1005 is negative it indicates an error. On error a pigpio
1006 exception will be raised if exceptions is True.
1007 """
1008 v = u2i(uint32)
1009 if v < 0:
1010 if exceptions:
1011 raise error(error_text(v))
1012 return v
1014def _pigpio_command(sl, cmd, p1, p2):
1015 """
1016 Runs a pigpio socket command.
1018 sl:= command socket and lock.
1019 cmd:= the command to be executed.
1020 p1:= command parameter 1 (if applicable).
1021 p2:= command parameter 2 (if applicable).
1022 """
1023 res = PI_CMD_INTERRUPTED
1024 with sl.l:
1025 sl.s.send(struct.pack('IIII', cmd, p1, p2, 0))
1026 dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
1027 return res
1029def _pigpio_command_nolock(sl, cmd, p1, p2):
1030 """
1031 Runs a pigpio socket command.
1033 sl:= command socket and lock.
1034 cmd:= the command to be executed.
1035 p1:= command parameter 1 (if applicable).
1036 p2:= command parameter 2 (if applicable).
1037 """
1038 res = PI_CMD_INTERRUPTED
1039 sl.s.send(struct.pack('IIII', cmd, p1, p2, 0))
1040 dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
1041 return res
1043def _pigpio_command_ext(sl, cmd, p1, p2, p3, extents):
1044 """
1045 Runs an extended pigpio socket command.
1047 sl:= command socket and lock.
1048 cmd:= the command to be executed.
1049 p1:= command parameter 1 (if applicable).
1050 p2:= command parameter 2 (if applicable).
1051 p3:= total size in bytes of following extents
1052 extents:= additional data blocks
1053 """
1054 ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
1055 for x in extents:
1056 if type(x) == type(""):
1057 ext.extend(_b(x))
1058 else:
1059 ext.extend(x)
1060 res = PI_CMD_INTERRUPTED
1061 with sl.l:
1062 sl.s.sendall(ext)
1063 dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
1064 return res
1066def _pigpio_command_ext_nolock(sl, cmd, p1, p2, p3, extents):
1067 """
1068 Runs an extended pigpio socket command.
1070 sl:= command socket and lock.
1071 cmd:= the command to be executed.
1072 p1:= command parameter 1 (if applicable).
1073 p2:= command parameter 2 (if applicable).
1074 p3:= total size in bytes of following extents
1075 extents:= additional data blocks
1076 """
1077 res = PI_CMD_INTERRUPTED
1078 ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
1079 for x in extents:
1080 if type(x) == type(""):
1081 ext.extend(_b(x))
1082 else:
1083 ext.extend(x)
1084 sl.s.sendall(ext)
1085 dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
1086 return res
1088class _event_ADT:
1089 """
1090 An ADT class to hold event callback information.
1091 """
1093 def __init__(self, event, func):
1094 """
1095 Initialises an event callback ADT.
1097 event:= the event id.
1098 func:= a user function taking one argument, the event id.
1099 """
1100 self.event = event
1101 self.func = func
1102 self.bit = 1<<event
1104class _callback_ADT:
1105 """An ADT class to hold callback information."""
1107 def __init__(self, gpio, edge, func):
1108 """
1109 Initialises a callback ADT.
1111 gpio:= Broadcom GPIO number.
1112 edge:= EITHER_EDGE, RISING_EDGE, or FALLING_EDGE.
1113 func:= a user function taking three arguments (GPIO, level, tick).
1114 """
1115 self.gpio = gpio
1116 self.edge = edge
1117 self.func = func
1118 self.bit = 1<<gpio
1120class _callback_thread(threading.Thread):
1121 """A class to encapsulate pigpio notification callbacks."""
1122 def __init__(self, control, host, port):
1123 """Initialises notifications."""
1124 threading.Thread.__init__(self)
1125 self.control = control
1126 self.sl = _socklock()
1127 self.go = False
1128 self.daemon = True
1129 self.monitor = 0
1130 self.event_bits = 0
1131 self.callbacks = []
1132 self.events = []
1133 self.sl.s = socket.create_connection((host, port), None)
1134 self.lastLevel = _pigpio_command(self.sl, _PI_CMD_BR1, 0, 0)
1135 self.handle = _u2i(_pigpio_command(self.sl, _PI_CMD_NOIB, 0, 0))
1136 self.go = True
1137 self.start()
1139 def stop(self):
1140 """Stops notifications."""
1141 if self.go:
1142 self.go = False
1143 self.sl.s.send(struct.pack('IIII', _PI_CMD_NC, self.handle, 0, 0))
1145 def append(self, callb):
1146 """Adds a callback to the notification thread."""
1147 self.callbacks.append(callb)
1148 self.monitor = self.monitor | callb.bit
1149 _pigpio_command(self.control, _PI_CMD_NB, self.handle, self.monitor)
1151 def remove(self, callb):
1152 """Removes a callback from the notification thread."""
1153 if callb in self.callbacks:
1154 self.callbacks.remove(callb)
1155 newMonitor = 0
1156 for c in self.callbacks:
1157 newMonitor |= c.bit
1158 if newMonitor != self.monitor:
1159 self.monitor = newMonitor
1160 _pigpio_command(
1161 self.control, _PI_CMD_NB, self.handle, self.monitor)
1163 def append_event(self, callb):
1164 """
1165 Adds an event callback to the notification thread.
1166 """
1167 self.events.append(callb)
1168 self.event_bits = self.event_bits | callb.bit
1169 _pigpio_command(self.control, _PI_CMD_EVM, self.handle, self.event_bits)
1171 def remove_event(self, callb):
1172 """
1173 Removes an event callback from the notification thread.
1174 """
1175 if callb in self.events:
1176 self.events.remove(callb)
1177 new_event_bits = 0
1178 for c in self.events:
1179 new_event_bits |= c.bit
1180 if new_event_bits != self.event_bits:
1181 self.event_bits = new_event_bits
1182 _pigpio_command(
1183 self.control, _PI_CMD_EVM, self.handle, self.event_bits)
1185 def run(self):
1186 """Runs the notification thread."""
1188 lastLevel = self.lastLevel
1190 RECV_SIZ = 4096
1191 MSG_SIZ = 12
1193 buf = bytes()
1194 while self.go:
1196 buf += self.sl.s.recv(RECV_SIZ)
1197 offset = 0
1199 while self.go and (len(buf) - offset) >= MSG_SIZ:
1200 msgbuf = buf[offset:offset + MSG_SIZ]
1201 offset += MSG_SIZ
1202 seq, flags, tick, level = (struct.unpack('HHII', msgbuf))
1204 if flags == 0:
1205 changed = level ^ lastLevel
1206 lastLevel = level
1207 for cb in self.callbacks:
1208 if cb.bit & changed:
1209 newLevel = 0
1210 if cb.bit & level:
1211 newLevel = 1
1212 if (cb.edge ^ newLevel):
1213 cb.func(cb.gpio, newLevel, tick)
1214 else:
1215 if flags & NTFY_FLAGS_WDOG:
1216 gpio = flags & NTFY_FLAGS_GPIO
1217 for cb in self.callbacks:
1218 if cb.gpio == gpio:
1219 cb.func(gpio, TIMEOUT, tick)
1220 elif flags & NTFY_FLAGS_EVENT:
1221 event = flags & NTFY_FLAGS_GPIO
1222 for cb in self.events:
1223 if cb.event == event:
1224 cb.func(event, tick)
1225 buf = buf[offset:]
1227 self.sl.s.close()
1229class _callback:
1230 """A class to provide GPIO level change callbacks."""
1232 def __init__(self, notify, user_gpio, edge=RISING_EDGE, func=None):
1233 """
1234 Initialise a callback and adds it to the notification thread.
1235 """
1236 self._notify = notify
1237 self.count=0
1238 self._reset = False
1239 if func is None:
1240 func=self._tally
1241 self.callb = _callback_ADT(user_gpio, edge, func)
1242 self._notify.append(self.callb)
1244 def cancel(self):
1245 """Cancels a callback by removing it from the notification thread."""
1246 self._notify.remove(self.callb)
1248 def _tally(self, user_gpio, level, tick):
1249 """Increment the callback called count."""
1250 if self._reset:
1251 self._reset = False
1252 self.count = 0
1253 self.count += 1
1255 def tally(self):
1256 """
1257 Provides a count of how many times the default tally
1258 callback has triggered.
1260 The count will be zero if the user has supplied their own
1261 callback function.
1262 """
1263 return self.count
1265 def reset_tally(self):
1266 """
1267 Resets the tally count to zero.
1268 """
1269 self._reset = True
1270 self.count = 0
1272class _event:
1273 """A class to provide event callbacks."""
1275 def __init__(self, notify, event, func=None):
1276 """
1277 Initialise an event and adds it to the notification thread.
1278 """
1279 self._notify = notify
1280 self.count=0
1281 self._reset = False
1282 if func is None:
1283 func=self._tally
1284 self.callb = _event_ADT(event, func)
1285 self._notify.append_event(self.callb)
1287 def cancel(self):
1288 """
1289 Cancels a event callback by removing it from the
1290 notification thread.
1291 """
1292 self._notify.remove_event(self.callb)
1294 def _tally(self, event, tick):
1295 """Increment the event callback called count."""
1296 if self._reset:
1297 self._reset = False
1298 self.count = 0
1299 self.count += 1
1301 def tally(self):
1302 """
1303 Provides a count of how many times the default tally
1304 callback has triggered.
1306 The count will be zero if the user has supplied their own
1307 callback function.
1308 """
1309 return self.count
1311 def reset_tally(self):
1312 """
1313 Resets the tally count to zero.
1314 """
1315 self._reset = True
1316 self.count = 0
1318class _wait_for_edge:
1319 """Encapsulates waiting for GPIO edges."""
1321 def __init__(self, notify, gpio, edge, timeout):
1322 """Initialises a wait_for_edge."""
1323 self._notify = notify
1324 self.callb = _callback_ADT(gpio, edge, self.func)
1325 self.trigger = False
1326 self._notify.append(self.callb)
1327 self.start = time.time()
1328 while (self.trigger == False) and ((time.time()-self.start) < timeout):
1329 time.sleep(0.05)
1330 self._notify.remove(self.callb)
1332 def func(self, gpio, level, tick):
1333 """Sets wait_for_edge triggered."""
1334 self.trigger = True
1336class _wait_for_event:
1337 """Encapsulates waiting for an event."""
1339 def __init__(self, notify, event, timeout):
1340 """Initialises wait_for_event."""
1341 self._notify = notify
1342 self.callb = _event_ADT(event, self.func)
1343 self.trigger = False
1344 self._notify.append_event(self.callb)
1345 self.start = time.time()
1346 while (self.trigger == False) and ((time.time()-self.start) < timeout):
1347 time.sleep(0.05)
1348 self._notify.remove_event(self.callb)
1350 def func(self, event, tick):
1351 """Sets wait_for_event triggered."""
1352 self.trigger = True
1354class pi():
1356 def _rxbuf(self, count):
1357 """Returns count bytes from the command socket."""
1358 ext = bytearray(self.sl.s.recv(count))
1359 while len(ext) < count:
1360 ext.extend(self.sl.s.recv(count - len(ext)))
1361 return ext
1363 def set_mode(self, gpio, mode):
1364 """
1365 Sets the GPIO mode.
1367 gpio:= 0-53.
1368 mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
1370 ...
1371 pi.set_mode( 4, pigpio.INPUT) # GPIO 4 as input
1372 pi.set_mode(17, pigpio.OUTPUT) # GPIO 17 as output
1373 pi.set_mode(24, pigpio.ALT2) # GPIO 24 as ALT2
1374 ...
1375 """
1376 return _u2i(_pigpio_command(self.sl, _PI_CMD_MODES, gpio, mode))
1378 def get_mode(self, gpio):
1379 """
1380 Returns the GPIO mode.
1382 gpio:= 0-53.
1384 Returns a value as follows
1386 . .
1387 0 = INPUT
1388 1 = OUTPUT
1389 2 = ALT5
1390 3 = ALT4
1391 4 = ALT0
1392 5 = ALT1
1393 6 = ALT2
1394 7 = ALT3
1395 . .
1397 ...
1398 print(pi.get_mode(0))
1399 4
1400 ...
1401 """
1402 return _u2i(_pigpio_command(self.sl, _PI_CMD_MODEG, gpio, 0))
1404 def set_pull_up_down(self, gpio, pud):
1405 """
1406 Sets or clears the internal GPIO pull-up/down resistor.
1408 gpio:= 0-53.
1409 pud:= PUD_UP, PUD_DOWN, PUD_OFF.
1411 ...
1412 pi.set_pull_up_down(17, pigpio.PUD_OFF)
1413 pi.set_pull_up_down(23, pigpio.PUD_UP)
1414 pi.set_pull_up_down(24, pigpio.PUD_DOWN)
1415 ...
1416 """
1417 return _u2i(_pigpio_command(self.sl, _PI_CMD_PUD, gpio, pud))
1419 def read(self, gpio):
1420 """
1421 Returns the GPIO level.
1423 gpio:= 0-53.
1425 ...
1426 pi.set_mode(23, pigpio.INPUT)
1428 pi.set_pull_up_down(23, pigpio.PUD_DOWN)
1429 print(pi.read(23))
1430 0
1432 pi.set_pull_up_down(23, pigpio.PUD_UP)
1433 print(pi.read(23))
1434 1
1435 ...
1436 """
1437 return _u2i(_pigpio_command(self.sl, _PI_CMD_READ, gpio, 0))
1439 def write(self, gpio, level):
1440 """
1441 Sets the GPIO level.
1443 GPIO:= 0-53.
1444 level:= 0, 1.
1446 If PWM or servo pulses are active on the GPIO they are
1447 switched off.
1449 ...
1450 pi.set_mode(17, pigpio.OUTPUT)
1452 pi.write(17,0)
1453 print(pi.read(17))
1454 0
1456 pi.write(17,1)
1457 print(pi.read(17))
1458 1
1459 ...
1460 """
1461 return _u2i(_pigpio_command(self.sl, _PI_CMD_WRITE, gpio, level))
1463 def set_PWM_dutycycle(self, user_gpio, dutycycle):
1464 """
1465 Starts (non-zero dutycycle) or stops (0) PWM pulses on the GPIO.
1467 user_gpio:= 0-31.
1468 dutycycle:= 0-range (range defaults to 255).
1470 The [*set_PWM_range*] function can change the default range of 255.
1472 ...
1473 pi.set_PWM_dutycycle(4, 0) # PWM off
1474 pi.set_PWM_dutycycle(4, 64) # PWM 1/4 on
1475 pi.set_PWM_dutycycle(4, 128) # PWM 1/2 on
1476 pi.set_PWM_dutycycle(4, 192) # PWM 3/4 on
1477 pi.set_PWM_dutycycle(4, 255) # PWM full on
1478 ...
1479 """
1480 return _u2i(_pigpio_command(
1481 self.sl, _PI_CMD_PWM, user_gpio, int(dutycycle)))
1483 def get_PWM_dutycycle(self, user_gpio):
1484 """
1485 Returns the PWM dutycycle being used on the GPIO.
1487 user_gpio:= 0-31.
1489 Returns the PWM dutycycle.
1492 For normal PWM the dutycycle will be out of the defined range
1493 for the GPIO (see [*get_PWM_range*]).
1495 If a hardware clock is active on the GPIO the reported
1496 dutycycle will be 500000 (500k) out of 1000000 (1M).
1498 If hardware PWM is active on the GPIO the reported dutycycle
1499 will be out of a 1000000 (1M).
1501 ...
1502 pi.set_PWM_dutycycle(4, 25)
1503 print(pi.get_PWM_dutycycle(4))
1504 25
1506 pi.set_PWM_dutycycle(4, 203)
1507 print(pi.get_PWM_dutycycle(4))
1508 203
1509 ...
1510 """
1511 return _u2i(_pigpio_command(self.sl, _PI_CMD_GDC, user_gpio, 0))
1513 def set_PWM_range(self, user_gpio, range_):
1514 """
1515 Sets the range of PWM values to be used on the GPIO.
1517 user_gpio:= 0-31.
1518 range_:= 25-40000.
1520 ...
1521 pi.set_PWM_range(9, 100) # now 25 1/4, 50 1/2, 75 3/4 on
1522 pi.set_PWM_range(9, 500) # now 125 1/4, 250 1/2, 375 3/4 on
1523 pi.set_PWM_range(9, 3000) # now 750 1/4, 1500 1/2, 2250 3/4 on
1524 ...
1525 """
1526 return _u2i(_pigpio_command(self.sl, _PI_CMD_PRS, user_gpio, range_))
1528 def get_PWM_range(self, user_gpio):
1529 """
1530 Returns the range of PWM values being used on the GPIO.
1532 user_gpio:= 0-31.
1534 If a hardware clock or hardware PWM is active on the GPIO
1535 the reported range will be 1000000 (1M).
1537 ...
1538 pi.set_PWM_range(9, 500)
1539 print(pi.get_PWM_range(9))
1540 500
1541 ...
1542 """
1543 return _u2i(_pigpio_command(self.sl, _PI_CMD_PRG, user_gpio, 0))
1545 def get_PWM_real_range(self, user_gpio):
1546 """
1547 Returns the real (underlying) range of PWM values being
1548 used on the GPIO.
1550 user_gpio:= 0-31.
1552 If a hardware clock is active on the GPIO the reported
1553 real range will be 1000000 (1M).
1555 If hardware PWM is active on the GPIO the reported real range
1556 will be approximately 250M divided by the set PWM frequency.
1558 ...
1559 pi.set_PWM_frequency(4, 800)
1560 print(pi.get_PWM_real_range(4))
1561 250
1562 ...
1563 """
1564 return _u2i(_pigpio_command(self.sl, _PI_CMD_PRRG, user_gpio, 0))
1566 def set_PWM_frequency(self, user_gpio, frequency):
1567 """
1568 Sets the frequency (in Hz) of the PWM to be used on the GPIO.
1570 user_gpio:= 0-31.
1571 frequency:= >=0 Hz
1573 Returns the numerically closest frequency if OK, otherwise
1574 PI_BAD_USER_GPIO or PI_NOT_PERMITTED.
1576 If PWM is currently active on the GPIO it will be switched
1577 off and then back on at the new frequency.
1579 Each GPIO can be independently set to one of 18 different
1580 PWM frequencies.
1582 The selectable frequencies depend upon the sample rate which
1583 may be 1, 2, 4, 5, 8, or 10 microseconds (default 5). The
1584 sample rate is set when the pigpio daemon is started.
1586 The frequencies for each sample rate are:
1588 . .
1589 Hertz
1591 1: 40000 20000 10000 8000 5000 4000 2500 2000 1600
1592 1250 1000 800 500 400 250 200 100 50
1594 2: 20000 10000 5000 4000 2500 2000 1250 1000 800
1595 625 500 400 250 200 125 100 50 25
1597 4: 10000 5000 2500 2000 1250 1000 625 500 400
1598 313 250 200 125 100 63 50 25 13
1599 sample
1600 rate
1601 (us) 5: 8000 4000 2000 1600 1000 800 500 400 320
1602 250 200 160 100 80 50 40 20 10
1604 8: 5000 2500 1250 1000 625 500 313 250 200
1605 156 125 100 63 50 31 25 13 6
1607 10: 4000 2000 1000 800 500 400 250 200 160
1608 125 100 80 50 40 25 20 10 5
1609 . .
1611 ...
1612 pi.set_PWM_frequency(4,0)
1613 print(pi.get_PWM_frequency(4))
1614 10
1616 pi.set_PWM_frequency(4,100000)
1617 print(pi.get_PWM_frequency(4))
1618 8000
1619 ...
1620 """
1621 return _u2i(
1622 _pigpio_command(self.sl, _PI_CMD_PFS, user_gpio, frequency))
1624 def get_PWM_frequency(self, user_gpio):
1625 """
1626 Returns the frequency of PWM being used on the GPIO.
1628 user_gpio:= 0-31.
1630 Returns the frequency (in Hz) used for the GPIO.
1632 For normal PWM the frequency will be that defined for the GPIO
1633 by [*set_PWM_frequency*].
1635 If a hardware clock is active on the GPIO the reported frequency
1636 will be that set by [*hardware_clock*].
1638 If hardware PWM is active on the GPIO the reported frequency
1639 will be that set by [*hardware_PWM*].
1641 ...
1642 pi.set_PWM_frequency(4,0)
1643 print(pi.get_PWM_frequency(4))
1644 10
1646 pi.set_PWM_frequency(4, 800)
1647 print(pi.get_PWM_frequency(4))
1648 800
1649 ...
1650 """
1651 return _u2i(_pigpio_command(self.sl, _PI_CMD_PFG, user_gpio, 0))
1653 def set_servo_pulsewidth(self, user_gpio, pulsewidth):
1654 """
1655 Starts (500-2500) or stops (0) servo pulses on the GPIO.
1657 user_gpio:= 0-31.
1658 pulsewidth:= 0 (off),
1659 500 (most anti-clockwise) - 2500 (most clockwise).
1661 The selected pulsewidth will continue to be transmitted until
1662 changed by a subsequent call to set_servo_pulsewidth.
1664 The pulsewidths supported by servos varies and should probably
1665 be determined by experiment. A value of 1500 should always be
1666 safe and represents the mid-point of rotation.
1668 You can DAMAGE a servo if you command it to move beyond its
1669 limits.
1671 ...
1672 pi.set_servo_pulsewidth(17, 0) # off
1673 pi.set_servo_pulsewidth(17, 1000) # safe anti-clockwise
1674 pi.set_servo_pulsewidth(17, 1500) # centre
1675 pi.set_servo_pulsewidth(17, 2000) # safe clockwise
1676 ...
1677 """
1678 return _u2i(_pigpio_command(
1679 self.sl, _PI_CMD_SERVO, user_gpio, int(pulsewidth)))
1681 def get_servo_pulsewidth(self, user_gpio):
1682 """
1683 Returns the servo pulsewidth being used on the GPIO.
1685 user_gpio:= 0-31.
1687 Returns the servo pulsewidth.
1689 ...
1690 pi.set_servo_pulsewidth(4, 525)
1691 print(pi.get_servo_pulsewidth(4))
1692 525
1694 pi.set_servo_pulsewidth(4, 2130)
1695 print(pi.get_servo_pulsewidth(4))
1696 2130
1697 ...
1698 """
1699 return _u2i(_pigpio_command(self.sl, _PI_CMD_GPW, user_gpio, 0))
1701 def notify_open(self):
1702 """
1703 Returns a notification handle (>=0).
1705 A notification is a method for being notified of GPIO state
1706 changes via a pipe.
1708 Pipes are only accessible from the local machine so this
1709 function serves no purpose if you are using Python from a
1710 remote machine. The in-built (socket) notifications
1711 provided by [*callback*] should be used instead.
1713 Notifications for handle x will be available at the pipe
1714 named /dev/pigpiox (where x is the handle number).
1716 E.g. if the function returns 15 then the notifications must be
1717 read from /dev/pigpio15.
1719 Notifications have the following structure:
1721 . .
1722 H seqno
1723 H flags
1724 I tick
1725 I level
1726 . .
1728 seqno: starts at 0 each time the handle is opened and then
1729 increments by one for each report.
1731 flags: three flags are defined, PI_NTFY_FLAGS_WDOG,
1732 PI_NTFY_FLAGS_ALIVE, and PI_NTFY_FLAGS_EVENT.
1734 If bit 5 is set (PI_NTFY_FLAGS_WDOG) then bits 0-4 of the
1735 flags indicate a GPIO which has had a watchdog timeout.
1737 If bit 6 is set (PI_NTFY_FLAGS_ALIVE) this indicates a keep
1738 alive signal on the pipe/socket and is sent once a minute
1739 in the absence of other notification activity.
1741 If bit 7 is set (PI_NTFY_FLAGS_EVENT) then bits 0-4 of the
1742 flags indicate an event which has been triggered.
1745 tick: the number of microseconds since system boot. It wraps
1746 around after 1h12m.
1748 level: indicates the level of each GPIO. If bit 1<<x is set
1749 then GPIO x is high.
1751 ...
1752 h = pi.notify_open()
1753 if h >= 0:
1754 pi.notify_begin(h, 1234)
1755 ...
1756 """
1757 return _u2i(_pigpio_command(self.sl, _PI_CMD_NO, 0, 0))
1759 def notify_begin(self, handle, bits):
1760 """
1761 Starts notifications on a handle.
1763 handle:= >=0 (as returned by a prior call to [*notify_open*])
1764 bits:= a 32 bit mask indicating the GPIO to be notified.
1766 The notification sends state changes for each GPIO whose
1767 corresponding bit in bits is set.
1769 The following code starts notifications for GPIO 1, 4,
1770 6, 7, and 10 (1234 = 0x04D2 = 0b0000010011010010).
1772 ...
1773 h = pi.notify_open()
1774 if h >= 0:
1775 pi.notify_begin(h, 1234)
1776 ...
1777 """
1778 return _u2i(_pigpio_command(self.sl, _PI_CMD_NB, handle, bits))
1780 def notify_pause(self, handle):
1781 """
1782 Pauses notifications on a handle.
1784 handle:= >=0 (as returned by a prior call to [*notify_open*])
1786 Notifications for the handle are suspended until
1787 [*notify_begin*] is called again.
1789 ...
1790 h = pi.notify_open()
1791 if h >= 0:
1792 pi.notify_begin(h, 1234)
1793 ...
1794 pi.notify_pause(h)
1795 ...
1796 pi.notify_begin(h, 1234)
1797 ...
1798 ...
1799 """
1800 return _u2i(_pigpio_command(self.sl, _PI_CMD_NB, handle, 0))
1802 def notify_close(self, handle):
1803 """
1804 Stops notifications on a handle and releases the handle for reuse.
1806 handle:= >=0 (as returned by a prior call to [*notify_open*])
1808 ...
1809 h = pi.notify_open()
1810 if h >= 0:
1811 pi.notify_begin(h, 1234)
1812 ...
1813 pi.notify_close(h)
1814 ...
1815 ...
1816 """
1817 return _u2i(_pigpio_command(self.sl, _PI_CMD_NC, handle, 0))
1819 def set_watchdog(self, user_gpio, wdog_timeout):
1820 """
1821 Sets a watchdog timeout for a GPIO.
1823 user_gpio:= 0-31.
1824 wdog_timeout:= 0-60000.
1826 The watchdog is nominally in milliseconds.
1828 Only one watchdog may be registered per GPIO.
1830 The watchdog may be cancelled by setting timeout to 0.
1832 Once a watchdog has been started callbacks for the GPIO
1833 will be triggered every timeout interval after the last
1834 GPIO activity.
1836 The callback will receive the special level TIMEOUT.
1838 ...
1839 pi.set_watchdog(23, 1000) # 1000 ms watchdog on GPIO 23
1840 pi.set_watchdog(23, 0) # cancel watchdog on GPIO 23
1841 ...
1842 """
1843 return _u2i(_pigpio_command(
1844 self.sl, _PI_CMD_WDOG, user_gpio, int(wdog_timeout)))
1846 def read_bank_1(self):
1847 """
1848 Returns the levels of the bank 1 GPIO (GPIO 0-31).
1850 The returned 32 bit integer has a bit set if the corresponding
1851 GPIO is high. GPIO n has bit value (1<<n).
1853 ...
1854 print(bin(pi.read_bank_1()))
1855 0b10010100000011100100001001111
1856 ...
1857 """
1858 return _pigpio_command(self.sl, _PI_CMD_BR1, 0, 0)
1860 def read_bank_2(self):
1861 """
1862 Returns the levels of the bank 2 GPIO (GPIO 32-53).
1864 The returned 32 bit integer has a bit set if the corresponding
1865 GPIO is high. GPIO n has bit value (1<<(n-32)).
1867 ...
1868 print(bin(pi.read_bank_2()))
1869 0b1111110000000000000000
1870 ...
1871 """
1872 return _pigpio_command(self.sl, _PI_CMD_BR2, 0, 0)
1874 def clear_bank_1(self, bits):
1875 """
1876 Clears GPIO 0-31 if the corresponding bit in bits is set.
1878 bits:= a 32 bit mask with 1 set if the corresponding GPIO is
1879 to be cleared.
1881 A returned status of PI_SOME_PERMITTED indicates that the user
1882 is not allowed to write to one or more of the GPIO.
1884 ...
1885 pi.clear_bank_1(int("111110010000",2))
1886 ...
1887 """
1888 return _u2i(_pigpio_command(self.sl, _PI_CMD_BC1, bits, 0))
1890 def clear_bank_2(self, bits):
1891 """
1892 Clears GPIO 32-53 if the corresponding bit (0-21) in bits is set.
1894 bits:= a 32 bit mask with 1 set if the corresponding GPIO is
1895 to be cleared.
1897 A returned status of PI_SOME_PERMITTED indicates that the user
1898 is not allowed to write to one or more of the GPIO.
1900 ...
1901 pi.clear_bank_2(0x1010)
1902 ...
1903 """
1904 return _u2i(_pigpio_command(self.sl, _PI_CMD_BC2, bits, 0))
1906 def set_bank_1(self, bits):
1907 """
1908 Sets GPIO 0-31 if the corresponding bit in bits is set.
1910 bits:= a 32 bit mask with 1 set if the corresponding GPIO is
1911 to be set.
1913 A returned status of PI_SOME_PERMITTED indicates that the user
1914 is not allowed to write to one or more of the GPIO.
1916 ...
1917 pi.set_bank_1(int("111110010000",2))
1918 ...
1919 """
1920 return _u2i(_pigpio_command(self.sl, _PI_CMD_BS1, bits, 0))
1922 def set_bank_2(self, bits):
1923 """
1924 Sets GPIO 32-53 if the corresponding bit (0-21) in bits is set.
1926 bits:= a 32 bit mask with 1 set if the corresponding GPIO is
1927 to be set.
1929 A returned status of PI_SOME_PERMITTED indicates that the user
1930 is not allowed to write to one or more of the GPIO.
1932 ...
1933 pi.set_bank_2(0x303)
1934 ...
1935 """
1936 return _u2i(_pigpio_command(self.sl, _PI_CMD_BS2, bits, 0))
1938 def hardware_clock(self, gpio, clkfreq):
1939 """
1940 Starts a hardware clock on a GPIO at the specified frequency.
1941 Frequencies above 30MHz are unlikely to work.
1943 gpio:= see description
1944 clkfreq:= 0 (off) or 4689-250M (13184-375M for the BCM2711)
1947 Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO,
1948 PI_NOT_HCLK_GPIO, PI_BAD_HCLK_FREQ,or PI_BAD_HCLK_PASS.
1950 The same clock is available on multiple GPIO. The latest
1951 frequency setting will be used by all GPIO which share a clock.
1953 The GPIO must be one of the following:
1955 . .
1956 4 clock 0 All models
1957 5 clock 1 All models but A and B (reserved for system use)
1958 6 clock 2 All models but A and B
1959 20 clock 0 All models but A and B
1960 21 clock 1 All models but A and Rev.2 B (reserved for system use)
1962 32 clock 0 Compute module only
1963 34 clock 0 Compute module only
1964 42 clock 1 Compute module only (reserved for system use)
1965 43 clock 2 Compute module only
1966 44 clock 1 Compute module only (reserved for system use)
1967 . .
1969 Access to clock 1 is protected by a password as its use will
1970 likely crash the Pi. The password is given by or'ing 0x5A000000
1971 with the GPIO number.
1973 ...
1974 pi.hardware_clock(4, 5000) # 5 KHz clock on GPIO 4
1976 pi.hardware_clock(4, 40000000) # 40 MHz clock on GPIO 4
1977 ...
1978 """
1979 return _u2i(_pigpio_command(self.sl, _PI_CMD_HC, gpio, clkfreq))
1981 def hardware_PWM(self, gpio, PWMfreq, PWMduty):
1982 """
1983 Starts hardware PWM on a GPIO at the specified frequency
1984 and dutycycle. Frequencies above 30MHz are unlikely to work.
1986 NOTE: Any waveform started by [*wave_send_once*],
1987 [*wave_send_repeat*], or [*wave_chain*] will be cancelled.
1989 This function is only valid if the pigpio main clock is PCM.
1990 The main clock defaults to PCM but may be overridden when the
1991 pigpio daemon is started (option -t).
1993 gpio:= see descripton
1994 PWMfreq:= 0 (off) or 1-125M (1-187.5M for the BCM2711).
1995 PWMduty:= 0 (off) to 1000000 (1M)(fully on).
1997 Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO,
1998 PI_NOT_HPWM_GPIO, PI_BAD_HPWM_DUTY, PI_BAD_HPWM_FREQ.
2000 The same PWM channel is available on multiple GPIO.
2001 The latest frequency and dutycycle setting will be used
2002 by all GPIO which share a PWM channel.
2004 The GPIO must be one of the following:
2006 . .
2007 12 PWM channel 0 All models but A and B
2008 13 PWM channel 1 All models but A and B
2009 18 PWM channel 0 All models
2010 19 PWM channel 1 All models but A and B
2012 40 PWM channel 0 Compute module only
2013 41 PWM channel 1 Compute module only
2014 45 PWM channel 1 Compute module only
2015 52 PWM channel 0 Compute module only
2016 53 PWM channel 1 Compute module only
2017 . .
2019 The actual number of steps beween off and fully on is the
2020 integral part of 250M/PWMfreq (375M/PWMfreq for the BCM2711).
2022 The actual frequency set is 250M/steps (375M/steps
2023 for the BCM2711).
2025 There will only be a million steps for a PWMfreq of 250
2026 (375 for the BCM2711). Lower frequencies will have more
2027 steps and higher frequencies will have fewer steps.
2028 PWMduty is automatically scaled to take this into account.
2030 ...
2031 pi.hardware_PWM(18, 800, 250000) # 800Hz 25% dutycycle
2033 pi.hardware_PWM(18, 2000, 750000) # 2000Hz 75% dutycycle
2034 ...
2035 """
2036 # pigpio message format
2038 # I p1 gpio
2039 # I p2 PWMfreq
2040 # I p3 4
2041 ## extension ##
2042 # I PWMdutycycle
2043 extents = [struct.pack("I", PWMduty)]
2044 return _u2i(_pigpio_command_ext(
2045 self.sl, _PI_CMD_HP, gpio, PWMfreq, 4, extents))
2048 def get_current_tick(self):
2049 """
2050 Returns the current system tick.
2052 Tick is the number of microseconds since system boot. As an
2053 unsigned 32 bit quantity tick wraps around approximately
2054 every 71.6 minutes.
2056 ...
2057 t1 = pi.get_current_tick()
2058 time.sleep(1)
2059 t2 = pi.get_current_tick()
2060 ...
2061 """
2062 return _pigpio_command(self.sl, _PI_CMD_TICK, 0, 0)
2064 def get_hardware_revision(self):
2065 """
2066 Returns the Pi's hardware revision number.
2068 The hardware revision is the last few characters on the
2069 Revision line of /proc/cpuinfo.
2071 The revision number can be used to determine the assignment
2072 of GPIO to pins (see [*gpio*]).
2074 There are at least three types of board.
2076 Type 1 boards have hardware revision numbers of 2 and 3.
2078 Type 2 boards have hardware revision numbers of 4, 5, 6, and 15.
2080 Type 3 boards have hardware revision numbers of 16 or greater.
2082 If the hardware revision can not be found or is not a valid
2083 hexadecimal number the function returns 0.
2085 ...
2086 print(pi.get_hardware_revision())
2087 2
2088 ...
2089 """
2090 return _pigpio_command(self.sl, _PI_CMD_HWVER, 0, 0)
2092 def get_pigpio_version(self):
2093 """
2094 Returns the pigpio software version.
2096 ...
2097 v = pi.get_pigpio_version()
2098 ...
2099 """
2100 return _pigpio_command(self.sl, _PI_CMD_PIGPV, 0, 0)
2102 def wave_clear(self):
2103 """
2104 Clears all waveforms and any data added by calls to the
2105 [*wave_add_**] functions.
2107 ...
2108 pi.wave_clear()
2109 ...
2110 """
2111 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCLR, 0, 0))
2113 def wave_add_new(self):
2114 """
2115 Starts a new empty waveform.
2117 You would not normally need to call this function as it is
2118 automatically called after a waveform is created with the
2119 [*wave_create*] function.
2121 ...
2122 pi.wave_add_new()
2123 ...
2124 """
2125 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVNEW, 0, 0))
2127 def wave_add_generic(self, pulses):
2128 """
2129 Adds a list of pulses to the current waveform.
2131 pulses:= list of pulses to add to the waveform.
2133 Returns the new total number of pulses in the current waveform.
2135 The pulses are interleaved in time order within the existing
2136 waveform (if any).
2138 Merging allows the waveform to be built in parts, that is the
2139 settings for GPIO#1 can be added, and then GPIO#2 etc.
2141 If the added waveform is intended to start after or within
2142 the existing waveform then the first pulse should consist
2143 solely of a delay.
2145 ...
2146 G1=4
2147 G2=24
2149 pi.set_mode(G1, pigpio.OUTPUT)
2150 pi.set_mode(G2, pigpio.OUTPUT)
2152 flash_500=[] # flash every 500 ms
2153 flash_100=[] # flash every 100 ms
2155 # ON OFF DELAY
2157 flash_500.append(pigpio.pulse(1<<G1, 1<<G2, 500000))
2158 flash_500.append(pigpio.pulse(1<<G2, 1<<G1, 500000))
2160 flash_100.append(pigpio.pulse(1<<G1, 1<<G2, 100000))
2161 flash_100.append(pigpio.pulse(1<<G2, 1<<G1, 100000))
2163 pi.wave_clear() # clear any existing waveforms
2165 pi.wave_add_generic(flash_500) # 500 ms flashes
2166 f500 = pi.wave_create() # create and save id
2168 pi.wave_add_generic(flash_100) # 100 ms flashes
2169 f100 = pi.wave_create() # create and save id
2171 pi.wave_send_repeat(f500)
2173 time.sleep(4)
2175 pi.wave_send_repeat(f100)
2177 time.sleep(4)
2179 pi.wave_send_repeat(f500)
2181 time.sleep(4)
2183 pi.wave_tx_stop() # stop waveform
2185 pi.wave_clear() # clear all waveforms
2186 ...
2187 """
2188 # pigpio message format
2190 # I p1 0
2191 # I p2 0
2192 # I p3 pulses * 12
2193 ## extension ##
2194 # III on/off/delay * pulses
2195 if len(pulses):
2196 ext = bytearray()
2197 for p in pulses:
2198 ext.extend(struct.pack("III", p.gpio_on, p.gpio_off, p.delay))
2199 extents = [ext]
2200 return _u2i(_pigpio_command_ext(
2201 self.sl, _PI_CMD_WVAG, 0, 0, len(pulses)*12, extents))
2202 else:
2203 return 0
2205 def wave_add_serial(
2206 self, user_gpio, baud, data, offset=0, bb_bits=8, bb_stop=2):
2207 """
2208 Adds a waveform representing serial data to the existing
2209 waveform (if any). The serial data starts [*offset*]
2210 microseconds from the start of the waveform.
2212 user_gpio:= GPIO to transmit data. You must set the GPIO mode
2213 to output.
2214 baud:= 50-1000000 bits per second.
2215 data:= the bytes to write.
2216 offset:= number of microseconds from the start of the
2217 waveform, default 0.
2218 bb_bits:= number of data bits, default 8.
2219 bb_stop:= number of stop half bits, default 2.
2221 Returns the new total number of pulses in the current waveform.
2223 The serial data is formatted as one start bit, [*bb_bits*]
2224 data bits, and [*bb_stop*]/2 stop bits.
2226 It is legal to add serial data streams with different baud
2227 rates to the same waveform.
2229 The bytes required for each character depend upon [*bb_bits*].
2231 For [*bb_bits*] 1-8 there will be one byte per character.
2232 For [*bb_bits*] 9-16 there will be two bytes per character.
2233 For [*bb_bits*] 17-32 there will be four bytes per character.
2235 ...
2236 pi.wave_add_serial(4, 300, 'Hello world')
2238 pi.wave_add_serial(4, 300, b"Hello world")
2240 pi.wave_add_serial(4, 300, b'\\x23\\x01\\x00\\x45')
2242 pi.wave_add_serial(17, 38400, [23, 128, 234], 5000)
2243 ...
2244 """
2245 # pigpio message format
2247 # I p1 gpio
2248 # I p2 baud
2249 # I p3 len+12
2250 ## extension ##
2251 # I bb_bits
2252 # I bb_stop
2253 # I offset
2254 # s len data bytes
2255 if len(data):
2256 extents = [struct.pack("III", bb_bits, bb_stop, offset), data]
2257 return _u2i(_pigpio_command_ext(
2258 self.sl, _PI_CMD_WVAS, user_gpio, baud, len(data)+12, extents))
2259 else:
2260 return 0
2262 def wave_create(self):
2263 """
2264 Creates a waveform from the data provided by the prior calls
2265 to the [*wave_add_**] functions.
2267 Returns a wave id (>=0) if OK, otherwise PI_EMPTY_WAVEFORM,
2268 PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID.
2270 The data provided by the [*wave_add_**] functions is consumed by
2271 this function.
2273 As many waveforms may be created as there is space available.
2274 The wave id is passed to [*wave_send_**] to specify the waveform
2275 to transmit.
2277 Normal usage would be
2279 Step 1. [*wave_clear*] to clear all waveforms and added data.
2281 Step 2. [*wave_add_**] calls to supply the waveform data.
2283 Step 3. [*wave_create*] to create the waveform and get a unique id
2285 Repeat steps 2 and 3 as needed.
2287 Step 4. [*wave_send_**] with the id of the waveform to transmit.
2289 A waveform comprises one or more pulses.
2291 A pulse specifies
2293 1) the GPIO to be switched on at the start of the pulse.
2294 2) the GPIO to be switched off at the start of the pulse.
2295 3) the delay in microseconds before the next pulse.
2297 Any or all the fields can be zero. It doesn't make any sense
2298 to set all the fields to zero (the pulse will be ignored).
2300 When a waveform is started each pulse is executed in order with
2301 the specified delay between the pulse and the next.
2303 ...
2304 wid = pi.wave_create()
2305 ...
2306 """
2307 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCRE, 0, 0))
2309 def wave_create_and_pad(self, percent):
2310 """
2311 This function creates a waveform like [*wave_create*] but pads the consumed
2312 resources. Where percent gives the percentage of the resources to use
2313 (in terms of the theoretical maximum, not the current amount free).
2314 This allows the reuse of deleted waves while a transmission is active.
2316 Upon success a wave id greater than or equal to 0 is returned, otherwise
2317 PI_EMPTY_WAVEFORM, PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID.
2319 . .
2320 percent: 0-100, size of waveform as percentage of maximum available.
2321 . .
2323 The data provided by the [*wave_add_**] functions are consumed by this
2324 function.
2326 As many waveforms may be created as there is space available. The
2327 wave id is passed to [*wave_send_**] to specify the waveform to transmit.
2329 A usage would be the creation of two waves where one is filled while the
2330 other is being transmitted. Each wave is assigned 50% of the resources.
2331 This buffer structure allows the transmission of infinite wave sequences.
2333 Normal usage:
2335 Step 1. [*wave_clear*] to clear all waveforms and added data.
2337 Step 2. [*wave_add_**] calls to supply the waveform data.
2339 Step 3. [*wave_create_and_pad*] to create a waveform of uniform size.
2341 Step 4. [*wave_send_**] with the id of the waveform to transmit.
2343 Repeat steps 2-4 as needed.
2345 Step 5. Any wave id can now be deleted and another wave of the same size
2346 can be created in its place.
2348 ...
2349 wid = pi.wave_create_and_pad(50)
2350 ...
2351 """
2352 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCAP, percent, 0))
2354 def wave_delete(self, wave_id):
2355 """
2356 This function deletes the waveform with id wave_id.
2358 wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
2360 Wave ids are allocated in order, 0, 1, 2, etc.
2362 The wave is flagged for deletion. The resources used by the wave
2363 will only be reused when either of the following apply.
2365 - all waves with higher numbered wave ids have been deleted or have
2366 been flagged for deletion.
2368 - a new wave is created which uses exactly the same resources as
2369 the current wave (see the C source for gpioWaveCreate for details).
2371 ...
2372 pi.wave_delete(6) # delete waveform with id 6
2374 pi.wave_delete(0) # delete waveform with id 0
2375 ...
2376 """
2377 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVDEL, wave_id, 0))
2379 def wave_tx_start(self): # DEPRECATED
2380 """
2381 This function is deprecated and has been removed.
2383 Use [*wave_create*]/[*wave_send_**] instead.
2384 """
2385 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVGO, 0, 0))
2387 def wave_tx_repeat(self): # DEPRECATED
2388 """
2389 This function is deprecated and has beeen removed.
2391 Use [*wave_create*]/[*wave_send_**] instead.
2392 """
2393 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVGOR, 0, 0))
2395 def wave_send_once(self, wave_id):
2396 """
2397 Transmits the waveform with id wave_id. The waveform is sent
2398 once.
2400 NOTE: Any hardware PWM started by [*hardware_PWM*] will
2401 be cancelled.
2403 wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
2405 Returns the number of DMA control blocks used in the waveform.
2407 ...
2408 cbs = pi.wave_send_once(wid)
2409 ...
2410 """
2411 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTX, wave_id, 0))
2413 def wave_send_repeat(self, wave_id):
2414 """
2415 Transmits the waveform with id wave_id. The waveform repeats
2416 until wave_tx_stop is called or another call to [*wave_send_**]
2417 is made.
2419 NOTE: Any hardware PWM started by [*hardware_PWM*] will
2420 be cancelled.
2422 wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
2424 Returns the number of DMA control blocks used in the waveform.
2426 ...
2427 cbs = pi.wave_send_repeat(wid)
2428 ...
2429 """
2430 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTXR, wave_id, 0))
2432 def wave_send_using_mode(self, wave_id, mode):
2433 """
2434 Transmits the waveform with id wave_id using mode mode.
2436 wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
2437 mode:= WAVE_MODE_ONE_SHOT, WAVE_MODE_REPEAT,
2438 WAVE_MODE_ONE_SHOT_SYNC, or WAVE_MODE_REPEAT_SYNC.
2440 WAVE_MODE_ONE_SHOT: same as [*wave_send_once*].
2442 WAVE_MODE_REPEAT same as [*wave_send_repeat*].
2444 WAVE_MODE_ONE_SHOT_SYNC same as [*wave_send_once*] but tries
2445 to sync with the previous waveform.
2447 WAVE_MODE_REPEAT_SYNC same as [*wave_send_repeat*] but tries
2448 to sync with the previous waveform.
2450 WARNING: bad things may happen if you delete the previous
2451 waveform before it has been synced to the new waveform.
2453 NOTE: Any hardware PWM started by [*hardware_PWM*] will
2454 be cancelled.
2456 wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
2458 Returns the number of DMA control blocks used in the waveform.
2460 ...
2461 cbs = pi.wave_send_using_mode(wid, WAVE_MODE_REPEAT_SYNC)
2462 ...
2463 """
2464 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTXM, wave_id, mode))
2466 def wave_tx_at(self):
2467 """
2468 Returns the id of the waveform currently being
2469 transmitted using [*wave_send**]. Chained waves are not supported.
2471 Returns the waveform id or one of the following special
2472 values:
2474 WAVE_NOT_FOUND (9998) - transmitted wave not found.
2475 NO_TX_WAVE (9999) - no wave being transmitted.
2477 ...
2478 wid = pi.wave_tx_at()
2479 ...
2480 """
2481 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTAT, 0, 0))
2483 def wave_tx_busy(self):
2484 """
2485 Returns 1 if a waveform is currently being transmitted,
2486 otherwise 0.
2488 ...
2489 pi.wave_send_once(0) # send first waveform
2491 while pi.wave_tx_busy(): # wait for waveform to be sent
2492 time.sleep(0.1)
2494 pi.wave_send_once(1) # send next waveform
2495 ...
2496 """
2497 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVBSY, 0, 0))
2499 def wave_tx_stop(self):
2500 """
2501 Stops the transmission of the current waveform.
2503 This function is intended to stop a waveform started with
2504 wave_send_repeat.
2506 ...
2507 pi.wave_send_repeat(3)
2509 time.sleep(5)
2511 pi.wave_tx_stop()
2512 ...
2513 """
2514 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVHLT, 0, 0))
2516 def wave_chain(self, data):
2517 """
2518 This function transmits a chain of waveforms.
2520 NOTE: Any hardware PWM started by [*hardware_PWM*]
2521 will be cancelled.
2523 The waves to be transmitted are specified by the contents
2524 of data which contains an ordered list of [*wave_id*]s
2525 and optional command codes and related data.
2527 Returns 0 if OK, otherwise PI_CHAIN_NESTING,
2528 PI_CHAIN_LOOP_CNT, PI_BAD_CHAIN_LOOP, PI_BAD_CHAIN_CMD,
2529 PI_CHAIN_COUNTER, PI_BAD_CHAIN_DELAY, PI_CHAIN_TOO_BIG,
2530 or PI_BAD_WAVE_ID.
2532 Each wave is transmitted in the order specified. A wave
2533 may occur multiple times per chain.
2535 A blocks of waves may be transmitted multiple times by
2536 using the loop commands. The block is bracketed by loop
2537 start and end commands. Loops may be nested.
2539 Delays between waves may be added with the delay command.
2541 The following command codes are supported:
2543 Name @ Cmd & Data @ Meaning
2544 Loop Start @ 255 0 @ Identify start of a wave block
2545 Loop Repeat @ 255 1 x y @ loop x + y*256 times
2546 Delay @ 255 2 x y @ delay x + y*256 microseconds
2547 Loop Forever @ 255 3 @ loop forever
2549 If present Loop Forever must be the last entry in the chain.
2551 The code is currently dimensioned to support a chain with
2552 roughly 600 entries and 20 loop counters.
2554 ...
2555 #!/usr/bin/env python
2557 import time
2558 import pigpio
2560 WAVES=5
2561 GPIO=4
2563 wid=[0]*WAVES
2565 pi = pigpio.pi() # Connect to local Pi.
2567 pi.set_mode(GPIO, pigpio.OUTPUT);
2569 for i in range(WAVES):
2570 pi.wave_add_generic([
2571 pigpio.pulse(1<<GPIO, 0, 20),
2572 pigpio.pulse(0, 1<<GPIO, (i+1)*200)]);
2574 wid[i] = pi.wave_create();
2576 pi.wave_chain([
2577 wid[4], wid[3], wid[2], # transmit waves 4+3+2
2578 255, 0, # loop start
2579 wid[0], wid[0], wid[0], # transmit waves 0+0+0
2580 255, 0, # loop start
2581 wid[0], wid[1], # transmit waves 0+1
2582 255, 2, 0x88, 0x13, # delay 5000us
2583 255, 1, 30, 0, # loop end (repeat 30 times)
2584 255, 0, # loop start
2585 wid[2], wid[3], wid[0], # transmit waves 2+3+0
2586 wid[3], wid[1], wid[2], # transmit waves 3+1+2
2587 255, 1, 10, 0, # loop end (repeat 10 times)
2588 255, 1, 5, 0, # loop end (repeat 5 times)
2589 wid[4], wid[4], wid[4], # transmit waves 4+4+4
2590 255, 2, 0x20, 0x4E, # delay 20000us
2591 wid[0], wid[0], wid[0], # transmit waves 0+0+0
2592 ])
2594 while pi.wave_tx_busy():
2595 time.sleep(0.1);
2597 for i in range(WAVES):
2598 pi.wave_delete(wid[i])
2600 pi.stop()
2601 ...
2602 """
2603 # I p1 0
2604 # I p2 0
2605 # I p3 len
2606 ## extension ##
2607 # s len data bytes
2609 return _u2i(_pigpio_command_ext(
2610 self.sl, _PI_CMD_WVCHA, 0, 0, len(data), [data]))
2613 def wave_get_micros(self):
2614 """
2615 Returns the length in microseconds of the current waveform.
2617 ...
2618 micros = pi.wave_get_micros()
2619 ...
2620 """
2621 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSM, 0, 0))
2623 def wave_get_max_micros(self):
2624 """
2625 Returns the maximum possible size of a waveform in microseconds.
2627 ...
2628 micros = pi.wave_get_max_micros()
2629 ...
2630 """
2631 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSM, 2, 0))
2633 def wave_get_pulses(self):
2634 """
2635 Returns the length in pulses of the current waveform.
2637 ...
2638 pulses = pi.wave_get_pulses()
2639 ...
2640 """
2641 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSP, 0, 0))
2643 def wave_get_max_pulses(self):
2644 """
2645 Returns the maximum possible size of a waveform in pulses.
2647 ...
2648 pulses = pi.wave_get_max_pulses()
2649 ...
2650 """
2651 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSP, 2, 0))
2653 def wave_get_cbs(self):
2654 """
2655 Returns the length in DMA control blocks of the current
2656 waveform.
2658 ...
2659 cbs = pi.wave_get_cbs()
2660 ...
2661 """
2662 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSC, 0, 0))
2664 def wave_get_max_cbs(self):
2665 """
2666 Returns the maximum possible size of a waveform in DMA
2667 control blocks.
2669 ...
2670 cbs = pi.wave_get_max_cbs()
2671 ...
2672 """
2673 return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSC, 2, 0))
2675 def i2c_open(self, i2c_bus, i2c_address, i2c_flags=0):
2676 """
2677 Returns a handle (>=0) for the device at the I2C bus address.
2679 i2c_bus:= >=0.
2680 i2c_address:= 0-0x7F.
2681 i2c_flags:= 0, no flags are currently defined.
2683 Physically buses 0 and 1 are available on the Pi. Higher
2684 numbered buses will be available if a kernel supported bus
2685 multiplexor is being used.
2687 The GPIO used are given in the following table.
2689 @ SDA @ SCL
2690 I2C 0 @ 0 @ 1
2691 I2C 1 @ 2 @ 3
2693 For the SMBus commands the low level transactions are shown
2694 at the end of the function description. The following
2695 abbreviations are used:
2697 . .
2698 S (1 bit) : Start bit
2699 P (1 bit) : Stop bit
2700 Rd/Wr (1 bit) : Read/Write bit. Rd equals 1, Wr equals 0.
2701 A, NA (1 bit) : Accept and not accept bit.
2702 Addr (7 bits): I2C 7 bit address.
2703 reg (8 bits): Command byte, which often selects a register.
2704 Data (8 bits): A data byte.
2705 Count (8 bits): A byte defining the length of a block operation.
2707 [..]: Data sent by the device.
2708 . .
2710 ...
2711 h = pi.i2c_open(1, 0x53) # open device at address 0x53 on bus 1
2712 ...
2713 """
2714 # I p1 i2c_bus
2715 # I p2 i2c_addr
2716 # I p3 4
2717 ## extension ##
2718 # I i2c_flags
2719 extents = [struct.pack("I", i2c_flags)]
2720 return _u2i(_pigpio_command_ext(
2721 self.sl, _PI_CMD_I2CO, i2c_bus, i2c_address, 4, extents))
2723 def i2c_close(self, handle):
2724 """
2725 Closes the I2C device associated with handle.
2727 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2729 ...
2730 pi.i2c_close(h)
2731 ...
2732 """
2733 return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CC, handle, 0))
2735 def i2c_write_quick(self, handle, bit):
2736 """
2737 Sends a single bit to the device associated with handle.
2739 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2740 bit:= 0 or 1, the value to write.
2742 SMBus 2.0 5.5.1 - Quick command.
2743 . .
2744 S Addr bit [A] P
2745 . .
2747 ...
2748 pi.i2c_write_quick(0, 1) # send 1 to device 0
2749 pi.i2c_write_quick(3, 0) # send 0 to device 3
2750 ...
2751 """
2752 return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CWQ, handle, bit))
2754 def i2c_write_byte(self, handle, byte_val):
2755 """
2756 Sends a single byte to the device associated with handle.
2758 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2759 byte_val:= 0-255, the value to write.
2761 SMBus 2.0 5.5.2 - Send byte.
2762 . .
2763 S Addr Wr [A] byte_val [A] P
2764 . .
2766 ...
2767 pi.i2c_write_byte(1, 17) # send byte 17 to device 1
2768 pi.i2c_write_byte(2, 0x23) # send byte 0x23 to device 2
2769 ...
2770 """
2771 return _u2i(
2772 _pigpio_command(self.sl, _PI_CMD_I2CWS, handle, byte_val))
2774 def i2c_read_byte(self, handle):
2775 """
2776 Reads a single byte from the device associated with handle.
2778 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2780 SMBus 2.0 5.5.3 - Receive byte.
2781 . .
2782 S Addr Rd [A] [Data] NA P
2783 . .
2785 ...
2786 b = pi.i2c_read_byte(2) # read a byte from device 2
2787 ...
2788 """
2789 return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRS, handle, 0))
2791 def i2c_write_byte_data(self, handle, reg, byte_val):
2792 """
2793 Writes a single byte to the specified register of the device
2794 associated with handle.
2796 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2797 reg:= >=0, the device register.
2798 byte_val:= 0-255, the value to write.
2800 SMBus 2.0 5.5.4 - Write byte.
2801 . .
2802 S Addr Wr [A] reg [A] byte_val [A] P
2803 . .
2805 ...
2806 # send byte 0xC5 to reg 2 of device 1
2807 pi.i2c_write_byte_data(1, 2, 0xC5)
2809 # send byte 9 to reg 4 of device 2
2810 pi.i2c_write_byte_data(2, 4, 9)
2811 ...
2812 """
2813 # I p1 handle
2814 # I p2 reg
2815 # I p3 4
2816 ## extension ##
2817 # I byte_val
2818 extents = [struct.pack("I", byte_val)]
2819 return _u2i(_pigpio_command_ext(
2820 self.sl, _PI_CMD_I2CWB, handle, reg, 4, extents))
2822 def i2c_write_word_data(self, handle, reg, word_val):
2823 """
2824 Writes a single 16 bit word to the specified register of the
2825 device associated with handle.
2827 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2828 reg:= >=0, the device register.
2829 word_val:= 0-65535, the value to write.
2831 SMBus 2.0 5.5.4 - Write word.
2832 . .
2833 S Addr Wr [A] reg [A] word_val_Low [A] word_val_High [A] P
2834 . .
2836 ...
2837 # send word 0xA0C5 to reg 5 of device 4
2838 pi.i2c_write_word_data(4, 5, 0xA0C5)
2840 # send word 2 to reg 2 of device 5
2841 pi.i2c_write_word_data(5, 2, 23)
2842 ...
2843 """
2844 # I p1 handle
2845 # I p2 reg
2846 # I p3 4
2847 ## extension ##
2848 # I word_val
2849 extents = [struct.pack("I", word_val)]
2850 return _u2i(_pigpio_command_ext(
2851 self.sl, _PI_CMD_I2CWW, handle, reg, 4, extents))
2853 def i2c_read_byte_data(self, handle, reg):
2854 """
2855 Reads a single byte from the specified register of the device
2856 associated with handle.
2858 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2859 reg:= >=0, the device register.
2861 SMBus 2.0 5.5.5 - Read byte.
2862 . .
2863 S Addr Wr [A] reg [A] S Addr Rd [A] [Data] NA P
2864 . .
2866 ...
2867 # read byte from reg 17 of device 2
2868 b = pi.i2c_read_byte_data(2, 17)
2870 # read byte from reg 1 of device 0
2871 b = pi.i2c_read_byte_data(0, 1)
2872 ...
2873 """
2874 return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRB, handle, reg))
2876 def i2c_read_word_data(self, handle, reg):
2877 """
2878 Reads a single 16 bit word from the specified register of the
2879 device associated with handle.
2881 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2882 reg:= >=0, the device register.
2884 SMBus 2.0 5.5.5 - Read word.
2885 . .
2886 S Addr Wr [A] reg [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P
2887 . .
2889 ...
2890 # read word from reg 2 of device 3
2891 w = pi.i2c_read_word_data(3, 2)
2893 # read word from reg 7 of device 2
2894 w = pi.i2c_read_word_data(2, 7)
2895 ...
2896 """
2897 return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRW, handle, reg))
2899 def i2c_process_call(self, handle, reg, word_val):
2900 """
2901 Writes 16 bits of data to the specified register of the device
2902 associated with handle and reads 16 bits of data in return.
2904 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2905 reg:= >=0, the device register.
2906 word_val:= 0-65535, the value to write.
2908 SMBus 2.0 5.5.6 - Process call.
2909 . .
2910 S Addr Wr [A] reg [A] word_val_Low [A] word_val_High [A]
2911 S Addr Rd [A] [DataLow] A [DataHigh] NA P
2912 . .
2914 ...
2915 r = pi.i2c_process_call(h, 4, 0x1231)
2916 r = pi.i2c_process_call(h, 6, 0)
2917 ...
2918 """
2919 # I p1 handle
2920 # I p2 reg
2921 # I p3 4
2922 ## extension ##
2923 # I word_val
2924 extents = [struct.pack("I", word_val)]
2925 return _u2i(_pigpio_command_ext(
2926 self.sl, _PI_CMD_I2CPC, handle, reg, 4, extents))
2928 def i2c_write_block_data(self, handle, reg, data):
2929 """
2930 Writes up to 32 bytes to the specified register of the device
2931 associated with handle.
2933 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2934 reg:= >=0, the device register.
2935 data:= the bytes to write.
2937 SMBus 2.0 5.5.7 - Block write.
2938 . .
2939 S Addr Wr [A] reg [A] len(data) [A] data0 [A] data1 [A] ... [A]
2940 datan [A] P
2941 . .
2943 ...
2944 pi.i2c_write_block_data(4, 5, b'hello')
2946 pi.i2c_write_block_data(4, 5, "data bytes")
2948 pi.i2c_write_block_data(5, 0, b'\\x00\\x01\\x22')
2950 pi.i2c_write_block_data(6, 2, [0, 1, 0x22])
2951 ...
2952 """
2953 # I p1 handle
2954 # I p2 reg
2955 # I p3 len
2956 ## extension ##
2957 # s len data bytes
2958 if len(data):
2959 return _u2i(_pigpio_command_ext(
2960 self.sl, _PI_CMD_I2CWK, handle, reg, len(data), [data]))
2961 else:
2962 return 0
2964 def i2c_read_block_data(self, handle, reg):
2965 """
2966 Reads a block of up to 32 bytes from the specified register of
2967 the device associated with handle.
2969 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
2970 reg:= >=0, the device register.
2972 SMBus 2.0 5.5.7 - Block read.
2973 . .
2974 S Addr Wr [A] reg [A]
2975 S Addr Rd [A] [Count] A [Data] A [Data] A ... A [Data] NA P
2976 . .
2978 The amount of returned data is set by the device.
2980 The returned value is a tuple of the number of bytes read and a
2981 bytearray containing the bytes. If there was an error the
2982 number of bytes read will be less than zero (and will contain
2983 the error code).
2985 ...
2986 (b, d) = pi.i2c_read_block_data(h, 10)
2987 if b >= 0:
2988 # process data
2989 else:
2990 # process read failure
2991 ...
2992 """
2993 bytes = PI_CMD_INTERRUPTED
2994 rdata = ""
2995 with self.sl.l:
2996 bytes = u2i(_pigpio_command_nolock(
2997 self.sl, _PI_CMD_I2CRK, handle, reg))
2998 if bytes > 0:
2999 rdata = self._rxbuf(bytes)
3000 return bytes, rdata
3002 def i2c_block_process_call(self, handle, reg, data):
3003 """
3004 Writes data bytes to the specified register of the device
3005 associated with handle and reads a device specified number
3006 of bytes of data in return.
3008 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
3009 reg:= >=0, the device register.
3010 data:= the bytes to write.
3012 The SMBus 2.0 documentation states that a minimum of 1 byte may
3013 be sent and a minimum of 1 byte may be received. The total
3014 number of bytes sent/received must be 32 or less.
3016 SMBus 2.0 5.5.8 - Block write-block read.
3017 . .
3018 S Addr Wr [A] reg [A] len(data) [A] data0 [A] ... datan [A]
3019 S Addr Rd [A] [Count] A [Data] ... A P
3020 . .
3022 The returned value is a tuple of the number of bytes read and a
3023 bytearray containing the bytes. If there was an error the
3024 number of bytes read will be less than zero (and will contain
3025 the error code).
3027 ...
3028 (b, d) = pi.i2c_block_process_call(h, 10, b'\\x02\\x05\\x00')
3030 (b, d) = pi.i2c_block_process_call(h, 10, b'abcdr')
3032 (b, d) = pi.i2c_block_process_call(h, 10, "abracad")
3034 (b, d) = pi.i2c_block_process_call(h, 10, [2, 5, 16])
3035 ...
3036 """
3037 # I p1 handle
3038 # I p2 reg
3039 # I p3 len
3040 ## extension ##
3041 # s len data bytes
3043 bytes = PI_CMD_INTERRUPTED
3044 rdata = ""
3045 with self.sl.l:
3046 bytes = u2i(_pigpio_command_ext_nolock(
3047 self.sl, _PI_CMD_I2CPK, handle, reg, len(data), [data]))
3048 if bytes > 0:
3049 rdata = self._rxbuf(bytes)
3050 return bytes, rdata
3052 def i2c_write_i2c_block_data(self, handle, reg, data):
3053 """
3054 Writes data bytes to the specified register of the device
3055 associated with handle . 1-32 bytes may be written.
3057 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
3058 reg:= >=0, the device register.
3059 data:= the bytes to write.
3061 . .
3062 S Addr Wr [A] reg [A] data0 [A] data1 [A] ... [A] datan [NA] P
3063 . .
3065 ...
3066 pi.i2c_write_i2c_block_data(4, 5, 'hello')
3068 pi.i2c_write_i2c_block_data(4, 5, b'hello')
3070 pi.i2c_write_i2c_block_data(5, 0, b'\\x00\\x01\\x22')
3072 pi.i2c_write_i2c_block_data(6, 2, [0, 1, 0x22])
3073 ...
3074 """
3075 # I p1 handle
3076 # I p2 reg
3077 # I p3 len
3078 ## extension ##
3079 # s len data bytes
3080 if len(data):
3081 return _u2i(_pigpio_command_ext(
3082 self.sl, _PI_CMD_I2CWI, handle, reg, len(data), [data]))
3083 else:
3084 return 0
3086 def i2c_read_i2c_block_data(self, handle, reg, count):
3087 """
3088 Reads count bytes from the specified register of the device
3089 associated with handle . The count may be 1-32.
3091 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
3092 reg:= >=0, the device register.
3093 count:= >0, the number of bytes to read.
3095 . .
3096 S Addr Wr [A] reg [A]
3097 S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P
3098 . .
3100 The returned value is a tuple of the number of bytes read and a
3101 bytearray containing the bytes. If there was an error the
3102 number of bytes read will be less than zero (and will contain
3103 the error code).
3105 ...
3106 (b, d) = pi.i2c_read_i2c_block_data(h, 4, 32)
3107 if b >= 0:
3108 # process data
3109 else:
3110 # process read failure
3111 ...
3112 """
3113 # I p1 handle
3114 # I p2 reg
3115 # I p3 4
3116 ## extension ##
3117 # I count
3118 extents = [struct.pack("I", count)]
3120 bytes = PI_CMD_INTERRUPTED
3121 rdata = ""
3122 with self.sl.l:
3123 bytes = u2i(_pigpio_command_ext_nolock(
3124 self.sl, _PI_CMD_I2CRI, handle, reg, 4, extents))
3125 if bytes > 0:
3126 rdata = self._rxbuf(bytes)
3127 return bytes, rdata
3129 def i2c_read_device(self, handle, count):
3130 """
3131 Returns count bytes read from the raw device associated
3132 with handle.
3134 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
3135 count:= >0, the number of bytes to read.
3137 . .
3138 S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P
3139 . .
3141 The returned value is a tuple of the number of bytes read and a
3142 bytearray containing the bytes. If there was an error the
3143 number of bytes read will be less than zero (and will contain
3144 the error code).
3146 ...
3147 (count, data) = pi.i2c_read_device(h, 12)
3148 ...
3149 """
3150 bytes = PI_CMD_INTERRUPTED
3151 rdata = ""
3152 with self.sl.l:
3153 bytes = u2i(
3154 _pigpio_command_nolock(self.sl, _PI_CMD_I2CRD, handle, count))
3155 if bytes > 0:
3156 rdata = self._rxbuf(bytes)
3157 return bytes, rdata
3159 def i2c_write_device(self, handle, data):
3160 """
3161 Writes the data bytes to the raw device associated with handle.
3163 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
3164 data:= the bytes to write.
3166 . .
3167 S Addr Wr [A] data0 [A] data1 [A] ... [A] datan [A] P
3168 . .
3170 ...
3171 pi.i2c_write_device(h, b"\\x12\\x34\\xA8")
3173 pi.i2c_write_device(h, b"help")
3175 pi.i2c_write_device(h, 'help')
3177 pi.i2c_write_device(h, [23, 56, 231])
3178 ...
3179 """
3180 # I p1 handle
3181 # I p2 0
3182 # I p3 len
3183 ## extension ##
3184 # s len data bytes
3185 if len(data):
3186 return _u2i(_pigpio_command_ext(
3187 self.sl, _PI_CMD_I2CWD, handle, 0, len(data), [data]))
3188 else:
3189 return 0
3192 def i2c_zip(self, handle, data):
3193 """
3194 This function executes a sequence of I2C operations. The
3195 operations to be performed are specified by the contents of data
3196 which contains the concatenated command codes and associated data.
3198 handle:= >=0 (as returned by a prior call to [*i2c_open*]).
3199 data:= the concatenated I2C commands, see below
3201 The returned value is a tuple of the number of bytes read and a
3202 bytearray containing the bytes. If there was an error the
3203 number of bytes read will be less than zero (and will contain
3204 the error code).
3206 ...
3207 (count, data) = pi.i2c_zip(h, [4, 0x53, 7, 1, 0x32, 6, 6, 0])
3208 ...
3210 The following command codes are supported:
3212 Name @ Cmd & Data @ Meaning
3213 End @ 0 @ No more commands
3214 Escape @ 1 @ Next P is two bytes
3215 On @ 2 @ Switch combined flag on
3216 Off @ 3 @ Switch combined flag off
3217 Address @ 4 P @ Set I2C address to P
3218 Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8)
3219 Read @ 6 P @ Read P bytes of data
3220 Write @ 7 P ... @ Write P bytes of data
3222 The address, read, and write commands take a parameter P.
3223 Normally P is one byte (0-255). If the command is preceded by
3224 the Escape command then P is two bytes (0-65535, least significant
3225 byte first).
3227 The address defaults to that associated with the handle.
3228 The flags default to 0. The address and flags maintain their
3229 previous value until updated.
3231 Any read I2C data is concatenated in the returned bytearray.
3233 ...
3234 Set address 0x53, write 0x32, read 6 bytes
3235 Set address 0x1E, write 0x03, read 6 bytes
3236 Set address 0x68, write 0x1B, read 8 bytes
3237 End
3239 0x04 0x53 0x07 0x01 0x32 0x06 0x06
3240 0x04 0x1E 0x07 0x01 0x03 0x06 0x06
3241 0x04 0x68 0x07 0x01 0x1B 0x06 0x08
3242 0x00
3243 ...
3244 """
3245 # I p1 handle
3246 # I p2 0
3247 # I p3 len
3248 ## extension ##
3249 # s len data bytes
3251 bytes = PI_CMD_INTERRUPTED
3252 rdata = ""
3253 with self.sl.l:
3254 bytes = u2i(_pigpio_command_ext_nolock(
3255 self.sl, _PI_CMD_I2CZ, handle, 0, len(data), [data]))
3256 if bytes > 0:
3257 rdata = self._rxbuf(bytes)
3258 return bytes, rdata
3261 def bb_spi_open(self, CS, MISO, MOSI, SCLK, baud=100000, spi_flags=0):
3262 """
3263 This function selects a set of GPIO for bit banging SPI at a
3264 specified baud rate.
3266 CS := 0-31
3267 MISO := 0-31
3268 MOSI := 0-31
3269 SCLK := 0-31
3270 baud := 50-250000
3271 spiFlags := see below
3273 spiFlags consists of the least significant 22 bits.
3275 . .
3276 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
3277 0 0 0 0 0 0 R T 0 0 0 0 0 0 0 0 0 0 0 p m m
3278 . .
3280 mm defines the SPI mode, defaults to 0
3282 . .
3283 Mode CPOL CPHA
3284 0 0 0
3285 1 0 1
3286 2 1 0
3287 3 1 1
3288 . .
3290 The following constants may be used to set the mode:
3292 . .
3293 pigpio.SPI_MODE_0
3294 pigpio.SPI_MODE_1
3295 pigpio.SPI_MODE_2
3296 pigpio.SPI_MODE_3
3297 . .
3299 Alternatively pigpio.SPI_CPOL and/or pigpio.SPI_CPHA
3300 may be used.
3302 p is 0 if CS is active low (default) and 1 for active high.
3303 pigpio.SPI_CS_HIGH_ACTIVE may be used to set this flag.
3305 T is 1 if the least significant bit is transmitted on MOSI first,
3306 the default (0) shifts the most significant bit out first.
3307 pigpio.SPI_TX_LSBFIRST may be used to set this flag.
3309 R is 1 if the least significant bit is received on MISO first,
3310 the default (0) receives the most significant bit first.
3311 pigpio.SPI_RX_LSBFIRST may be used to set this flag.
3313 The other bits in spiFlags should be set to zero.
3315 Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_SPI_BAUD, or
3316 PI_GPIO_IN_USE.
3318 If more than one device is connected to the SPI bus (defined by
3319 SCLK, MOSI, and MISO) each must have its own CS.
3321 ...
3322 bb_spi_open(10, MISO, MOSI, SCLK, 10000, 0); // device 1
3323 bb_spi_open(11, MISO, MOSI, SCLK, 20000, 3); // device 2
3324 ...
3325 """
3326 # I p1 CS
3327 # I p2 0
3328 # I p3 20
3329 ## extension ##
3330 # I MISO
3331 # I MOSI
3332 # I SCLK
3333 # I baud
3334 # I spi_flags
3336 extents = [struct.pack("IIIII", MISO, MOSI, SCLK, baud, spi_flags)]
3337 return _u2i(_pigpio_command_ext(
3338 self.sl, _PI_CMD_BSPIO, CS, 0, 20, extents))
3341 def bb_spi_close(self, CS):
3342 """
3343 This function stops bit banging SPI on a set of GPIO
3344 opened with [*bb_spi_open*].
3346 CS:= 0-31, the CS GPIO used in a prior call to [*bb_spi_open*]
3348 Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_SPI_GPIO.
3350 ...
3351 pi.bb_spi_close(CS)
3352 ...
3353 """
3354 return _u2i(_pigpio_command(self.sl, _PI_CMD_BSPIC, CS, 0))
3357 def bb_spi_xfer(self, CS, data):
3358 """
3359 This function executes a bit banged SPI transfer.
3361 CS:= 0-31 (as used in a prior call to [*bb_spi_open*])
3362 data:= data to be sent
3364 The returned value is a tuple of the number of bytes read and a
3365 bytearray containing the bytes. If there was an error the
3366 number of bytes read will be less than zero (and will contain
3367 the error code).
3369 ...
3370 #!/usr/bin/env python
3372 import pigpio
3374 CE0=5
3375 CE1=6
3376 MISO=13
3377 MOSI=19
3378 SCLK=12
3380 pi = pigpio.pi()
3381 if not pi.connected:
3382 exit()
3384 pi.bb_spi_open(CE0, MISO, MOSI, SCLK, 10000, 0) # MCP4251 DAC
3385 pi.bb_spi_open(CE1, MISO, MOSI, SCLK, 20000, 3) # MCP3008 ADC
3387 for i in range(256):
3389 count, data = pi.bb_spi_xfer(CE0, [0, i]) # Set DAC value
3391 if count == 2:
3393 count, data = pi.bb_spi_xfer(CE0, [12, 0]) # Read back DAC
3395 if count == 2:
3397 set_val = data[1]
3399 count, data = pi.bb_spi_xfer(CE1, [1, 128, 0]) # Read ADC
3401 if count == 3:
3403 read_val = ((data[1]&3)<<8) | data[2]
3405 print("{} {}".format(set_val, read_val))
3407 pi.bb_spi_close(CE0)
3408 pi.bb_spi_close(CE1)
3410 pi.stop()
3411 ...
3412 """
3413 # I p1 CS
3414 # I p2 0
3415 # I p3 len
3416 ## extension ##
3417 # s len data bytes
3419 bytes = PI_CMD_INTERRUPTED
3420 rdata = ""
3421 with self.sl.l:
3422 bytes = u2i(_pigpio_command_ext_nolock(
3423 self.sl, _PI_CMD_BSPIX, CS, 0, len(data), [data]))
3424 if bytes > 0:
3425 rdata = self._rxbuf(bytes)
3426 return bytes, rdata
3429 def bb_i2c_open(self, SDA, SCL, baud=100000):
3430 """
3431 This function selects a pair of GPIO for bit banging I2C at a
3432 specified baud rate.
3434 Bit banging I2C allows for certain operations which are not possible
3435 with the standard I2C driver.
3437 o baud rates as low as 50
3438 o repeated starts
3439 o clock stretching
3440 o I2C on any pair of spare GPIO
3442 SDA:= 0-31
3443 SCL:= 0-31
3444 baud:= 50-500000
3446 Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_I2C_BAUD, or
3447 PI_GPIO_IN_USE.
3449 NOTE:
3451 The GPIO used for SDA and SCL must have pull-ups to 3V3 connected.
3452 As a guide the hardware pull-ups on pins 3 and 5 are 1k8 in value.
3454 ...
3455 h = pi.bb_i2c_open(4, 5, 50000) # bit bang on GPIO 4/5 at 50kbps
3456 ...
3457 """
3458 # I p1 SDA
3459 # I p2 SCL
3460 # I p3 4
3461 ## extension ##
3462 # I baud
3463 extents = [struct.pack("I", baud)]
3464 return _u2i(_pigpio_command_ext(
3465 self.sl, _PI_CMD_BI2CO, SDA, SCL, 4, extents))
3468 def bb_i2c_close(self, SDA):
3469 """
3470 This function stops bit banging I2C on a pair of GPIO
3471 previously opened with [*bb_i2c_open*].
3473 SDA:= 0-31, the SDA GPIO used in a prior call to [*bb_i2c_open*]
3475 Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_I2C_GPIO.
3477 ...
3478 pi.bb_i2c_close(SDA)
3479 ...
3480 """
3481 return _u2i(_pigpio_command(self.sl, _PI_CMD_BI2CC, SDA, 0))
3484 def bb_i2c_zip(self, SDA, data):
3485 """
3486 This function executes a sequence of bit banged I2C operations.
3487 The operations to be performed are specified by the contents
3488 of data which contains the concatenated command codes and
3489 associated data.
3491 SDA:= 0-31 (as used in a prior call to [*bb_i2c_open*])
3492 data:= the concatenated I2C commands, see below
3494 The returned value is a tuple of the number of bytes read and a
3495 bytearray containing the bytes. If there was an error the
3496 number of bytes read will be less than zero (and will contain
3497 the error code).
3499 ...
3500 (count, data) = pi.bb_i2c_zip(
3501 SDA, [4, 0x53, 2, 7, 1, 0x32, 2, 6, 6, 3, 0])
3502 ...
3504 The following command codes are supported:
3506 Name @ Cmd & Data @ Meaning
3507 End @ 0 @ No more commands
3508 Escape @ 1 @ Next P is two bytes
3509 Start @ 2 @ Start condition
3510 Stop @ 3 @ Stop condition
3511 Address @ 4 P @ Set I2C address to P
3512 Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8)
3513 Read @ 6 P @ Read P bytes of data
3514 Write @ 7 P ... @ Write P bytes of data
3516 The address, read, and write commands take a parameter P.
3517 Normally P is one byte (0-255). If the command is preceded by
3518 the Escape command then P is two bytes (0-65535, least significant
3519 byte first).
3521 The address and flags default to 0. The address and flags maintain
3522 their previous value until updated.
3524 No flags are currently defined.
3526 Any read I2C data is concatenated in the returned bytearray.
3528 ...
3529 Set address 0x53
3530 start, write 0x32, (re)start, read 6 bytes, stop
3531 Set address 0x1E
3532 start, write 0x03, (re)start, read 6 bytes, stop
3533 Set address 0x68
3534 start, write 0x1B, (re)start, read 8 bytes, stop
3535 End
3537 0x04 0x53
3538 0x02 0x07 0x01 0x32 0x02 0x06 0x06 0x03
3540 0x04 0x1E
3541 0x02 0x07 0x01 0x03 0x02 0x06 0x06 0x03
3543 0x04 0x68
3544 0x02 0x07 0x01 0x1B 0x02 0x06 0x08 0x03
3546 0x00
3547 ...
3548 """
3549 # I p1 SDA
3550 # I p2 0
3551 # I p3 len
3552 ## extension ##
3553 # s len data bytes
3555 bytes = PI_CMD_INTERRUPTED
3556 rdata = ""
3557 with self.sl.l:
3558 bytes = u2i(_pigpio_command_ext_nolock(
3559 self.sl, _PI_CMD_BI2CZ, SDA, 0, len(data), [data]))
3560 if bytes > 0:
3561 rdata = self._rxbuf(bytes)
3562 return bytes, rdata
3564 def event_trigger(self, event):
3565 """
3566 This function signals the occurrence of an event.
3568 event:= 0-31, the event
3570 Returns 0 if OK, otherwise PI_BAD_EVENT_ID.
3572 An event is a signal used to inform one or more consumers
3573 to start an action. Each consumer which has registered an
3574 interest in the event (e.g. by calling [*event_callback*]) will
3575 be informed by a callback.
3577 One event, EVENT_BSC (31) is predefined. This event is
3578 auto generated on BSC slave activity.
3580 The meaning of other events is arbitrary.
3582 Note that other than its id and its tick there is no data associated
3583 with an event.
3585 ...
3586 pi.event_trigger(23)
3587 ...
3588 """
3589 return _u2i(_pigpio_command(self.sl, _PI_CMD_EVT, event, 0))
3592 def bsc_xfer(self, bsc_control, data):
3593 """
3594 This function provides a low-level interface to the SPI/I2C Slave
3595 peripheral on the BCM chip.
3597 This peripheral allows the Pi to act as a hardware slave device
3598 on an I2C or SPI bus.
3600 This is not a bit bang version and as such is OS timing
3601 independent. The bus timing is handled directly by the chip.
3603 The output process is simple. You simply append data to the FIFO
3604 buffer on the chip. This works like a queue, you add data to the
3605 queue and the master removes it.
3607 The function sets the BSC mode, writes any data in
3608 the transmit buffer to the BSC transmit FIFO, and
3609 copies any data in the BSC receive FIFO to the
3610 receive buffer.
3612 bsc_control:= see below
3613 data:= the data bytes to place in the transmit FIFO.
3615 The returned value is a tuple of the status (see below),
3616 the number of bytes read, and a bytearray containing the
3617 read bytes. If there was an error the status will be less
3618 than zero (and will contain the error code).
3620 Note that the control word sets the BSC mode. The BSC will
3621 stay in that mode until a different control word is sent.
3623 GPIO used for models other than those based on the BCM2711.
3625 @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE
3626 I2C @ 18 @ 19 @ - @ - @ - @ -
3627 SPI @ - @ - @ 20 @ 19 @ 18 @ 21
3629 GPIO used for models based on the BCM2711 (e.g. the Pi4B).
3631 @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE
3632 I2C @ 10 @ 11 @ - @ - @ - @ -
3633 SPI @ - @ - @ 9 @ 11 @ 10 @ 8
3635 When a zero control word is received the used GPIO will be reset
3636 to INPUT mode.
3638 bsc_control consists of the following bits:
3640 . .
3641 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
3642 a a a a a a a - - IT HC TF IR RE TE BK EC ES PL PH I2 SP EN
3643 . .
3645 Bits 0-13 are copied unchanged to the BSC CR register. See
3646 pages 163-165 of the Broadcom peripherals document for full
3647 details.
3649 aaaaaaa @ defines the I2C slave address (only relevant in I2C mode)
3650 IT @ invert transmit status flags
3651 HC @ enable host control
3652 TF @ enable test FIFO
3653 IR @ invert receive status flags
3654 RE @ enable receive
3655 TE @ enable transmit
3656 BK @ abort operation and clear FIFOs
3657 EC @ send control register as first I2C byte
3658 ES @ send status register as first I2C byte
3659 PL @ set SPI polarity high
3660 PH @ set SPI phase high
3661 I2 @ enable I2C mode
3662 SP @ enable SPI mode
3663 EN @ enable BSC peripheral
3665 The status has the following format:
3667 . .
3668 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
3669 S S S S S R R R R R T T T T T RB TE RF TF RE TB
3670 . .
3672 Bits 0-15 are copied unchanged from the BSC FR register. See
3673 pages 165-166 of the Broadcom peripherals document for full
3674 details.
3676 SSSSS @ number of bytes successfully copied to transmit FIFO
3677 RRRRR @ number of bytes in receive FIFO
3678 TTTTT @ number of bytes in transmit FIFO
3679 RB @ receive busy
3680 TE @ transmit FIFO empty
3681 RF @ receive FIFO full
3682 TF @ transmit FIFO full
3683 RE @ receive FIFO empty
3684 TB @ transmit busy
3686 ...
3687 (status, count, data) = pi.bsc_xfer(0x330305, "Hello!")
3688 ...
3690 The BSC slave in SPI mode deserializes data from the MOSI pin into its
3691 receiver/FIFO when the LSB of the first byte is a 0. No data is output on
3692 the MISO pin. When the LSB of the first byte on MOSI is a 1, the
3693 transmitter/FIFO data is serialized onto the MISO pin while all other data
3694 on the MOSI pin is ignored.
3696 The BK bit of the BSC control register is non-functional when in the SPI
3697 mode. The transmitter along with its FIFO can be dequeued by successively
3698 disabling and re-enabling the TE bit on the BSC control register while in
3699 SPI mode.
3701 This example demonstrates a SPI master talking to the BSC as SPI slave:
3702 Requires SPI master SCLK / MOSI / MISO / CE GPIO are connected to
3703 BSC peripheral GPIO 11 / 9 / 10 / 8 respectively, on a Pi4B (BCM2711).
3705 ...
3706 #!/usr/bin/env python
3708 import pigpio
3710 # Choose some random GPIO for the bit-bang SPI master
3711 CE=15
3712 MISO=26
3713 MOSI=13
3714 SCLK=14
3716 pi = pigpio.pi()
3717 if not pi.connected:
3718 exit()
3720 pi.bb_spi_open(CE, MISO, MOSI, SCLK, 10000, 0) # open SPI master
3721 pi.bsc_xfer(0x303, []) # start BSC as SPI slave
3722 pi.bb_spi_xfer(CE, '\0' + 'hello') # write 'hello' to BSC
3723 status, count, bsc_data = pi.bsc_xfer(0x303, 'world')
3724 print bsc_data # hello
3725 count, spi_data = pi.bb_spi_xfer(CE, [1,0,0,0,0,0])
3726 print spi_data # world
3728 pi.bsc_xfer(0, [])
3729 pi.bb_spi_close(CE)
3731 pi.stop()
3732 ...
3733 """
3734 # I p1 control
3735 # I p2 0
3736 # I p3 len
3737 ## extension ##
3738 # s len data bytes
3740 status = PI_CMD_INTERRUPTED
3741 bytes = 0
3742 rdata = bytearray(b'')
3743 with self.sl.l:
3744 bytes = u2i(_pigpio_command_ext_nolock(
3745 self.sl, _PI_CMD_BSCX, bsc_control, 0, len(data), [data]))
3746 if bytes > 0:
3747 rx = self._rxbuf(bytes)
3748 status = struct.unpack('I', rx[0:4])[0]
3749 bytes -= 4
3750 rdata = rx[4:]
3751 else:
3752 status = bytes
3753 bytes = 0
3754 return status, bytes, rdata
3756 def bsc_i2c(self, i2c_address, data=[]):
3757 """
3758 This function allows the Pi to act as a slave I2C device.
3760 The data bytes (if any) are written to the BSC transmit
3761 FIFO and the bytes in the BSC receive FIFO are returned.
3763 i2c_address:= the I2C slave address.
3764 data:= the data bytes to transmit.
3766 The returned value is a tuple of the status, the number
3767 of bytes read, and a bytearray containing the read bytes.
3769 See [*bsc_xfer*] for details of the status value.
3771 If there was an error the status will be less than zero
3772 (and will contain the error code).
3774 Note that an i2c_address of 0 may be used to close
3775 the BSC device and reassign the used GPIO as inputs.
3777 This example assumes GPIO 2/3 are connected to GPIO 18/19
3778 (GPIO 10/11 on the BCM2711).
3780 ...
3781 #!/usr/bin/env python
3782 import time
3783 import pigpio
3785 I2C_ADDR=0x13
3787 def i2c(id, tick):
3788 global pi
3790 s, b, d = pi.bsc_i2c(I2C_ADDR)
3791 if b:
3792 if d[0] == ord('t'): # 116 send 'HH:MM:SS*'
3794 print("sent={} FR={} received={} [{}]".
3795 format(s>>16, s&0xfff,b,d))
3797 s, b, d = pi.bsc_i2c(I2C_ADDR,
3798 "{}*".format(time.asctime()[11:19]))
3800 elif d[0] == ord('d'): # 100 send 'Sun Oct 30*'
3802 print("sent={} FR={} received={} [{}]".
3803 format(s>>16, s&0xfff,b,d))
3805 s, b, d = pi.bsc_i2c(I2C_ADDR,
3806 "{}*".format(time.asctime()[:10]))
3808 pi = pigpio.pi()
3810 if not pi.connected:
3811 exit()
3813 # Respond to BSC slave activity
3815 e = pi.event_callback(pigpio.EVENT_BSC, i2c)
3817 pi.bsc_i2c(I2C_ADDR) # Configure BSC as I2C slave
3819 time.sleep(600)
3821 e.cancel()
3823 pi.bsc_i2c(0) # Disable BSC peripheral
3825 pi.stop()
3826 ...
3828 While running the above.
3830 . .
3831 $ i2cdetect -y 1
3832 0 1 2 3 4 5 6 7 8 9 a b c d e f
3833 00: -- -- -- -- -- -- -- -- -- -- -- -- --
3834 10: -- -- -- 13 -- -- -- -- -- -- -- -- -- -- -- --
3835 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
3836 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
3837 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
3838 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
3839 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
3840 70: -- -- -- -- -- -- -- --
3842 $ pigs i2co 1 0x13 0
3843 0
3845 $ pigs i2cwd 0 116
3846 $ pigs i2crd 0 9 -a
3847 9 10:13:58*
3849 $ pigs i2cwd 0 116
3850 $ pigs i2crd 0 9 -a
3851 9 10:14:29*
3853 $ pigs i2cwd 0 100
3854 $ pigs i2crd 0 11 -a
3855 11 Sun Oct 30*
3857 $ pigs i2cwd 0 100
3858 $ pigs i2crd 0 11 -a
3859 11 Sun Oct 30*
3861 $ pigs i2cwd 0 116
3862 $ pigs i2crd 0 9 -a
3863 9 10:23:16*
3865 $ pigs i2cwd 0 100
3866 $ pigs i2crd 0 11 -a
3867 11 Sun Oct 30*
3868 . .
3869 """
3870 if i2c_address:
3871 control = (i2c_address<<16)|0x305
3872 else:
3873 control = 0
3874 return self.bsc_xfer(control, data)
3876 def spi_open(self, spi_channel, baud, spi_flags=0):
3877 """
3878 Returns a handle for the SPI device on the channel. Data
3879 will be transferred at baud bits per second. The flags
3880 may be used to modify the default behaviour of 4-wire
3881 operation, mode 0, active low chip select.
3883 The Pi has two SPI peripherals: main and auxiliary.
3885 The main SPI has two chip selects (channels), the auxiliary
3886 has three.
3888 The auxiliary SPI is available on all models but the A and B.
3890 The GPIO used are given in the following table.
3892 @ MISO @ MOSI @ SCLK @ CE0 @ CE1 @ CE2
3893 Main SPI @ 9 @ 10 @ 11 @ 8 @ 7 @ -
3894 Aux SPI @ 19 @ 20 @ 21 @ 18 @ 17 @ 16
3896 spi_channel:= 0-1 (0-2 for the auxiliary SPI).
3897 baud:= 32K-125M (values above 30M are unlikely to work).
3898 spi_flags:= see below.
3900 spi_flags consists of the least significant 22 bits.
3902 . .
3903 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
3904 b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m
3905 . .
3907 mm defines the SPI mode.
3909 WARNING: modes 1 and 3 do not appear to work on
3910 the auxiliary SPI.
3912 . .
3913 Mode POL PHA
3914 0 0 0
3915 1 0 1
3916 2 1 0
3917 3 1 1
3918 . .
3920 px is 0 if CEx is active low (default) and 1 for active high.
3922 ux is 0 if the CEx GPIO is reserved for SPI (default)
3923 and 1 otherwise.
3925 A is 0 for the main SPI, 1 for the auxiliary SPI.
3927 W is 0 if the device is not 3-wire, 1 if the device is 3-wire.
3928 Main SPI only.
3930 nnnn defines the number of bytes (0-15) to write before
3931 switching the MOSI line to MISO to read data. This field
3932 is ignored if W is not set. Main SPI only.
3934 T is 1 if the least significant bit is transmitted on MOSI
3935 first, the default (0) shifts the most significant bit out
3936 first. Auxiliary SPI only.
3938 R is 1 if the least significant bit is received on MISO
3939 first, the default (0) receives the most significant bit
3940 first. Auxiliary SPI only.
3942 bbbbbb defines the word size in bits (0-32). The default (0)
3943 sets 8 bits per word. Auxiliary SPI only.
3945 The [*spi_read*], [*spi_write*], and [*spi_xfer*] functions
3946 transfer data packed into 1, 2, or 4 bytes according to
3947 the word size in bits.
3949 For bits 1-8 there will be one byte per character.
3950 For bits 9-16 there will be two bytes per character.
3951 For bits 17-32 there will be four bytes per character.
3953 Multi-byte transfers are made in least significant byte
3954 first order.
3956 E.g. to transfer 32 11-bit words data should
3957 contain 64 bytes.
3959 E.g. to transfer the 14 bit value 0x1ABC send the
3960 bytes 0xBC followed by 0x1A.
3962 The other bits in flags should be set to zero.
3964 ...
3965 # open SPI device on channel 1 in mode 3 at 50000 bits per second
3967 h = pi.spi_open(1, 50000, 3)
3968 ...
3969 """
3970 # I p1 spi_channel
3971 # I p2 baud
3972 # I p3 4
3973 ## extension ##
3974 # I spi_flags
3975 extents = [struct.pack("I", spi_flags)]
3976 return _u2i(_pigpio_command_ext(
3977 self.sl, _PI_CMD_SPIO, spi_channel, baud, 4, extents))
3979 def spi_close(self, handle):
3980 """
3981 Closes the SPI device associated with handle.
3983 handle:= >=0 (as returned by a prior call to [*spi_open*]).
3985 ...
3986 pi.spi_close(h)
3987 ...
3988 """
3989 return _u2i(_pigpio_command(self.sl, _PI_CMD_SPIC, handle, 0))
3991 def spi_read(self, handle, count):
3992 """
3993 Reads count bytes from the SPI device associated with handle.
3995 handle:= >=0 (as returned by a prior call to [*spi_open*]).
3996 count:= >0, the number of bytes to read.
3998 The returned value is a tuple of the number of bytes read and a
3999 bytearray containing the bytes. If there was an error the
4000 number of bytes read will be less than zero (and will contain
4001 the error code).
4003 ...
4004 (b, d) = pi.spi_read(h, 60) # read 60 bytes from device h
4005 if b == 60:
4006 # process read data
4007 else:
4008 # error path
4009 ...
4010 """
4011 bytes = PI_CMD_INTERRUPTED
4012 rdata = ""
4013 with self.sl.l:
4014 bytes = u2i(_pigpio_command_nolock(
4015 self.sl, _PI_CMD_SPIR, handle, count))
4016 if bytes > 0:
4017 rdata = self._rxbuf(bytes)
4018 return bytes, rdata
4020 def spi_write(self, handle, data):
4021 """
4022 Writes the data bytes to the SPI device associated with handle.
4024 handle:= >=0 (as returned by a prior call to [*spi_open*]).
4025 data:= the bytes to write.
4027 ...
4028 pi.spi_write(0, b'\\x02\\xc0\\x80') # write 3 bytes to device 0
4030 pi.spi_write(0, b'defgh') # write 5 bytes to device 0
4032 pi.spi_write(0, "def") # write 3 bytes to device 0
4034 pi.spi_write(1, [2, 192, 128]) # write 3 bytes to device 1
4035 ...
4036 """
4037 # I p1 handle
4038 # I p2 0
4039 # I p3 len
4040 ## extension ##
4041 # s len data bytes
4042 return _u2i(_pigpio_command_ext(
4043 self.sl, _PI_CMD_SPIW, handle, 0, len(data), [data]))
4045 def spi_xfer(self, handle, data):
4046 """
4047 Writes the data bytes to the SPI device associated with handle,
4048 returning the data bytes read from the device.
4050 handle:= >=0 (as returned by a prior call to [*spi_open*]).
4051 data:= the bytes to write.
4053 The returned value is a tuple of the number of bytes read and a
4054 bytearray containing the bytes. If there was an error the
4055 number of bytes read will be less than zero (and will contain
4056 the error code).
4058 ...
4059 (count, rx_data) = pi.spi_xfer(h, b'\\x01\\x80\\x00')
4061 (count, rx_data) = pi.spi_xfer(h, [1, 128, 0])
4063 (count, rx_data) = pi.spi_xfer(h, b"hello")
4065 (count, rx_data) = pi.spi_xfer(h, "hello")
4066 ...
4067 """
4068 # I p1 handle
4069 # I p2 0
4070 # I p3 len
4071 ## extension ##
4072 # s len data bytes
4074 bytes = PI_CMD_INTERRUPTED
4075 rdata = ""
4076 with self.sl.l:
4077 bytes = u2i(_pigpio_command_ext_nolock(
4078 self.sl, _PI_CMD_SPIX, handle, 0, len(data), [data]))
4079 if bytes > 0:
4080 rdata = self._rxbuf(bytes)
4081 return bytes, rdata
4083 def serial_open(self, tty, baud, ser_flags=0):
4084 """
4085 Returns a handle for the serial tty device opened
4086 at baud bits per second. The device name must start
4087 with /dev/tty or /dev/serial.
4089 tty:= the serial device to open.
4090 baud:= baud rate in bits per second, see below.
4091 ser_flags:= 0, no flags are currently defined.
4093 Normally you would only use the [*serial_**] functions if
4094 you are or will be connecting to the Pi over a network. If
4095 you will always run on the local Pi use the standard serial
4096 module instead.
4098 The baud rate must be one of 50, 75, 110, 134, 150,
4099 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200,
4100 38400, 57600, 115200, or 230400.
4102 ...
4103 h1 = pi.serial_open("/dev/ttyAMA0", 300)
4105 h2 = pi.serial_open("/dev/ttyUSB1", 19200, 0)
4107 h3 = pi.serial_open("/dev/serial0", 9600)
4108 ...
4109 """
4110 # I p1 baud
4111 # I p2 ser_flags
4112 # I p3 len
4113 ## extension ##
4114 # s len data bytes
4115 return _u2i(_pigpio_command_ext(
4116 self.sl, _PI_CMD_SERO, baud, ser_flags, len(tty), [tty]))
4118 def serial_close(self, handle):
4119 """
4120 Closes the serial device associated with handle.
4122 handle:= >=0 (as returned by a prior call to [*serial_open*]).
4124 ...
4125 pi.serial_close(h1)
4126 ...
4127 """
4128 return _u2i(_pigpio_command(self.sl, _PI_CMD_SERC, handle, 0))
4130 def serial_read_byte(self, handle):
4131 """
4132 Returns a single byte from the device associated with handle.
4134 handle:= >=0 (as returned by a prior call to [*serial_open*]).
4136 If no data is ready a negative error code will be returned.
4138 ...
4139 b = pi.serial_read_byte(h1)
4140 ...
4141 """
4142 return _u2i(_pigpio_command(self.sl, _PI_CMD_SERRB, handle, 0))
4144 def serial_write_byte(self, handle, byte_val):
4145 """
4146 Writes a single byte to the device associated with handle.
4148 handle:= >=0 (as returned by a prior call to [*serial_open*]).
4149 byte_val:= 0-255, the value to write.
4151 ...
4152 pi.serial_write_byte(h1, 23)
4154 pi.serial_write_byte(h1, ord('Z'))
4155 ...
4156 """
4157 return _u2i(
4158 _pigpio_command(self.sl, _PI_CMD_SERWB, handle, byte_val))
4160 def serial_read(self, handle, count=1000):
4161 """
4162 Reads up to count bytes from the device associated with handle.
4164 handle:= >=0 (as returned by a prior call to [*serial_open*]).
4165 count:= >0, the number of bytes to read (defaults to 1000).
4167 The returned value is a tuple of the number of bytes read and
4168 a bytearray containing the bytes. If there was an error the
4169 number of bytes read will be less than zero (and will contain
4170 the error code).
4172 If no data is ready a bytes read of zero is returned.
4173 ...
4174 (b, d) = pi.serial_read(h2, 100)
4175 if b > 0:
4176 # process read data
4177 ...
4178 """
4179 bytes = PI_CMD_INTERRUPTED
4180 rdata = ""
4181 with self.sl.l:
4182 bytes = u2i(
4183 _pigpio_command_nolock(self.sl, _PI_CMD_SERR, handle, count))
4184 if bytes > 0:
4185 rdata = self._rxbuf(bytes)
4186 return bytes, rdata
4188 def serial_write(self, handle, data):
4189 """
4190 Writes the data bytes to the device associated with handle.
4192 handle:= >=0 (as returned by a prior call to [*serial_open*]).
4193 data:= the bytes to write.
4195 ...
4196 pi.serial_write(h1, b'\\x02\\x03\\x04')
4198 pi.serial_write(h2, b'help')
4200 pi.serial_write(h2, "hello")
4202 pi.serial_write(h1, [2, 3, 4])
4203 ...
4204 """
4205 # I p1 handle
4206 # I p2 0
4207 # I p3 len
4208 ## extension ##
4209 # s len data bytes
4211 return _u2i(_pigpio_command_ext(
4212 self.sl, _PI_CMD_SERW, handle, 0, len(data), [data]))
4214 def serial_data_available(self, handle):
4215 """
4216 Returns the number of bytes available to be read from the
4217 device associated with handle.
4219 handle:= >=0 (as returned by a prior call to [*serial_open*]).
4221 ...
4222 rdy = pi.serial_data_available(h1)
4224 if rdy > 0:
4225 (b, d) = pi.serial_read(h1, rdy)
4226 ...
4227 """
4228 return _u2i(_pigpio_command(self.sl, _PI_CMD_SERDA, handle, 0))
4230 def gpio_trigger(self, user_gpio, pulse_len=10, level=1):
4231 """
4232 Send a trigger pulse to a GPIO. The GPIO is set to
4233 level for pulse_len microseconds and then reset to not level.
4235 user_gpio:= 0-31
4236 pulse_len:= 1-100
4237 level:= 0-1
4239 ...
4240 pi.gpio_trigger(23, 10, 1)
4241 ...
4242 """
4243 # pigpio message format
4245 # I p1 user_gpio
4246 # I p2 pulse_len
4247 # I p3 4
4248 ## extension ##
4249 # I level
4250 extents = [struct.pack("I", level)]
4251 return _u2i(_pigpio_command_ext(
4252 self.sl, _PI_CMD_TRIG, user_gpio, pulse_len, 4, extents))
4254 def set_glitch_filter(self, user_gpio, steady):
4255 """
4256 Sets a glitch filter on a GPIO.
4258 Level changes on the GPIO are not reported unless the level
4259 has been stable for at least [*steady*] microseconds. The
4260 level is then reported. Level changes of less than [*steady*]
4261 microseconds are ignored.
4263 user_gpio:= 0-31
4264 steady:= 0-300000
4266 Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_BAD_FILTER.
4268 This filter affects the GPIO samples returned to callbacks set up
4269 with [*callback*] and [*wait_for_edge*].
4271 It does not affect levels read by [*read*],
4272 [*read_bank_1*], or [*read_bank_2*].
4274 Each (stable) edge will be timestamped [*steady*]
4275 microseconds after it was first detected.
4277 ...
4278 pi.set_glitch_filter(23, 100)
4279 ...
4280 """
4281 return _u2i(_pigpio_command(self.sl, _PI_CMD_FG, user_gpio, steady))
4283 def set_noise_filter(self, user_gpio, steady, active):
4284 """
4285 Sets a noise filter on a GPIO.
4287 Level changes on the GPIO are ignored until a level which has
4288 been stable for [*steady*] microseconds is detected. Level
4289 changes on the GPIO are then reported for [*active*]
4290 microseconds after which the process repeats.
4292 user_gpio:= 0-31
4293 steady:= 0-300000
4294 active:= 0-1000000
4296 Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_BAD_FILTER.
4298 This filter affects the GPIO samples returned to callbacks set up
4299 with [*callback*] and [*wait_for_edge*].
4301 It does not affect levels read by [*read*],
4302 [*read_bank_1*], or [*read_bank_2*].
4304 Level changes before and after the active period may
4305 be reported. Your software must be designed to cope with
4306 such reports.
4308 ...
4309 pi.set_noise_filter(23, 1000, 5000)
4310 ...
4311 """
4312 # pigpio message format
4314 # I p1 user_gpio
4315 # I p2 steady
4316 # I p3 4
4317 ## extension ##
4318 # I active
4319 extents = [struct.pack("I", active)]
4320 return _u2i(_pigpio_command_ext(
4321 self.sl, _PI_CMD_FN, user_gpio, steady, 4, extents))
4323 def store_script(self, script):
4324 """
4325 Store a script for later execution.
4327 See [[http://abyz.me.uk/rpi/pigpio/pigs.html#Scripts]] for
4328 details.
4330 script:= the script text as a series of bytes.
4332 Returns a >=0 script id if OK.
4334 ...
4335 sid = pi.store_script(
4336 b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0')
4337 ...
4338 """
4339 # I p1 0
4340 # I p2 0
4341 # I p3 len
4342 ## extension ##
4343 # s len data bytes
4344 if len(script):
4345 return _u2i(_pigpio_command_ext(
4346 self.sl, _PI_CMD_PROC, 0, 0, len(script), [script]))
4347 else:
4348 return 0
4350 def run_script(self, script_id, params=None):
4351 """
4352 Runs a stored script.
4354 script_id:= id of stored script.
4355 params:= up to 10 parameters required by the script.
4357 ...
4358 s = pi.run_script(sid, [par1, par2])
4360 s = pi.run_script(sid)
4362 s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
4363 ...
4364 """
4365 # I p1 script id
4366 # I p2 0
4367 # I p3 params * 4 (0-10 params)
4368 ## (optional) extension ##
4369 # I[] params
4370 if params is not None:
4371 ext = bytearray()
4372 for p in params:
4373 ext.extend(struct.pack("I", p))
4374 nump = len(params)
4375 extents = [ext]
4376 else:
4377 nump = 0
4378 extents = []
4379 return _u2i(_pigpio_command_ext(
4380 self.sl, _PI_CMD_PROCR, script_id, 0, nump*4, extents))
4382 def update_script(self, script_id, params=None):
4383 """
4384 Sets the parameters of a script. The script may or
4385 may not be running. The first parameters of the script are
4386 overwritten with the new values.
4388 script_id:= id of stored script.
4389 params:= up to 10 parameters required by the script.
4391 ...
4392 s = pi.update_script(sid, [par1, par2])
4394 s = pi.update_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
4395 ...
4396 """
4397 # I p1 script id
4398 # I p2 0
4399 # I p3 params * 4 (0-10 params)
4400 ## (optional) extension ##
4401 # I[] params
4402 if params is not None:
4403 ext = bytearray()
4404 for p in params:
4405 ext.extend(struct.pack("I", p))
4406 nump = len(params)
4407 extents = [ext]
4408 else:
4409 nump = 0
4410 extents = []
4411 return _u2i(_pigpio_command_ext(
4412 self.sl, _PI_CMD_PROCU, script_id, 0, nump*4, extents))
4414 def script_status(self, script_id):
4415 """
4416 Returns the run status of a stored script as well as the
4417 current values of parameters 0 to 9.
4419 script_id:= id of stored script.
4421 The run status may be
4423 . .
4424 PI_SCRIPT_INITING
4425 PI_SCRIPT_HALTED
4426 PI_SCRIPT_RUNNING
4427 PI_SCRIPT_WAITING
4428 PI_SCRIPT_FAILED
4429 . .
4431 The return value is a tuple of run status and a list of
4432 the 10 parameters. On error the run status will be negative
4433 and the parameter list will be empty.
4435 ...
4436 (s, pars) = pi.script_status(sid)
4437 ...
4438 """
4439 status = PI_CMD_INTERRUPTED
4440 params = ()
4441 with self.sl.l:
4442 bytes = u2i(
4443 _pigpio_command_nolock(self.sl, _PI_CMD_PROCP, script_id, 0))
4444 if bytes > 0:
4445 data = self._rxbuf(bytes)
4446 pars = struct.unpack('11i', _str(data))
4447 status = pars[0]
4448 params = pars[1:]
4449 else:
4450 status = bytes
4451 return status, params
4453 def stop_script(self, script_id):
4454 """
4455 Stops a running script.
4457 script_id:= id of stored script.
4459 ...
4460 status = pi.stop_script(sid)
4461 ...
4462 """
4463 return _u2i(_pigpio_command(self.sl, _PI_CMD_PROCS, script_id, 0))
4465 def delete_script(self, script_id):
4466 """
4467 Deletes a stored script.
4469 script_id:= id of stored script.
4471 ...
4472 status = pi.delete_script(sid)
4473 ...
4474 """
4475 return _u2i(_pigpio_command(self.sl, _PI_CMD_PROCD, script_id, 0))
4477 def bb_serial_read_open(self, user_gpio, baud, bb_bits=8):
4478 """
4479 Opens a GPIO for bit bang reading of serial data.
4481 user_gpio:= 0-31, the GPIO to use.
4482 baud:= 50-250000, the baud rate.
4483 bb_bits:= 1-32, the number of bits per word, default 8.
4485 The serial data is held in a cyclic buffer and is read using
4486 [*bb_serial_read*].
4488 It is the caller's responsibility to read data from the cyclic
4489 buffer in a timely fashion.
4491 ...
4492 status = pi.bb_serial_read_open(4, 19200)
4493 status = pi.bb_serial_read_open(17, 9600)
4494 ...
4495 """
4496 # pigpio message format
4498 # I p1 user_gpio
4499 # I p2 baud
4500 # I p3 4
4501 ## extension ##
4502 # I bb_bits
4503 extents = [struct.pack("I", bb_bits)]
4504 return _u2i(_pigpio_command_ext(
4505 self.sl, _PI_CMD_SLRO, user_gpio, baud, 4, extents))
4507 def bb_serial_read(self, user_gpio):
4508 """
4509 Returns data from the bit bang serial cyclic buffer.
4511 user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
4513 The returned value is a tuple of the number of bytes read and a
4514 bytearray containing the bytes. If there was an error the
4515 number of bytes read will be less than zero (and will contain
4516 the error code).
4518 The bytes returned for each character depend upon the number of
4519 data bits [*bb_bits*] specified in the [*bb_serial_read_open*]
4520 command.
4522 For [*bb_bits*] 1-8 there will be one byte per character.
4523 For [*bb_bits*] 9-16 there will be two bytes per character.
4524 For [*bb_bits*] 17-32 there will be four bytes per character.
4526 ...
4527 (count, data) = pi.bb_serial_read(4)
4528 ...
4529 """
4530 bytes = PI_CMD_INTERRUPTED
4531 rdata = ""
4532 with self.sl.l:
4533 bytes = u2i(
4534 _pigpio_command_nolock(self.sl, _PI_CMD_SLR, user_gpio, 10000))
4535 if bytes > 0:
4536 rdata = self._rxbuf(bytes)
4537 return bytes, rdata
4540 def bb_serial_read_close(self, user_gpio):
4541 """
4542 Closes a GPIO for bit bang reading of serial data.
4544 user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
4546 ...
4547 status = pi.bb_serial_read_close(17)
4548 ...
4549 """
4550 return _u2i(_pigpio_command(self.sl, _PI_CMD_SLRC, user_gpio, 0))
4552 def bb_serial_invert(self, user_gpio, invert):
4553 """
4554 Invert serial logic.
4556 user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
4557 invert:= 0-1 (1 invert, 0 normal)
4559 ...
4560 status = pi.bb_serial_invert(17, 1)
4561 ...
4562 """
4563 return _u2i(_pigpio_command(self.sl, _PI_CMD_SLRI, user_gpio, invert))
4566 def custom_1(self, arg1=0, arg2=0, argx=[]):
4567 """
4568 Calls a pigpio function customised by the user.
4570 arg1:= >=0, default 0.
4571 arg2:= >=0, default 0.
4572 argx:= extra arguments (each 0-255), default empty.
4574 The returned value is an integer which by convention
4575 should be >=0 for OK and <0 for error.
4577 ...
4578 value = pi.custom_1()
4580 value = pi.custom_1(23)
4582 value = pi.custom_1(0, 55)
4584 value = pi.custom_1(23, 56, [1, 5, 7])
4586 value = pi.custom_1(23, 56, b"hello")
4588 value = pi.custom_1(23, 56, "hello")
4589 ...
4590 """
4591 # I p1 arg1
4592 # I p2 arg2
4593 # I p3 len
4594 ## extension ##
4595 # s len argx bytes
4597 return u2i(_pigpio_command_ext(
4598 self.sl, _PI_CMD_CF1, arg1, arg2, len(argx), [argx]))
4600 def custom_2(self, arg1=0, argx=[], retMax=8192):
4601 """
4602 Calls a pigpio function customised by the user.
4604 arg1:= >=0, default 0.
4605 argx:= extra arguments (each 0-255), default empty.
4606 retMax:= >=0, maximum number of bytes to return, default 8192.
4608 The returned value is a tuple of the number of bytes
4609 returned and a bytearray containing the bytes. If
4610 there was an error the number of bytes read will be
4611 less than zero (and will contain the error code).
4613 ...
4614 (count, data) = pi.custom_2()
4616 (count, data) = pi.custom_2(23)
4618 (count, data) = pi.custom_2(23, [1, 5, 7])
4620 (count, data) = pi.custom_2(23, b"hello")
4622 (count, data) = pi.custom_2(23, "hello", 128)
4623 ...
4624 """
4625 # I p1 arg1
4626 # I p2 retMax
4627 # I p3 len
4628 ## extension ##
4629 # s len argx bytes
4631 bytes = PI_CMD_INTERRUPTED
4632 rdata = ""
4633 with self.sl.l:
4634 bytes = u2i(_pigpio_command_ext_nolock(
4635 self.sl, _PI_CMD_CF2, arg1, retMax, len(argx), [argx]))
4636 if bytes > 0:
4637 rdata = self._rxbuf(bytes)
4638 return bytes, rdata
4640 def get_pad_strength(self, pad):
4641 """
4642 This function returns the pad drive strength in mA.
4644 pad:= 0-2, the pad to get.
4646 Returns the pad drive strength if OK, otherwise PI_BAD_PAD.
4648 Pad @ GPIO
4649 0 @ 0-27
4650 1 @ 28-45
4651 2 @ 46-53
4653 ...
4654 strength = pi.get_pad_strength(0) # Get pad 0 strength.
4655 ...
4656 """
4657 return _u2i(_pigpio_command(self.sl, _PI_CMD_PADG, pad, 0))
4659 def set_pad_strength(self, pad, pad_strength):
4660 """
4661 This function sets the pad drive strength in mA.
4664 pad:= 0-2, the pad to set.
4665 pad_strength:= 1-16 mA.
4667 Returns 0 if OK, otherwise PI_BAD_PAD, or PI_BAD_STRENGTH.
4669 Pad @ GPIO
4670 0 @ 0-27
4671 1 @ 28-45
4672 2 @ 46-53
4674 ...
4675 pi.set_pad_strength(2, 14) # Set pad 2 to 14 mA.
4676 ...
4677 """
4678 return _u2i(_pigpio_command(self.sl, _PI_CMD_PADS, pad, pad_strength))
4681 def file_open(self, file_name, file_mode):
4682 """
4683 This function returns a handle to a file opened in a specified mode.
4685 file_name:= the file to open.
4686 file_mode:= the file open mode.
4688 Returns a handle (>=0) if OK, otherwise PI_NO_HANDLE,
4689 PI_NO_FILE_ACCESS, PI_BAD_FILE_MODE,
4690 PI_FILE_OPEN_FAILED, or PI_FILE_IS_A_DIR.
4692 ...
4693 h = pi.file_open("/home/pi/shared/dir_3/file.txt",
4694 pigpio.FILE_WRITE | pigpio.FILE_CREATE)
4696 pi.file_write(h, "Hello world")
4698 pi.file_close(h)
4699 ...
4701 File
4703 A file may only be opened if permission is granted by an entry
4704 in /opt/pigpio/access. This is intended to allow remote access
4705 to files in a more or less controlled manner.
4707 Each entry in /opt/pigpio/access takes the form of a file path
4708 which may contain wildcards followed by a single letter permission.
4709 The permission may be R for read, W for write, U for read/write,
4710 and N for no access.
4712 Where more than one entry matches a file the most specific rule
4713 applies. If no entry matches a file then access is denied.
4715 Suppose /opt/pigpio/access contains the following entries:
4717 . .
4718 /home/* n
4719 /home/pi/shared/dir_1/* w
4720 /home/pi/shared/dir_2/* r
4721 /home/pi/shared/dir_3/* u
4722 /home/pi/shared/dir_1/file.txt n
4723 . .
4725 Files may be written in directory dir_1 with the exception
4726 of file.txt.
4728 Files may be read in directory dir_2.
4730 Files may be read and written in directory dir_3.
4732 If a directory allows read, write, or read/write access then files
4733 may be created in that directory.
4735 In an attempt to prevent risky permissions the following paths are
4736 ignored in /opt/pigpio/access:
4738 . .
4739 a path containing ..
4740 a path containing only wildcards (*?)
4741 a path containing less than two non-wildcard parts
4742 . .
4744 Mode
4746 The mode may have the following values:
4748 Constant @ Value @ Meaning
4749 FILE_READ @ 1 @ open file for reading
4750 FILE_WRITE @ 2 @ open file for writing
4751 FILE_RW @ 3 @ open file for reading and writing
4753 The following values may be or'd into the mode:
4755 Name @ Value @ Meaning
4756 FILE_APPEND @ 4 @ All writes append data to the end of the file
4757 FILE_CREATE @ 8 @ The file is created if it doesn't exist
4758 FILE_TRUNC @ 16 @ The file is truncated
4760 Newly created files are owned by root with permissions owner
4761 read and write.
4763 ...
4764 #!/usr/bin/env python
4766 import pigpio
4768 pi = pigpio.pi()
4770 if not pi.connected:
4771 exit()
4773 # Assumes /opt/pigpio/access contains the following line:
4774 # /ram/*.c r
4776 handle = pi.file_open("/ram/pigpio.c", pigpio.FILE_READ)
4778 done = False
4780 while not done:
4781 c, d = pi.file_read(handle, 60000)
4782 if c > 0:
4783 print(d)
4784 else:
4785 done = True
4787 pi.file_close(handle)
4789 pi.stop()
4790 ...
4791 """
4792 # I p1 file_mode
4793 # I p2 0
4794 # I p3 len
4795 ## extension ##
4796 # s len data bytes
4797 return _u2i(_pigpio_command_ext(
4798 self.sl, _PI_CMD_FO, file_mode, 0, len(file_name), [file_name]))
4800 def file_close(self, handle):
4801 """
4802 Closes the file associated with handle.
4804 handle:= >=0 (as returned by a prior call to [*file_open*]).
4806 ...
4807 pi.file_close(handle)
4808 ...
4809 """
4810 return _u2i(_pigpio_command(self.sl, _PI_CMD_FC, handle, 0))
4812 def file_read(self, handle, count):
4813 """
4814 Reads up to count bytes from the file associated with handle.
4816 handle:= >=0 (as returned by a prior call to [*file_open*]).
4817 count:= >0, the number of bytes to read.
4819 The returned value is a tuple of the number of bytes read and a
4820 bytearray containing the bytes. If there was an error the
4821 number of bytes read will be less than zero (and will contain
4822 the error code).
4824 ...
4825 (b, d) = pi.file_read(h2, 100)
4826 if b > 0:
4827 # process read data
4828 ...
4829 """
4830 bytes = PI_CMD_INTERRUPTED
4831 rdata = ""
4832 with self.sl.l:
4833 bytes = u2i(
4834 _pigpio_command_nolock(self.sl, _PI_CMD_FR, handle, count))
4835 if bytes > 0:
4836 rdata = self._rxbuf(bytes)
4837 return bytes, rdata
4839 def file_write(self, handle, data):
4840 """
4841 Writes the data bytes to the file associated with handle.
4843 handle:= >=0 (as returned by a prior call to [*file_open*]).
4844 data:= the bytes to write.
4846 ...
4847 pi.file_write(h1, b'\\x02\\x03\\x04')
4849 pi.file_write(h2, b'help')
4851 pi.file_write(h2, "hello")
4853 pi.file_write(h1, [2, 3, 4])
4854 ...
4855 """
4856 # I p1 handle
4857 # I p2 0
4858 # I p3 len
4859 ## extension ##
4860 # s len data bytes
4862 return _u2i(_pigpio_command_ext(
4863 self.sl, _PI_CMD_FW, handle, 0, len(data), [data]))
4865 def file_seek(self, handle, seek_offset, seek_from):
4866 """
4867 Seeks to a position relative to the start, current position,
4868 or end of the file. Returns the new position.
4870 handle:= >=0 (as returned by a prior call to [*file_open*]).
4871 seek_offset:= byte offset.
4872 seek_from:= FROM_START, FROM_CURRENT, or FROM_END.
4874 ...
4875 new_pos = pi.file_seek(h, 100, pigpio.FROM_START)
4877 cur_pos = pi.file_seek(h, 0, pigpio.FROM_CURRENT)
4879 file_size = pi.file_seek(h, 0, pigpio.FROM_END)
4880 ...
4881 """
4882 # I p1 handle
4883 # I p2 seek_offset
4884 # I p3 4
4885 ## extension ##
4886 # I seek_from
4887 extents = [struct.pack("I", seek_from)]
4888 return _u2i(_pigpio_command_ext(
4889 self.sl, _PI_CMD_FS, handle, seek_offset, 4, extents))
4891 def file_list(self, fpattern):
4892 """
4893 Returns a list of files which match a pattern.
4895 fpattern:= file pattern to match.
4897 Returns the number of returned bytes if OK, otherwise
4898 PI_NO_FILE_ACCESS, or PI_NO_FILE_MATCH.
4900 The pattern must match an entry in /opt/pigpio/access. The
4901 pattern may contain wildcards. See [*file_open*].
4903 NOTE
4905 The returned value is not the number of files, it is the number
4906 of bytes in the buffer. The file names are separated by newline
4907 characters.
4909 ...
4910 #!/usr/bin/env python
4912 import pigpio
4914 pi = pigpio.pi()
4916 if not pi.connected:
4917 exit()
4919 # Assumes /opt/pigpio/access contains the following line:
4920 # /ram/*.c r
4922 c, d = pi.file_list("/ram/p*.c")
4923 if c > 0:
4924 print(d)
4926 pi.stop()
4927 ...
4928 """
4929 # I p1 60000
4930 # I p2 0
4931 # I p3 len
4932 ## extension ##
4933 # s len data bytes
4935 bytes = PI_CMD_INTERRUPTED
4936 rdata = ""
4937 with self.sl.l:
4938 bytes = u2i(_pigpio_command_ext_nolock(
4939 self.sl, _PI_CMD_FL, 60000, 0, len(fpattern), [fpattern]))
4940 if bytes > 0:
4941 rdata = self._rxbuf(bytes)
4942 return bytes, rdata
4944 def shell(self, shellscr, pstring=""):
4945 """
4946 This function uses the system call to execute a shell script
4947 with the given string as its parameter.
4949 shellscr:= the name of the script, only alphanumerics,
4950 '-' and '_' are allowed in the name
4951 pstring := the parameter string to pass to the script
4953 The exit status of the system call is returned if OK,
4954 otherwise PI_BAD_SHELL_STATUS.
4956 [*shellscr*] must exist in /opt/pigpio/cgi and must be executable.
4958 The returned exit status is normally 256 times that set by
4959 the shell script exit function. If the script can't be
4960 found 32512 will be returned.
4962 The following table gives some example returned statuses:
4964 Script exit status @ Returned system call status
4965 1 @ 256
4966 5 @ 1280
4967 10 @ 2560
4968 200 @ 51200
4969 script not found @ 32512
4971 ...
4972 // pass two parameters, hello and world
4973 status = pi.shell("scr1", "hello world");
4975 // pass three parameters, hello, string with spaces, and world
4976 status = pi.shell("scr1", "hello 'string with spaces' world");
4978 // pass one parameter, hello string with spaces world
4979 status = pi.shell("scr1", "\\"hello string with spaces world\\"");
4980 ...
4981 """
4982 # I p1 len(shellscr)
4983 # I p2 0
4984 # I p3 len(shellscr)+len(pstring)+1
4985 ## extension ##
4986 # s len data bytes
4988 ls = len(shellscr)
4989 lp = len(pstring)
4990 return _u2i(_pigpio_command_ext(
4991 self.sl, _PI_CMD_SHELL, ls, 0, ls+lp+1, [shellscr+'\x00'+pstring]))
4994 def callback(self, user_gpio, edge=RISING_EDGE, func=None):
4995 """
4996 Calls a user supplied function (a callback) whenever the
4997 specified GPIO edge is detected.
4999 user_gpio:= 0-31.
5000 edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
5001 func:= user supplied callback function.
5003 The user supplied callback receives three parameters, the GPIO,
5004 the level, and the tick.
5006 . .
5007 Parameter Value Meaning
5009 GPIO 0-31 The GPIO which has changed state
5011 level 0-2 0 = change to low (a falling edge)
5012 1 = change to high (a rising edge)
5013 2 = no level change (a watchdog timeout)
5015 tick 32 bit The number of microseconds since boot
5016 WARNING: this wraps around from
5017 4294967295 to 0 roughly every 72 minutes
5018 . .
5020 If a user callback is not specified a default tally callback is
5021 provided which simply counts edges. The count may be retrieved
5022 by calling the tally function. The count may be reset to zero
5023 by calling the reset_tally function.
5025 The callback may be cancelled by calling the cancel function.
5027 A GPIO may have multiple callbacks (although I can't think of
5028 a reason to do so).
5030 The GPIO are sampled at a rate set when the pigpio daemon
5031 is started (default 5 us).
5033 The number of samples per second is given in the following table.
5035 . .
5036 samples
5037 per sec
5039 1 1,000,000
5040 2 500,000
5041 sample 4 250,000
5042 rate 5 200,000
5043 (us) 8 125,000
5044 10 100,000
5045 . .
5047 GPIO level changes shorter than the sample rate may be missed.
5049 The daemon software which generates the callbacks is triggered
5050 1000 times per second. The callbacks will be called once per
5051 level change since the last time they were called.
5052 i.e. The callbacks will get all level changes but there will
5053 be a latency.
5055 If you want to track the level of more than one GPIO do so by
5056 maintaining the state in the callback. Do not use [*read*].
5057 Remember the event that triggered the callback may have
5058 happened several milliseconds before and the GPIO may have
5059 changed level many times since then.
5061 ...
5062 def cbf(gpio, level, tick):
5063 print(gpio, level, tick)
5065 cb1 = pi.callback(22, pigpio.EITHER_EDGE, cbf)
5067 cb2 = pi.callback(4, pigpio.EITHER_EDGE)
5069 cb3 = pi.callback(17)
5071 print(cb3.tally())
5073 cb3.reset_tally()
5075 cb1.cancel() # To cancel callback cb1.
5076 ...
5077 """
5078 return _callback(self._notify, user_gpio, edge, func)
5080 def event_callback(self, event, func=None):
5081 """
5082 Calls a user supplied function (a callback) whenever the
5083 specified event is signalled.
5085 event:= 0-31.
5086 func:= user supplied callback function.
5088 The user supplied callback receives two parameters, the event id,
5089 and the tick.
5091 If a user callback is not specified a default tally callback is
5092 provided which simply counts events. The count may be retrieved
5093 by calling the tally function. The count may be reset to zero
5094 by calling the reset_tally function.
5096 The callback may be canceled by calling the cancel function.
5098 An event may have multiple callbacks (although I can't think of
5099 a reason to do so).
5101 ...
5102 def cbf(event, tick):
5103 print(event, tick)
5105 cb1 = pi.event_callback(22, cbf)
5107 cb2 = pi.event_callback(4)
5109 print(cb2.tally())
5111 cb2.reset_tally()
5113 cb1.cancel() # To cancel callback cb1.
5114 ...
5115 """
5117 return _event(self._notify, event, func)
5119 def wait_for_edge(self, user_gpio, edge=RISING_EDGE, wait_timeout=60.0):
5120 """
5121 Wait for an edge event on a GPIO.
5123 user_gpio:= 0-31.
5124 edge:= EITHER_EDGE, RISING_EDGE (default), or
5125 FALLING_EDGE.
5126 wait_timeout:= >=0.0 (default 60.0).
5128 The function returns when the edge is detected or after
5129 the number of seconds specified by timeout has expired.
5131 Do not use this function for precise timing purposes,
5132 the edge is only checked 20 times a second. Whenever
5133 you need to know the accurate time of GPIO events use
5134 a [*callback*] function.
5136 The function returns True if the edge is detected,
5137 otherwise False.
5139 ...
5140 if pi.wait_for_edge(23):
5141 print("Rising edge detected")
5142 else:
5143 print("wait for edge timed out")
5145 if pi.wait_for_edge(23, pigpio.FALLING_EDGE, 5.0):
5146 print("Falling edge detected")
5147 else:
5148 print("wait for falling edge timed out")
5149 ...
5150 """
5151 a = _wait_for_edge(self._notify, user_gpio, edge, wait_timeout)
5152 return a.trigger
5154 def wait_for_event(self, event, wait_timeout=60.0):
5155 """
5156 Wait for an event.
5158 event:= 0-31.
5159 wait_timeout:= >=0.0 (default 60.0).
5161 The function returns when the event is signalled or after
5162 the number of seconds specified by timeout has expired.
5164 The function returns True if the event is detected,
5165 otherwise False.
5167 ...
5168 if pi.wait_for_event(23):
5169 print("event detected")
5170 else:
5171 print("wait for event timed out")
5172 ...
5173 """
5174 a = _wait_for_event(self._notify, event, wait_timeout)
5175 return a.trigger
5177 def __init__(self,
5178 host = os.getenv("PIGPIO_ADDR", 'localhost'),
5179 port = os.getenv("PIGPIO_PORT", 8888),
5180 show_errors = True):
5181 """
5182 Grants access to a Pi's GPIO.
5184 host:= the host name of the Pi on which the pigpio daemon is
5185 running. The default is localhost unless overridden by
5186 the PIGPIO_ADDR environment variable.
5188 port:= the port number on which the pigpio daemon is listening.
5189 The default is 8888 unless overridden by the PIGPIO_PORT
5190 environment variable. The pigpio daemon must have been
5191 started with the same port number.
5193 This connects to the pigpio daemon and reserves resources
5194 to be used for sending commands and receiving notifications.
5196 An instance attribute [*connected*] may be used to check the
5197 success of the connection. If the connection is established
5198 successfully [*connected*] will be True, otherwise False.
5200 ...
5201 pi = pigio.pi() # use defaults
5202 pi = pigpio.pi('mypi') # specify host, default port
5203 pi = pigpio.pi('mypi', 7777) # specify host and port
5205 pi = pigpio.pi() # exit script if no connection
5206 if not pi.connected:
5207 exit()
5208 ...
5209 """
5210 self.connected = True
5212 self.sl = _socklock()
5213 self._notify = None
5215 port = int(port)
5217 if host == '':
5218 host = "localhost"
5220 self._host = host
5221 self._port = port
5223 try:
5224 self.sl.s = socket.create_connection((host, port), None)
5226 # Disable the Nagle algorithm.
5227 self.sl.s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
5229 self._notify = _callback_thread(self.sl, host, port)
5231 except socket.error:
5232 exception = 1
5234 except struct.error:
5235 exception = 2
5237 except error:
5238 # assumed to be no handle available
5239 exception = 3
5241 else:
5242 exception = 0
5243 atexit.register(self.stop)
5245 if exception != 0:
5247 self.connected = False
5249 if self.sl.s is not None:
5250 self.sl.s = None
5252 if show_errors:
5254 s = "Can't connect to pigpio at {}({})".format(host, str(port))
5257 print(_except_a.format(s))
5258 if exception == 1:
5259 print(_except_1)
5260 elif exception == 2:
5261 print(_except_2)
5262 else:
5263 print(_except_3)
5264 print(_except_z)
5266 def __repr__(self):
5267 return "<pipio.pi host={} port={}>".format(self._host, self._port)
5269 def stop(self):
5270 """Release pigpio resources.
5272 ...
5273 pi.stop()
5274 ...
5275 """
5277 self.connected = False
5279 if self._notify is not None:
5280 self._notify.stop()
5281 self._notify = None
5283 if self.sl.s is not None:
5284 self.sl.s.close()
5285 self.sl.s = None
5287def xref():
5288 """
5289 active: 0-1000000
5290 The number of microseconds level changes are reported for once
5291 a noise filter has been triggered (by [*steady*] microseconds of
5292 a stable level).
5295 arg1:
5296 An unsigned argument passed to a user customised function. Its
5297 meaning is defined by the customiser.
5299 arg2:
5300 An unsigned argument passed to a user customised function. Its
5301 meaning is defined by the customiser.
5303 argx:
5304 An array of bytes passed to a user customised function.
5305 Its meaning and content is defined by the customiser.
5307 baud:
5308 The speed of serial communication (I2C, SPI, serial link, waves)
5309 in bits per second.
5311 bb_bits: 1-32
5312 The number of data bits to be used when adding serial data to a
5313 waveform.
5315 bb_stop: 2-8
5316 The number of (half) stop bits to be used when adding serial data
5317 to a waveform.
5319 bit: 0-1
5320 A value of 0 or 1.
5322 bits: 32 bit number
5323 A mask used to select GPIO to be operated on. If bit n is set
5324 then GPIO n is selected. A convenient way of setting bit n is to
5325 bit or in the value (1<<n).
5327 To select GPIO 1, 7, 23
5329 bits = (1<<1) | (1<<7) | (1<<23)
5331 bsc_control:
5333 . .
5334 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
5335 a a a a a a a - - IT HC TF IR RE TE BK EC ES PL PH I2 SP EN
5336 . .
5338 aaaaaaa defines the I2C slave address (only relevant in I2C mode)
5340 Bits 0-13 are copied unchanged to the BSC CR register. See
5341 pages 163-165 of the Broadcom peripherals document.
5343 byte_val: 0-255
5344 A whole number.
5346 clkfreq: 4689-250M (13184-375M for the BCM2711)
5347 The hardware clock frequency.
5349 connected:
5350 True if a connection was established, False otherwise.
5352 count:
5353 The number of bytes of data to be transferred.
5355 CS:
5356 The GPIO used for the slave select signal when bit banging SPI.
5358 data:
5359 Data to be transmitted, a series of bytes.
5361 delay: >=1
5362 The length of a pulse in microseconds.
5364 dutycycle: 0-range_
5365 A number between 0 and range_.
5367 The dutycycle sets the proportion of time on versus time off during each
5368 PWM cycle.
5370 Dutycycle @ On time
5371 0 @ Off
5372 range_ * 0.25 @ 25% On
5373 range_ * 0.50 @ 50% On
5374 range_ * 0.75 @ 75% On
5375 range_ @ Fully On
5377 edge: 0-2
5379 . .
5380 EITHER_EDGE = 2
5381 FALLING_EDGE = 1
5382 RISING_EDGE = 0
5383 . .
5385 errnum: <0
5387 . .
5388 PI_BAD_USER_GPIO = -2
5389 PI_BAD_GPIO = -3
5390 PI_BAD_MODE = -4
5391 PI_BAD_LEVEL = -5
5392 PI_BAD_PUD = -6
5393 PI_BAD_PULSEWIDTH = -7
5394 PI_BAD_DUTYCYCLE = -8
5395 PI_BAD_WDOG_TIMEOUT = -15
5396 PI_BAD_DUTYRANGE = -21
5397 PI_NO_HANDLE = -24
5398 PI_BAD_HANDLE = -25
5399 PI_BAD_WAVE_BAUD = -35
5400 PI_TOO_MANY_PULSES = -36
5401 PI_TOO_MANY_CHARS = -37
5402 PI_NOT_SERIAL_GPIO = -38
5403 PI_NOT_PERMITTED = -41
5404 PI_SOME_PERMITTED = -42
5405 PI_BAD_WVSC_COMMND = -43
5406 PI_BAD_WVSM_COMMND = -44
5407 PI_BAD_WVSP_COMMND = -45
5408 PI_BAD_PULSELEN = -46
5409 PI_BAD_SCRIPT = -47
5410 PI_BAD_SCRIPT_ID = -48
5411 PI_BAD_SER_OFFSET = -49
5412 PI_GPIO_IN_USE = -50
5413 PI_BAD_SERIAL_COUNT = -51
5414 PI_BAD_PARAM_NUM = -52
5415 PI_DUP_TAG = -53
5416 PI_TOO_MANY_TAGS = -54
5417 PI_BAD_SCRIPT_CMD = -55
5418 PI_BAD_VAR_NUM = -56
5419 PI_NO_SCRIPT_ROOM = -57
5420 PI_NO_MEMORY = -58
5421 PI_SOCK_READ_FAILED = -59
5422 PI_SOCK_WRIT_FAILED = -60
5423 PI_TOO_MANY_PARAM = -61
5424 PI_SCRIPT_NOT_READY = -62
5425 PI_BAD_TAG = -63
5426 PI_BAD_MICS_DELAY = -64
5427 PI_BAD_MILS_DELAY = -65
5428 PI_BAD_WAVE_ID = -66
5429 PI_TOO_MANY_CBS = -67
5430 PI_TOO_MANY_OOL = -68
5431 PI_EMPTY_WAVEFORM = -69
5432 PI_NO_WAVEFORM_ID = -70
5433 PI_I2C_OPEN_FAILED = -71
5434 PI_SER_OPEN_FAILED = -72
5435 PI_SPI_OPEN_FAILED = -73
5436 PI_BAD_I2C_BUS = -74
5437 PI_BAD_I2C_ADDR = -75
5438 PI_BAD_SPI_CHANNEL = -76
5439 PI_BAD_FLAGS = -77
5440 PI_BAD_SPI_SPEED = -78
5441 PI_BAD_SER_DEVICE = -79
5442 PI_BAD_SER_SPEED = -80
5443 PI_BAD_PARAM = -81
5444 PI_I2C_WRITE_FAILED = -82
5445 PI_I2C_READ_FAILED = -83
5446 PI_BAD_SPI_COUNT = -84
5447 PI_SER_WRITE_FAILED = -85
5448 PI_SER_READ_FAILED = -86
5449 PI_SER_READ_NO_DATA = -87
5450 PI_UNKNOWN_COMMAND = -88
5451 PI_SPI_XFER_FAILED = -89
5452 PI_NO_AUX_SPI = -91
5453 PI_NOT_PWM_GPIO = -92
5454 PI_NOT_SERVO_GPIO = -93
5455 PI_NOT_HCLK_GPIO = -94
5456 PI_NOT_HPWM_GPIO = -95
5457 PI_BAD_HPWM_FREQ = -96
5458 PI_BAD_HPWM_DUTY = -97
5459 PI_BAD_HCLK_FREQ = -98
5460 PI_BAD_HCLK_PASS = -99
5461 PI_HPWM_ILLEGAL = -100
5462 PI_BAD_DATABITS = -101
5463 PI_BAD_STOPBITS = -102
5464 PI_MSG_TOOBIG = -103
5465 PI_BAD_MALLOC_MODE = -104
5466 PI_BAD_SMBUS_CMD = -107
5467 PI_NOT_I2C_GPIO = -108
5468 PI_BAD_I2C_WLEN = -109
5469 PI_BAD_I2C_RLEN = -110
5470 PI_BAD_I2C_CMD = -111
5471 PI_BAD_I2C_BAUD = -112
5472 PI_CHAIN_LOOP_CNT = -113
5473 PI_BAD_CHAIN_LOOP = -114
5474 PI_CHAIN_COUNTER = -115
5475 PI_BAD_CHAIN_CMD = -116
5476 PI_BAD_CHAIN_DELAY = -117
5477 PI_CHAIN_NESTING = -118
5478 PI_CHAIN_TOO_BIG = -119
5479 PI_DEPRECATED = -120
5480 PI_BAD_SER_INVERT = -121
5481 PI_BAD_FOREVER = -124
5482 PI_BAD_FILTER = -125
5483 PI_BAD_PAD = -126
5484 PI_BAD_STRENGTH = -127
5485 PI_FIL_OPEN_FAILED = -128
5486 PI_BAD_FILE_MODE = -129
5487 PI_BAD_FILE_FLAG = -130
5488 PI_BAD_FILE_READ = -131
5489 PI_BAD_FILE_WRITE = -132
5490 PI_FILE_NOT_ROPEN = -133
5491 PI_FILE_NOT_WOPEN = -134
5492 PI_BAD_FILE_SEEK = -135
5493 PI_NO_FILE_MATCH = -136
5494 PI_NO_FILE_ACCESS = -137
5495 PI_FILE_IS_A_DIR = -138
5496 PI_BAD_SHELL_STATUS = -139
5497 PI_BAD_SCRIPT_NAME = -140
5498 PI_BAD_SPI_BAUD = -141
5499 PI_NOT_SPI_GPIO = -142
5500 PI_BAD_EVENT_ID = -143
5501 PI_CMD_INTERRUPTED = -144
5502 PI_NOT_ON_BCM2711 = -145
5503 PI_ONLY_ON_BCM2711 = -146
5504 . .
5506 event:0-31
5507 An event is a signal used to inform one or more consumers
5508 to start an action.
5510 file_mode:
5511 The mode may have the following values
5513 . .
5514 FILE_READ 1
5515 FILE_WRITE 2
5516 FILE_RW 3
5517 . .
5519 The following values can be or'd into the file open mode
5521 . .
5522 FILE_APPEND 4
5523 FILE_CREATE 8
5524 FILE_TRUNC 16
5525 . .
5527 file_name:
5528 A full file path. To be accessible the path must match
5529 an entry in /opt/pigpio/access.
5531 fpattern:
5532 A file path which may contain wildcards. To be accessible the path
5533 must match an entry in /opt/pigpio/access.
5535 frequency: 0-40000
5536 Defines the frequency to be used for PWM on a GPIO.
5537 The closest permitted frequency will be used.
5539 func:
5540 A user supplied callback function.
5542 gpio: 0-53
5543 A Broadcom numbered GPIO. All the user GPIO are in the range 0-31.
5545 There are 54 General Purpose Input Outputs (GPIO) named GPIO0
5546 through GPIO53.
5548 They are split into two banks. Bank 1 consists of GPIO0
5549 through GPIO31. Bank 2 consists of GPIO32 through GPIO53.
5551 All the GPIO which are safe for the user to read and write are in
5552 bank 1. Not all GPIO in bank 1 are safe though. Type 1 boards
5553 have 17 safe GPIO. Type 2 boards have 21. Type 3 boards have 26.
5555 See [*get_hardware_revision*].
5557 The user GPIO are marked with an X in the following table
5559 . .
5560 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
5561 Type 1 X X - - X - - X X X X X - - X X
5562 Type 2 - - X X X - - X X X X X - - X X
5563 Type 3 X X X X X X X X X X X X X X
5565 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
5566 Type 1 - X X - - X X X X X - - - - - -
5567 Type 2 - X X - - - X X X X - X X X X X
5568 Type 3 X X X X X X X X X X X X - - - -
5569 . .
5571 gpio_off:
5572 A mask used to select GPIO to be operated on. See [*bits*].
5574 This mask selects the GPIO to be switched off at the start
5575 of a pulse.
5577 gpio_on:
5578 A mask used to select GPIO to be operated on. See [*bits*].
5580 This mask selects the GPIO to be switched on at the start
5581 of a pulse.
5583 handle: >=0
5584 A number referencing an object opened by one of the following
5586 [*file_open*]
5587 [*i2c_open*]
5588 [*notify_open*]
5589 [*serial_open*]
5590 [*spi_open*]
5592 host:
5593 The name or IP address of the Pi running the pigpio daemon.
5595 i2c_address: 0-0x7F
5596 The address of a device on the I2C bus.
5598 i2c_bus: >=0
5599 An I2C bus number.
5601 i2c_flags: 0
5602 No I2C flags are currently defined.
5604 invert: 0-1
5605 A flag used to set normal or inverted bit bang serial data
5606 level logic.
5608 level: 0-1 (2)
5610 . .
5611 CLEAR = 0
5612 HIGH = 1
5613 LOW = 0
5614 OFF = 0
5615 ON = 1
5616 SET = 1
5617 TIMEOUT = 2 # only returned for a watchdog timeout
5618 . .
5620 MISO:
5621 The GPIO used for the MISO signal when bit banging SPI.
5623 mode:
5625 1.The operational mode of a GPIO, normally INPUT or OUTPUT.
5627 . .
5628 ALT0 = 4
5629 ALT1 = 5
5630 ALT2 = 6
5631 ALT3 = 7
5632 ALT4 = 3
5633 ALT5 = 2
5634 INPUT = 0
5635 OUTPUT = 1
5636 . .
5638 2. The mode of waveform transmission.
5640 . .
5641 WAVE_MODE_ONE_SHOT = 0
5642 WAVE_MODE_REPEAT = 1
5643 WAVE_MODE_ONE_SHOT_SYNC = 2
5644 WAVE_MODE_REPEAT_SYNC = 3
5645 . .
5647 MOSI:
5648 The GPIO used for the MOSI signal when bit banging SPI.
5650 offset: >=0
5651 The offset wave data starts from the beginning of the waveform
5652 being currently defined.
5654 pad: 0-2
5655 A set of GPIO which share common drivers.
5657 Pad @ GPIO
5658 0 @ 0-27
5659 1 @ 28-45
5660 2 @ 46-53
5662 pad_strength: 1-16
5663 The mA which may be drawn from each GPIO whilst still guaranteeing the
5664 high and low levels.
5666 params: 32 bit number
5667 When scripts are started they can receive up to 10 parameters
5668 to define their operation.
5670 percent:: 0-100
5671 The size of waveform as percentage of maximum available.
5673 port:
5674 The port used by the pigpio daemon, defaults to 8888.
5676 pstring:
5677 The string to be passed to a [*shell*] script to be executed.
5679 pud: 0-2
5680 . .
5681 PUD_DOWN = 1
5682 PUD_OFF = 0
5683 PUD_UP = 2
5684 . .
5686 pulse_len: 1-100
5687 The length of the trigger pulse in microseconds.
5689 pulses:
5690 A list of class pulse objects defining the characteristics of a
5691 waveform.
5693 pulsewidth:
5694 The servo pulsewidth in microseconds. 0 switches pulses off.
5696 PWMduty: 0-1000000 (1M)
5697 The hardware PWM dutycycle.
5699 PWMfreq: 1-125M (1-187.5M for the BCM2711)
5700 The hardware PWM frequency.
5702 range_: 25-40000
5703 Defines the limits for the [*dutycycle*] parameter.
5705 range_ defaults to 255.
5707 reg: 0-255
5708 An I2C device register. The usable registers depend on the
5709 actual device.
5711 retMax: >=0
5712 The maximum number of bytes a user customised function
5713 should return, default 8192.
5715 SCL:
5716 The user GPIO to use for the clock when bit banging I2C.
5718 SCLK::
5719 The GPIO used for the SCLK signal when bit banging SPI.
5721 script:
5722 The text of a script to store on the pigpio daemon.
5724 script_id: >=0
5725 A number referencing a script created by [*store_script*].
5727 SDA:
5728 The user GPIO to use for data when bit banging I2C.
5730 seek_from: 0-2
5731 Direction to seek for [*file_seek*].
5733 . .
5734 FROM_START=0
5735 FROM_CURRENT=1
5736 FROM_END=2
5737 . .
5739 seek_offset:
5740 The number of bytes to move forward (positive) or backwards
5741 (negative) from the seek position (start, current, or end of file).
5743 ser_flags: 32 bit
5744 No serial flags are currently defined.
5746 serial_*:
5747 One of the serial_ functions.
5749 shellscr:
5750 The name of a shell script. The script must exist
5751 in /opt/pigpio/cgi and must be executable.
5753 show_errors:
5754 Controls the display of pigpio daemon connection failures.
5755 The default of True prints the probable failure reasons to
5756 standard output.
5758 spi_channel: 0-2
5759 A SPI channel.
5761 spi_flags: 32 bit
5762 See [*spi_open*].
5764 steady: 0-300000
5766 The number of microseconds level changes must be stable for
5767 before reporting the level changed ([*set_glitch_filter*])
5768 or triggering the active part of a noise filter
5769 ([*set_noise_filter*]).
5771 t1:
5772 A tick (earlier).
5774 t2:
5775 A tick (later).
5777 tty:
5778 A Pi serial tty device, e.g. /dev/ttyAMA0, /dev/ttyUSB0
5780 uint32:
5781 An unsigned 32 bit number.
5783 user_gpio: 0-31
5784 A Broadcom numbered GPIO.
5786 All the user GPIO are in the range 0-31.
5788 Not all the GPIO within this range are usable, some are reserved
5789 for system use.
5791 See [*gpio*].
5793 wait_timeout: 0.0 -
5794 The number of seconds to wait in [*wait_for_edge*] before timing out.
5796 wave_add_*:
5797 One of the following
5799 [*wave_add_new*]
5800 [*wave_add_generic*]
5801 [*wave_add_serial*]
5803 wave_id: >=0
5804 A number referencing a wave created by [*wave_create*].
5806 wave_send_*:
5807 One of the following
5809 [*wave_send_once*]
5810 [*wave_send_repeat*]
5812 wdog_timeout: 0-60000
5813 Defines a GPIO watchdog timeout in milliseconds. If no level
5814 change is detected on the GPIO for timeout millisecond a watchdog
5815 timeout report is issued (with level TIMEOUT).
5817 word_val: 0-65535
5818 A whole number.
5819 """
5820 pass