diff --git a/.gitignore b/.gitignore index f67291c..fcdcc13 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ *.o *.so +*.so.* *.pyc pig2vcd pigpiod @@ -11,3 +12,12 @@ __pycache__ build dist *.egg-info + +tmp/ + +# DOC files +DOC/dbase/pigpio.sqlite.* +DOC/tmp +DOC/MAN/* +!DOC/MAN/README* +DOC/HTML/*.html diff --git a/CMakeLists.txt b/CMakeLists.txt index b36b0d6..383c445 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,15 @@ cmake_minimum_required(VERSION 3.0) -project(pigpio) +project(pigpio LANGUAGES C VERSION 0.71) -set(CMAKE_C_FLAGS "-O3 -Wall -pthread") -set(PIGPIO_FLAGS "-L. -lrt") -#set(DESTDIR ${CMAKE_CURRENT_SOURCE_DIR}/build/dest) +list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake) -if(NOT DEFINED BUILD_SHARED_LIBS) -set(BUILD_SHARED_LIBS "ON") -endif(NOT DEFINED BUILD_SHARED_LIBS) +find_package(Threads REQUIRED) +find_package(RT REQUIRED) + +option(BUILD_SHARED_LIBS "Create shared libraries" ON) + +add_compile_options(-Wall) # libpigpio.(so|a) add_library(pigpio pigpio.c command.c custom.cext) @@ -19,62 +20,76 @@ add_library(pigpiod_if pigpiod_if.c command.c) # libpigpiod_if2.(so|a) add_library(pigpiod_if2 pigpiod_if2.c command.c) - # x_pigpio add_executable(x_pigpio x_pigpio.c) -add_dependencies(x_pigpio pigpio) -target_link_libraries(x_pigpio - ${PIGPIO_FLAGS} - -lpigpio -) +target_link_libraries(x_pigpio pigpio RT::RT Threads::Threads) # x_pigpiod_if add_executable(x_pigpiod_if x_pigpiod_if.c) -add_dependencies(x_pigpiod_if pigpiod_if) -target_link_libraries(x_pigpiod_if - ${PIGPIO_FLAGS} - -lpigpiod_if -) +target_link_libraries(x_pigpiod_if pigpiod_if RT::RT Threads::Threads) # x_pigpiod_if2 add_executable(x_pigpiod_if2 x_pigpiod_if2.c) -add_dependencies(x_pigpiod_if2 pigpiod_if2) -target_link_libraries(x_pigpiod_if2 - ${PIGPIO_FLAGS} - -lpigpiod_if2 -) +target_link_libraries(x_pigpiod_if2 pigpiod_if2 RT::RT Threads::Threads) # pigpiod add_executable(pigpiod pigpiod.c) -add_dependencies(pigpiod pigpio) -target_link_libraries(pigpiod - ${PIGPIO_FLAGS} - -lpigpio -) +target_link_libraries(pigpiod pigpio RT::RT Threads::Threads) # pigs add_executable(pigs pigs.c command.c) +target_link_libraries(pigs Threads::Threads) # pig2vcd add_executable(pig2vcd pig2vcd.c command.c) +target_link_libraries(pig2vcd Threads::Threads) -# install -install(DIRECTORY - DESTINATION ${DESTDIR}/opt/pigpio/cgi - PATTERN "" - PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ - GROUP_READ GROUP_EXECUTE - WORLD_READ WORLD_EXECUTE -) +# Configure and install project + +include (GenerateExportHeader) +include (CMakePackageConfigHelpers) + +generate_export_header(${PROJECT_NAME}) install(TARGETS pigpio pigpiod_if pigpiod_if2 pig2vcd pigpiod pigs - LIBRARY DESTINATION ${DESTDIR}/usr/local/lib - RUNTIME DESTINATION ${DESTDIR}/usr/local/bin - ARCHIVE DESTINATION ${DESTDIR}/usr/local/lib + EXPORT ${PROJECT_NAME}Targets + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib + RUNTIME DESTINATION bin + INCLUDES DESTINATION include +) + +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" + VERSION ${${PROJECT_NAME}_VERSION} + COMPATIBILITY AnyNewerVersion +) + +export(EXPORT ${PROJECT_NAME}Targets + FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake" + NAMESPACE pigpio:: +) + +set(ConfigPackageLocation lib/cmake/${PROJECT_NAME}) +install(EXPORT ${PROJECT_NAME}Targets + FILE + ${PROJECT_NAME}Targets.cmake + NAMESPACE + pigpio:: + DESTINATION + ${ConfigPackageLocation} +) + +install( + FILES + ${CMAKE_CURRENT_LIST_DIR}/cmake/${PROJECT_NAME}Config.cmake + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" + DESTINATION + ${ConfigPackageLocation} ) install(FILES pigpio.h pigpiod_if.h pigpiod_if2.h - DESTINATION ${DESTDIR}/usr/local/include + DESTINATION include PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ @@ -82,7 +97,7 @@ install(FILES pigpio.h pigpiod_if.h pigpiod_if2.h file(GLOB man_1_SRC "*.1") install(FILES ${man_1_SRC} - DESTINATION ${DESTDIR}/usr/local/man/man1 + DESTINATION man/man1 PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ @@ -90,48 +105,23 @@ install(FILES ${man_1_SRC} file(GLOB man_3_SRC "*.3") install(FILES ${man_3_SRC} - DESTINATION ${DESTDIR}/usr/local/man/man3 + DESTINATION man/man3 PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ ) -file(GLOB setup_SRC "setup.py") -find_program(PYTHON2_FOUND python2) -if(PYTHON2_FOUND) - install(CODE "execute_process(COMMAND cd ${CMAKE_SOURCE_DIR} && python2 ${setup_SRC} install)") -endif() -find_program(PYTHON3_FOUND python3) -if(PYTHON3_FOUND) - install(CODE "execute_process(COMMAND cd ${CMAKE_SOURCE_DIR} && python3 ${setup_SRC} install)") +# Install python modules. +find_package(Python COMPONENTS Interpreter QUIET) + +if(Python_FOUND) + configure_file(${CMAKE_CURRENT_LIST_DIR}/cmake/setup.py.in + ${CMAKE_CURRENT_BINARY_DIR}/setup.py + ) + + install(CODE "execute_process(COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/setup.py install)") endif() -install(CODE "execute_process(COMMAND ldconfig)") +# package project -# uninstall -if(PYTHON2_FOUND) - set(PY2_CMD python2 ${setup_SRC} install --record /tmp/pigpio > /dev/null) - set(PY2_CMD ${PY2_CMD} && xargs rm -f < /tmp/pigpio > /dev/null) -endif() - -if(PYTHON3_FOUND) - set(PY3_CMD python3 ${setup_SRC} install --record /tmp/pigpio > /dev/null) - set(PY3_CMD ${PY3_CMD} && xargs rm -f < /tmp/pigpio > /dev/null) -endif() - -add_custom_target(uninstall - COMMAND rm -f ${DESTDIR}/usr/local/include/pigpio.h - COMMAND rm -f ${DESTDIR}/usr/local/include/pigpiod_if.h - COMMAND rm -f ${DESTDIR}/usr/local/include/pigpiod_if2.h - COMMAND rm -f ${DESTDIR}/usr/local/lib/libpigpio.so - COMMAND rm -f ${DESTDIR}/usr/local/lib/libpigpiod_if.so - COMMAND rm -f ${DESTDIR}/usr/local/lib/libpigpiod_if2.so - COMMAND rm -f ${DESTDIR}/usr/local/bin/pig2vcd - COMMAND rm -f ${DESTDIR}/usr/local/bin/pigpiod - COMMAND rm -f ${DESTDIR}/usr/local/bin/pigs - COMMAND cd ${CMAKE_SOURCE_DIR} && ${PY2_CMD} - COMMAND cd ${CMAKE_SOURCE_DIR} && ${PY3_CMD} - COMMAND rm -f ${DESTDIR}/usr/local/man/man1/pig*.1 - COMMAND rm -f ${DESTDIR}/usr/local/man/man3/pig*.3 - COMMAND ldconfig -) +include (CPack) \ No newline at end of file diff --git a/DOC/HTML/images/LDR-fritz.png b/DOC/HTML/images/LDR-fritz.png new file mode 100644 index 0000000..6265585 Binary files /dev/null and b/DOC/HTML/images/LDR-fritz.png differ diff --git a/DOC/HTML/images/LDR-gnup-1.png b/DOC/HTML/images/LDR-gnup-1.png new file mode 100644 index 0000000..6ec6194 Binary files /dev/null and b/DOC/HTML/images/LDR-gnup-1.png differ diff --git a/DOC/HTML/images/LDR-gnup-2.png b/DOC/HTML/images/LDR-gnup-2.png new file mode 100644 index 0000000..4453096 Binary files /dev/null and b/DOC/HTML/images/LDR-gnup-2.png differ diff --git a/DOC/HTML/images/LDR-photo.jpg b/DOC/HTML/images/LDR-photo.jpg new file mode 100644 index 0000000..95a63a3 Binary files /dev/null and b/DOC/HTML/images/LDR-photo.jpg differ diff --git a/DOC/HTML/images/LDR-wave-1.png b/DOC/HTML/images/LDR-wave-1.png new file mode 100644 index 0000000..69bb43b Binary files /dev/null and b/DOC/HTML/images/LDR-wave-1.png differ diff --git a/DOC/HTML/images/LDR-wave-2.png b/DOC/HTML/images/LDR-wave-2.png new file mode 100644 index 0000000..ea68076 Binary files /dev/null and b/DOC/HTML/images/LDR-wave-2.png differ diff --git a/DOC/HTML/images/LDR-wave-3.png b/DOC/HTML/images/LDR-wave-3.png new file mode 100644 index 0000000..a2ca42a Binary files /dev/null and b/DOC/HTML/images/LDR-wave-3.png differ diff --git a/DOC/HTML/images/breadboard.jpg b/DOC/HTML/images/breadboard.jpg new file mode 100644 index 0000000..5d916f7 Binary files /dev/null and b/DOC/HTML/images/breadboard.jpg differ diff --git a/DOC/HTML/images/caps.jpg b/DOC/HTML/images/caps.jpg new file mode 100644 index 0000000..f82e73b Binary files /dev/null and b/DOC/HTML/images/caps.jpg differ diff --git a/DOC/HTML/images/driver.jpg b/DOC/HTML/images/driver.jpg new file mode 100644 index 0000000..48266fe Binary files /dev/null and b/DOC/HTML/images/driver.jpg differ diff --git a/DOC/HTML/images/faq-i2c-ss.png b/DOC/HTML/images/faq-i2c-ss.png new file mode 100644 index 0000000..0e4c58a Binary files /dev/null and b/DOC/HTML/images/faq-i2c-ss.png differ diff --git a/DOC/HTML/images/faq-i2c.jpg b/DOC/HTML/images/faq-i2c.jpg new file mode 100644 index 0000000..02b4a01 Binary files /dev/null and b/DOC/HTML/images/faq-i2c.jpg differ diff --git a/DOC/HTML/images/faq-serial.jpg b/DOC/HTML/images/faq-serial.jpg new file mode 100644 index 0000000..9963589 Binary files /dev/null and b/DOC/HTML/images/faq-serial.jpg differ diff --git a/DOC/HTML/images/faq-spi.jpg b/DOC/HTML/images/faq-spi.jpg new file mode 100644 index 0000000..65ed087 Binary files /dev/null and b/DOC/HTML/images/faq-spi.jpg differ diff --git a/DOC/HTML/images/faq1.jpg b/DOC/HTML/images/faq1.jpg new file mode 100644 index 0000000..72c6eb6 Binary files /dev/null and b/DOC/HTML/images/faq1.jpg differ diff --git a/DOC/HTML/images/faq2.jpg b/DOC/HTML/images/faq2.jpg new file mode 100644 index 0000000..a22800e Binary files /dev/null and b/DOC/HTML/images/faq2.jpg differ diff --git a/DOC/HTML/images/faq3.jpg b/DOC/HTML/images/faq3.jpg new file mode 100644 index 0000000..9785a49 Binary files /dev/null and b/DOC/HTML/images/faq3.jpg differ diff --git a/DOC/HTML/images/imu-1.jpg b/DOC/HTML/images/imu-1.jpg new file mode 100644 index 0000000..f9de3a3 Binary files /dev/null and b/DOC/HTML/images/imu-1.jpg differ diff --git a/DOC/HTML/images/imu-2.jpg b/DOC/HTML/images/imu-2.jpg new file mode 100644 index 0000000..cd56dfd Binary files /dev/null and b/DOC/HTML/images/imu-2.jpg differ diff --git a/DOC/HTML/images/imu-3.jpg b/DOC/HTML/images/imu-3.jpg new file mode 100644 index 0000000..193fe48 Binary files /dev/null and b/DOC/HTML/images/imu-3.jpg differ diff --git a/DOC/HTML/images/ir-fritz.png b/DOC/HTML/images/ir-fritz.png new file mode 100644 index 0000000..595d8d5 Binary files /dev/null and b/DOC/HTML/images/ir-fritz.png differ diff --git a/DOC/HTML/images/ir-motion.jpg b/DOC/HTML/images/ir-motion.jpg new file mode 100644 index 0000000..7fe557e Binary files /dev/null and b/DOC/HTML/images/ir-motion.jpg differ diff --git a/DOC/HTML/images/ir-photo.jpg b/DOC/HTML/images/ir-photo.jpg new file mode 100644 index 0000000..f42ffa2 Binary files /dev/null and b/DOC/HTML/images/ir-photo.jpg differ diff --git a/DOC/HTML/images/ir-rx.jpg b/DOC/HTML/images/ir-rx.jpg new file mode 100644 index 0000000..130b365 Binary files /dev/null and b/DOC/HTML/images/ir-rx.jpg differ diff --git a/DOC/HTML/images/ir-wave-1.png b/DOC/HTML/images/ir-wave-1.png new file mode 100644 index 0000000..29edad3 Binary files /dev/null and b/DOC/HTML/images/ir-wave-1.png differ diff --git a/DOC/HTML/images/ir-wave-2.png b/DOC/HTML/images/ir-wave-2.png new file mode 100644 index 0000000..f820503 Binary files /dev/null and b/DOC/HTML/images/ir-wave-2.png differ diff --git a/DOC/HTML/images/ir-wave-3.png b/DOC/HTML/images/ir-wave-3.png new file mode 100644 index 0000000..b5292b8 Binary files /dev/null and b/DOC/HTML/images/ir-wave-3.png differ diff --git a/DOC/HTML/images/keypad.jpg b/DOC/HTML/images/keypad.jpg new file mode 100644 index 0000000..d6e1f3b Binary files /dev/null and b/DOC/HTML/images/keypad.jpg differ diff --git a/DOC/HTML/images/lcd.jpg b/DOC/HTML/images/lcd.jpg new file mode 100644 index 0000000..b38a174 Binary files /dev/null and b/DOC/HTML/images/lcd.jpg differ diff --git a/DOC/HTML/images/ldr-cap.jpg b/DOC/HTML/images/ldr-cap.jpg new file mode 100644 index 0000000..cd34bb8 Binary files /dev/null and b/DOC/HTML/images/ldr-cap.jpg differ diff --git a/DOC/HTML/images/ldr.jpg b/DOC/HTML/images/ldr.jpg new file mode 100644 index 0000000..d49be11 Binary files /dev/null and b/DOC/HTML/images/ldr.jpg differ diff --git a/DOC/HTML/images/leds.jpg b/DOC/HTML/images/leds.jpg new file mode 100644 index 0000000..7b79f72 Binary files /dev/null and b/DOC/HTML/images/leds.jpg differ diff --git a/DOC/HTML/images/meter.jpg b/DOC/HTML/images/meter.jpg new file mode 100644 index 0000000..65ce37d Binary files /dev/null and b/DOC/HTML/images/meter.jpg differ diff --git a/DOC/HTML/images/motor.jpg b/DOC/HTML/images/motor.jpg new file mode 100644 index 0000000..1ddcb82 Binary files /dev/null and b/DOC/HTML/images/motor.jpg differ diff --git a/DOC/HTML/images/msp430.jpg b/DOC/HTML/images/msp430.jpg new file mode 100644 index 0000000..04633f3 Binary files /dev/null and b/DOC/HTML/images/msp430.jpg differ diff --git a/DOC/HTML/images/nano.jpg b/DOC/HTML/images/nano.jpg new file mode 100644 index 0000000..03c3fb1 Binary files /dev/null and b/DOC/HTML/images/nano.jpg differ diff --git a/DOC/HTML/images/oled-2.jpg b/DOC/HTML/images/oled-2.jpg new file mode 100644 index 0000000..622713f Binary files /dev/null and b/DOC/HTML/images/oled-2.jpg differ diff --git a/DOC/HTML/images/oled.jpg b/DOC/HTML/images/oled.jpg new file mode 100644 index 0000000..02f093d Binary files /dev/null and b/DOC/HTML/images/oled.jpg differ diff --git a/DOC/HTML/images/pigpio-logo.gif b/DOC/HTML/images/pigpio-logo.gif new file mode 100644 index 0000000..f0980e1 Binary files /dev/null and b/DOC/HTML/images/pigpio-logo.gif differ diff --git a/DOC/HTML/images/pins.jpg b/DOC/HTML/images/pins.jpg new file mode 100644 index 0000000..60e2f4e Binary files /dev/null and b/DOC/HTML/images/pins.jpg differ diff --git a/DOC/HTML/images/pisc-1.jpg b/DOC/HTML/images/pisc-1.jpg new file mode 100644 index 0000000..a83d4c9 Binary files /dev/null and b/DOC/HTML/images/pisc-1.jpg differ diff --git a/DOC/HTML/images/pisc-2.jpg b/DOC/HTML/images/pisc-2.jpg new file mode 100644 index 0000000..1506017 Binary files /dev/null and b/DOC/HTML/images/pisc-2.jpg differ diff --git a/DOC/HTML/images/pisc-3.jpg b/DOC/HTML/images/pisc-3.jpg new file mode 100644 index 0000000..6b473ff Binary files /dev/null and b/DOC/HTML/images/pisc-3.jpg differ diff --git a/DOC/HTML/images/pot.jpg b/DOC/HTML/images/pot.jpg new file mode 100644 index 0000000..ea386e9 Binary files /dev/null and b/DOC/HTML/images/pot.jpg differ diff --git a/DOC/HTML/images/pro-mini.jpg b/DOC/HTML/images/pro-mini.jpg new file mode 100644 index 0000000..af8f0b9 Binary files /dev/null and b/DOC/HTML/images/pro-mini.jpg differ diff --git a/DOC/HTML/images/psu.jpg b/DOC/HTML/images/psu.jpg new file mode 100644 index 0000000..f848d14 Binary files /dev/null and b/DOC/HTML/images/psu.jpg differ diff --git a/DOC/HTML/images/re-fritz.png b/DOC/HTML/images/re-fritz.png new file mode 100644 index 0000000..2f545b5 Binary files /dev/null and b/DOC/HTML/images/re-fritz.png differ diff --git a/DOC/HTML/images/re-photo.jpg b/DOC/HTML/images/re-photo.jpg new file mode 100644 index 0000000..22c4bfe Binary files /dev/null and b/DOC/HTML/images/re-photo.jpg differ diff --git a/DOC/HTML/images/re-wave-1.png b/DOC/HTML/images/re-wave-1.png new file mode 100644 index 0000000..f8a194d Binary files /dev/null and b/DOC/HTML/images/re-wave-1.png differ diff --git a/DOC/HTML/images/re-wave-2.png b/DOC/HTML/images/re-wave-2.png new file mode 100644 index 0000000..399d7a4 Binary files /dev/null and b/DOC/HTML/images/re-wave-2.png differ diff --git a/DOC/HTML/images/remote-1.jpg b/DOC/HTML/images/remote-1.jpg new file mode 100644 index 0000000..2d28bef Binary files /dev/null and b/DOC/HTML/images/remote-1.jpg differ diff --git a/DOC/HTML/images/remote-2.jpg b/DOC/HTML/images/remote-2.jpg new file mode 100644 index 0000000..d11685a Binary files /dev/null and b/DOC/HTML/images/remote-2.jpg differ diff --git a/DOC/HTML/images/reverse.jpg b/DOC/HTML/images/reverse.jpg new file mode 100644 index 0000000..2eb3804 Binary files /dev/null and b/DOC/HTML/images/reverse.jpg differ diff --git a/DOC/HTML/images/rf-rx-2.jpg b/DOC/HTML/images/rf-rx-2.jpg new file mode 100644 index 0000000..1f1e93c Binary files /dev/null and b/DOC/HTML/images/rf-rx-2.jpg differ diff --git a/DOC/HTML/images/rf-rx.jpg b/DOC/HTML/images/rf-rx.jpg new file mode 100644 index 0000000..c246a4f Binary files /dev/null and b/DOC/HTML/images/rf-rx.jpg differ diff --git a/DOC/HTML/images/rf-tx.jpg b/DOC/HTML/images/rf-tx.jpg new file mode 100644 index 0000000..324d257 Binary files /dev/null and b/DOC/HTML/images/rf-tx.jpg differ diff --git a/DOC/HTML/images/rotary.jpg b/DOC/HTML/images/rotary.jpg new file mode 100644 index 0000000..0f7d224 Binary files /dev/null and b/DOC/HTML/images/rotary.jpg differ diff --git a/DOC/HTML/images/rpi.jpg b/DOC/HTML/images/rpi.jpg new file mode 100644 index 0000000..85ce158 Binary files /dev/null and b/DOC/HTML/images/rpi.jpg differ diff --git a/DOC/HTML/images/serial.jpg b/DOC/HTML/images/serial.jpg new file mode 100644 index 0000000..c2bb917 Binary files /dev/null and b/DOC/HTML/images/serial.jpg differ diff --git a/DOC/HTML/images/servo.jpg b/DOC/HTML/images/servo.jpg new file mode 100644 index 0000000..bbd895c Binary files /dev/null and b/DOC/HTML/images/servo.jpg differ diff --git a/DOC/HTML/images/sidebar.gif b/DOC/HTML/images/sidebar.gif new file mode 100644 index 0000000..89a0620 Binary files /dev/null and b/DOC/HTML/images/sidebar.gif differ diff --git a/DOC/HTML/images/son-fritz.png b/DOC/HTML/images/son-fritz.png new file mode 100644 index 0000000..c864641 Binary files /dev/null and b/DOC/HTML/images/son-fritz.png differ diff --git a/DOC/HTML/images/son-gnup-1.png b/DOC/HTML/images/son-gnup-1.png new file mode 100644 index 0000000..be53824 Binary files /dev/null and b/DOC/HTML/images/son-gnup-1.png differ diff --git a/DOC/HTML/images/son-gnup-2.png b/DOC/HTML/images/son-gnup-2.png new file mode 100644 index 0000000..c552306 Binary files /dev/null and b/DOC/HTML/images/son-gnup-2.png differ diff --git a/DOC/HTML/images/son-photo.jpg b/DOC/HTML/images/son-photo.jpg new file mode 100644 index 0000000..6954f40 Binary files /dev/null and b/DOC/HTML/images/son-photo.jpg differ diff --git a/DOC/HTML/images/son-wave-1.png b/DOC/HTML/images/son-wave-1.png new file mode 100644 index 0000000..96261bc Binary files /dev/null and b/DOC/HTML/images/son-wave-1.png differ diff --git a/DOC/HTML/images/son-wave-2.png b/DOC/HTML/images/son-wave-2.png new file mode 100644 index 0000000..73c8b6d Binary files /dev/null and b/DOC/HTML/images/son-wave-2.png differ diff --git a/DOC/HTML/images/son-wave-3.png b/DOC/HTML/images/son-wave-3.png new file mode 100644 index 0000000..346f5ae Binary files /dev/null and b/DOC/HTML/images/son-wave-3.png differ diff --git a/DOC/HTML/images/son-wave-4.png b/DOC/HTML/images/son-wave-4.png new file mode 100644 index 0000000..ad454ef Binary files /dev/null and b/DOC/HTML/images/son-wave-4.png differ diff --git a/DOC/HTML/images/speaker.jpg b/DOC/HTML/images/speaker.jpg new file mode 100644 index 0000000..2be827b Binary files /dev/null and b/DOC/HTML/images/speaker.jpg differ diff --git a/DOC/HTML/images/spi-lnx-pi3b.png b/DOC/HTML/images/spi-lnx-pi3b.png new file mode 100644 index 0000000..09ee665 Binary files /dev/null and b/DOC/HTML/images/spi-lnx-pi3b.png differ diff --git a/DOC/HTML/images/spi-lnx-pibr1.png b/DOC/HTML/images/spi-lnx-pibr1.png new file mode 100644 index 0000000..3c708e4 Binary files /dev/null and b/DOC/HTML/images/spi-lnx-pibr1.png differ diff --git a/DOC/HTML/images/spi-pig-pi3b.png b/DOC/HTML/images/spi-pig-pi3b.png new file mode 100644 index 0000000..602922c Binary files /dev/null and b/DOC/HTML/images/spi-pig-pi3b.png differ diff --git a/DOC/HTML/images/spi-pig-pibr1.png b/DOC/HTML/images/spi-pig-pibr1.png new file mode 100644 index 0000000..308f25d Binary files /dev/null and b/DOC/HTML/images/spi-pig-pibr1.png differ diff --git a/DOC/HTML/images/srf02.jpg b/DOC/HTML/images/srf02.jpg new file mode 100644 index 0000000..22486f8 Binary files /dev/null and b/DOC/HTML/images/srf02.jpg differ diff --git a/DOC/HTML/images/srf04.jpg b/DOC/HTML/images/srf04.jpg new file mode 100644 index 0000000..632d194 Binary files /dev/null and b/DOC/HTML/images/srf04.jpg differ diff --git a/DOC/HTML/images/stepper.jpg b/DOC/HTML/images/stepper.jpg new file mode 100644 index 0000000..11a1473 Binary files /dev/null and b/DOC/HTML/images/stepper.jpg differ diff --git a/DOC/HTML/images/switches.jpg b/DOC/HTML/images/switches.jpg new file mode 100644 index 0000000..6cd1df5 Binary files /dev/null and b/DOC/HTML/images/switches.jpg differ diff --git a/DOC/HTML/images/topbar.gif b/DOC/HTML/images/topbar.gif new file mode 100644 index 0000000..27ae71f Binary files /dev/null and b/DOC/HTML/images/topbar.gif differ diff --git a/DOC/HTML/images/transistors.jpg b/DOC/HTML/images/transistors.jpg new file mode 100644 index 0000000..6f6a14f Binary files /dev/null and b/DOC/HTML/images/transistors.jpg differ diff --git a/DOC/HTML/images/ubec-2.jpg b/DOC/HTML/images/ubec-2.jpg new file mode 100644 index 0000000..8fe87ce Binary files /dev/null and b/DOC/HTML/images/ubec-2.jpg differ diff --git a/DOC/HTML/images/uln2003a.jpg b/DOC/HTML/images/uln2003a.jpg new file mode 100644 index 0000000..aeebee4 Binary files /dev/null and b/DOC/HTML/images/uln2003a.jpg differ diff --git a/DOC/HTML/images/wheel.jpg b/DOC/HTML/images/wheel.jpg new file mode 100644 index 0000000..f274a2d Binary files /dev/null and b/DOC/HTML/images/wheel.jpg differ diff --git a/DOC/HTML/images/wires.jpg b/DOC/HTML/images/wires.jpg new file mode 100644 index 0000000..9574f90 Binary files /dev/null and b/DOC/HTML/images/wires.jpg differ diff --git a/DOC/HTML/images/yl-40.jpg b/DOC/HTML/images/yl-40.jpg new file mode 100644 index 0000000..1320405 Binary files /dev/null and b/DOC/HTML/images/yl-40.jpg differ diff --git a/DOC/HTML/scripts/index.css b/DOC/HTML/scripts/index.css new file mode 100644 index 0000000..64cfd33 --- /dev/null +++ b/DOC/HTML/scripts/index.css @@ -0,0 +1,52 @@ +body +{ +font-size: 100%; +font-family: Arial, Helvetica, sans-serif; +color: #101010; +margin-left: 1%; margin-right: 10%; +} + +h1 {font-size: 2.4em; color: #5d9dce; font-weight: bold;} +h2 {font-size: 1.8em; color: #5d9dce; font-weight: bold;} +h3 {font-size: 1.4em; color: #5d9dce; font-weight: bold;} +h4 {font-size: 1.2em; color: #5d9dce;} +h5 {font-size: 1.0em; color: #5d9dce;} +h6 {font-size: 0.8em; color: #5d9dce;} + +code {display:block;font-size:80%; font-family: "Courier New", Courier, monospace; background-color:#D0D0D0;} +pre {font-size:80%; font-family: Courier; background-color:#D0D020;} + +table.ev +{ +border: 3px solid green; +} + +td.ev1 +{ +width: 200px; +border: 1px solid green; +} + +td.ev2 +{ +border: 1px solid green; +} + +a.l1:link,a.l1:visited +{ +display:block; +font-weight:bold; +color:#FFFFFF; +background-color:#98bf21; +width:120px; +text-align:center; +padding:4px; +text-decoration:none; +} + +a.l1:hover,a.l1:active +{ +background-color:#7A991A; +} + + diff --git a/DOC/HTML/scripts/standard.css b/DOC/HTML/scripts/standard.css new file mode 100644 index 0000000..ad0415b --- /dev/null +++ b/DOC/HTML/scripts/standard.css @@ -0,0 +1,3 @@ +html { height: 100% } +body { height: 100%; margin: 0px; padding: 0px } +#map_canvas { height: 100% } diff --git a/DOC/MAN/README b/DOC/MAN/README new file mode 100644 index 0000000..cde5d85 --- /dev/null +++ b/DOC/MAN/README @@ -0,0 +1 @@ +Placeholder directory for man pages. diff --git a/DOC/README b/DOC/README new file mode 100644 index 0000000..19a1516 --- /dev/null +++ b/DOC/README @@ -0,0 +1,16 @@ +bin various scripts to generate man pages and HTML + +dbase defines the structure of the web documentation + +HTML auto generated html web site + +makedoc run to regenerate documentation + +MAN auto generated man pages + +src/defs edit to change pigs, pigpiod, pig2vcd, and examples docs + +src/html edit to change the fairly invariant web pages + DO NOT ADD auto generated HTML to this directory + +tmp stores temporary files, may be deleted diff --git a/DOC/bin/backup.sh b/DOC/bin/backup.sh new file mode 100755 index 0000000..6a45c48 --- /dev/null +++ b/DOC/bin/backup.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +# backup database +cp dbase/pigpio.sqlite dbase/pigpio.sqlite.bak + diff --git a/DOC/bin/body.py b/DOC/bin/body.py new file mode 100755 index 0000000..9e4c437 --- /dev/null +++ b/DOC/bin/body.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 + +import glob + +for fn in glob.glob("src/html/*.html"): + f = open(fn) + h = f.read() + f.close() + s1,d1,e1=h.partition("") + s2,d2,e2=e1.partition("") + f = open("tmp/body/" + fn[9:-5] + ".body", "w") + f.write(s2) + f.close() + diff --git a/DOC/bin/build_site.py b/DOC/bin/build_site.py new file mode 100755 index 0000000..c153150 --- /dev/null +++ b/DOC/bin/build_site.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +import os +import sqlite3 + +db=sqlite3.connect("dbase/pigpio.sqlite") + +c=db.cursor() + +c.execute("select file_name from pigpio") + +names = c.fetchall() + +for n in names: + os.system("bin/html.py {0} >HTML/{0}.html".format(n[0])) + print(n[0]) + +c.close() + +db.close() + diff --git a/DOC/bin/cmakdoc.py b/DOC/bin/cmakdoc.py new file mode 100755 index 0000000..dd1bd52 --- /dev/null +++ b/DOC/bin/cmakdoc.py @@ -0,0 +1,563 @@ +#!/usr/bin/env python3 + +import sys + +pigpio_m1=""" +.\" Process this file with +.\" groff -man -Tascii pigpio.3 +.\" +.TH pigpio 3 2012-2020 Linux "pigpio archive" +.SH NAME +pigpio - A C library to manipulate the Pi's GPIO.\n +.SH SYNOPSIS\n +#include \n + +gcc -Wall -pthread -o prog prog.c -lpigpio -lrt\n +sudo ./prog +.SH DESCRIPTION\n +""" + +pigpiod_if_m1=""" +.\" Process this file with +.\" groff -man -Tascii pigpiod_if.3 +.\" +.TH pigpiod_if 3 2012-2020 Linux "pigpio archive" +.SH NAME +pigpiod_if - A C library to interface to the pigpio daemon.\n +.SH SYNOPSIS\n +#include \n + +gcc -Wall -pthread -o prog prog.c -lpigpiod_if -lrt\n + ./prog +.SH DESCRIPTION\n +""" + +pigpiod_if2_m1=""" +.\" Process this file with +.\" groff -man -Tascii pigpiod_if2.3 +.\" +.TH pigpiod_if2 3 2012-2020 Linux "pigpio archive" +.SH NAME +pigpiod_if2 - A C library to interface to the pigpio daemon.\n +.SH SYNOPSIS\n +#include \n + +gcc -Wall -pthread -o prog prog.c -lpigpiod_if2 -lrt\n + ./prog +.SH DESCRIPTION\n +""" + +pigpiod_m1=""" +.\" Process this file with +.\" groff -man -Tascii pigpiod.1 +.\" +.TH pigpiod 1 2012-2020 Linux "pigpio archive" +.SH NAME +pigpiod - A utility to start the pigpio library as a daemon.\n +.SH SYNOPSIS\n +sudo pigpiod [OPTION]... +.SH DESCRIPTION\n +""" + +pig2vcd_m1=""" +.\" Process this file with +.\" groff -man -Tascii pig2vcd.1 +.\" +.TH pig2vcd 1 2012-2020 Linux "pigpio archive" +.SH NAME +pig2vd - A utility to convert pigpio notifications to VCD.\n +.SH SYNOPSIS\n +pig2vcd file.VCD +.SH DESCRIPTION\n +""" + +pigpio_m2=""" +.SH SEE ALSO\n +pigpiod(1), pig2vcd(1), pigs(1), pigpiod_if(3), pigpiod_if2(3) +.SH AUTHOR\n +joan@abyz.me.uk +""" + +pigpiod_if_m2=""" +.SH SEE ALSO\n +pigpiod(1), pig2vcd(1), pigs(1), pigpio(3), pigpiod_if2(3) +.SH AUTHOR\n +joan@abyz.me.uk +""" + +pigpiod_if2_m2=""" +.SH SEE ALSO\n +pigpiod(1), pig2vcd(1), pigs(1), pigpio(3), pigpiod_if(3) +.SH AUTHOR\n +joan@abyz.me.uk +""" + +pigpiod_m2=""" +.SH SEE ALSO\n +pig2vcd(1), pigs(1), pigpio(3), pigpiod_if(3), pigpiod_if2(3) +.SH AUTHOR\n +joan@abyz.me.uk +""" + +pig2vcd_m2=""" +.SH SEE ALSO\n +pigpiod(1), pigs(1), pigpio(3), pigpiod_if(3), pigpiod_if2(3) +.SH AUTHOR\n +joan@abyz.me.uk +""" + + +def emit(s): + sys.stdout.write(s) + +def get_line(f): + line = f.readline() + if man: + line = line.replace(" \n", "\n.br\n") + else: + line = line.replace("<", "<") + line = line.replace(">", ">") + line = line.replace(" \n", "
\n") + return line + +def nostar(k): + if k[0] == "*": + return k[1:] + else: + return k + +NONE =0 +MAN =1 +TEXT =2 +OVERVIEW=4 +FUNC =5 +DESC =6 +OPT =7 +PARAMS =8 +DEFS =9 + +param_used = [] +param_defd = [] +param_refd = [] + +at = NONE + +in_code = False +in_pard = False +in_table = False + +if len(sys.argv) > 2: + obj = sys.argv[1] + fn = sys.argv[2] + if len(sys.argv) > 3: + man = True + else: + man = False +else: + exit("bad args, need page file [man]") +try: + f = open(fn, "r") +except: + exit("aborting, can't open {}".format(fn)) + +if man: + if obj == "pigpio": + emit(pigpio_m1) + elif obj == "pigpiod_if": + emit(pigpiod_if_m1) + elif obj == "pigpiod_if2": + emit(pigpiod_if2_m1) + elif obj == "pigpiod": + emit(pigpiod_m1) + elif obj == "pig2vcd": + emit(pig2vcd_m1) + + emit("\n.ad l\n") + emit("\n.nh\n") + +while True: + + line = get_line(f) + + if line == "": + for p in param_used: + if p not in param_defd: + sys.stderr.write("{} used but not defined.\n".format(p)) + for p in param_defd: + if p not in param_used and p not in param_refd: + sys.stderr.write("{} defined but not used.\n".format(p)) + break + + if line == "/*MAN\n": + at = MAN + continue + + elif line == "MAN*/\n": + at = NONE + continue + + if line == "/*TEXT\n": + at = TEXT + continue + + elif line == "TEXT*/\n": + at = NONE + continue + + elif line == "/*OVERVIEW\n": + + if man: + emit("\n.SH OVERVIEW\n") + else: + emit("

OVERVIEW

") + emit( + "") + + at = OVERVIEW + continue + + elif line == "OVERVIEW*/\n": + + if man: + emit(".SH FUNCTIONS\n") + else: + emit("
") + emit("

FUNCTIONS

") + + at = NONE + + elif line == "/*F*/\n": + in_code = False + fdef="" + line = get_line(f) + at = FUNC + + elif line == "/*D\n": + # Function definition should be complete. + fdef = fdef.replace("\n", " ") + + while fdef.find(" ") != -1: + fdef = fdef.replace(" ", " ") + + fdef = fdef.replace("( ", "(") + + (rf, sep1, end1) = fdef.partition("(") + (parl, sep2, end2) = end1.partition(")") + tps = parl.split(",") + rf = rf.split(" ") + ret = rf[0] + func = rf[1] + + if ret not in param_used: + param_used.append(ret) + + if man: + t = "\\fB" + ret + " " + func + "(" + parl + ")\\fP" + emit("\n.IP \"{}\"\n.IP \"\" 4\n".format(t)) + else: + emit("

{} {}". + format(nostar(func), ret, ret,func)) + emit("(") + + x = 0 + for tp in tps: + tp = tp.strip() + (t, sep3, p) = tp.partition(" ") + t = t.strip() + p = p.strip() + if (p != ""): + if p not in param_used: + param_used.append(p) + if t not in param_used: + param_used.append(t) + if x > 0: + + if man: + pass + else: + emit(", ") + + x += 1 + + if man: + pass + else: + + emit("{} {}". + format(t, t, p, p)) + + else: + + if man: + pass + else: + emit("{}".format(t)) + + if man: + pass + else: + emit(")

\n") + + line = get_line(f) + at = DESC + + elif line == "D*/\n": + at = NONE + + elif line == "/*O\n": + if man: + emit(".SH OPTIONS\n") + else: + emit("") + at = OPT + continue + + elif line == "O*/\n": + if man: + pass + else: + emit("
") + at = NONE + continue + + elif line == "/*PARAMS\n": + last_par = "*" + + if man: + emit(".SH PARAMETERS\n") + else: + emit("

PARAMETERS

") + + at = PARAMS + continue + + elif line == "PARAMS*/\n": + at = NONE + + elif line.startswith("/*DEF_S "): + title = line[8:-3] + in_code = True + if man: + emit(".SH {}\n".format(title)) + emit("\n.EX\n") + else: + emit("

{}

".format(title)) + emit("") + at = DEFS + continue + + elif line == "/*DEF_E*/\n": + in_code = False + if man: + emit("\n.EE\n") + else: + emit("") + at = NONE + continue + + + if at != NONE and at != OVERVIEW: + if line.find("@") != -1: + if not in_table: + in_table = True + + if man: + pass + else: + emit("") + + if man: + line = line.replace("@", " ") + emit(line) + # emit("\n.br\n") + emit(".br\n") + else: + emit("") + cols = line.split("@") + for col in cols: + emit("".format(col.strip())) + emit("") + + continue + + else: + if in_table: + in_table = False + + if man: + pass + else: + emit("
{}
") + + if line == "...\n" or line == ". .\n": + if in_code: + in_code = False + + if man: + emit("\n.EE\n") + else: + emit("") + + else: + in_code = True + if line == "...\n": + + if man: + emit("\\fBExample\\fP\n.br\n") + else: + emit("Example

") + + if man: + emit("\n.EX\n") + else: + emit("") + + continue + + if line == "\n": + + if man: + emit("\n.br\n") + else: + emit("
") + + if not in_code: + if man: + emit("\n.br\n") + else: + emit("
") + + continue + + if in_code: + + if man: + line = line.replace("\n", "\n.br\n") + else: + line = line.replace(" ", " ") + line = line.replace("\n", "
") + + while line.find("[*") != -1 and line.find("*]") != -1: + (b, s, e) = line.partition("[*") + (l, s, e) = e.partition("*]") + + if man: + line = "{}\\fB{}\\fP{}".format(b, l, e) + else: + line = "{}{}{}".format(b, l, l, e) + + if l not in param_refd: + param_refd.append(l) + + while line.find("[[") != -1 and line.find("]]") != -1: + (b, s, e) = line.partition("[[") + (l, s, e) = e.partition("]]") + + if man: + line = "{}\\fB{}\\fP{}".format(b, l, e) + else: + line = "{}{}{}".format(b, l, l, e) + + if at == TEXT: + if line[0] == '*' and line[-2] == '*': + if man: + emit(".SS {}".format(line[1:-2])) + else: + emit("

{}

".format(line[1:-2])) + elif line[0] == '^' and line[-2] == '^': + if man: + emit(".SS {}".format(line[1:-2])) + else: + emit("
{}
".format(line[1:-2])) + else: + emit(line) + + elif at == OVERVIEW: + if line == "\n": + + if man: + emit("\n.br\n") + else: + emit("") + + else: + (func, sep, desc) = line.partition(" ") + if desc != "": + + if man: + emit("\n.br\n{}".format(line.strip())) + else: + emit("{}{}". + format(func, func, desc)) + + else: + + if man: + emit(".SS {}".format(line.replace("_", " ").strip())) + else: + emit("{}". + format(func.replace("_", " "))) + + elif at == FUNC: + fdef += line + + elif at == DESC: + emit(line) + + elif at == PARAMS: + if line.find("::") != -1: + (par, sep, end) = line.partition("::") + par = par.strip() + end = end.strip() + + if nostar(par.lower()) < nostar(last_par.lower()): + sys.stderr.write("Out of order {} after {}.\n". + format(par, last_par)) + last_par = par + + if par in param_defd: + sys.stderr.write("Duplicate definition of {}.\n".format(par)) + else: + param_defd.append(par) + + if end != "": + end = ": " + end + if man: + emit("\n.IP \"\\fB{}\\fP{}\" 0\n".format(par, end)) + else: + emit("

{}{}

\n".format(par, par, end)) + + else: + emit(line) + + elif at == MAN: + if man: + emit(line) + + elif at == OPT: + line = line.split("|") + if man: + emit("\n.IP \"\\fB{}\\fP\"\n{}.\n{}.\n{}.".format( + line[0], line[1], line[2], line[3])) + else: + emit("{}{}{}{}". + format(line[0], line[1], line[2], line[3])) + + elif at == DEFS: + emit(line) + +if man: + if obj == "pigpio": + emit(pigpio_m2) + elif obj == "pigpiod_if": + emit(pigpiod_if_m2) + elif obj == "pigpiod_if2": + emit(pigpiod_if2_m2) + elif obj == "pigpiod": + emit(pigpiod_m2) + elif obj == "pig2vcd": + emit(pig2vcd_m2) + + +f.close() + diff --git a/DOC/bin/examples.py b/DOC/bin/examples.py new file mode 100755 index 0000000..e389341 --- /dev/null +++ b/DOC/bin/examples.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 + +import sys +from collections import OrderedDict + +def emit(s): + sys.stdout.write(s) + +def get_line(f): + line = f.readline() + return line + +def get_file(): + try: + fn = sys.argv[1] + f = open(fn, "r") + except: + exit("aborting, can't open {}".format(fn)) + return f + +def cancel_row(): + global in_row + if in_row: + in_row = False + emit('') + +def start_row(): + global in_row + if not in_row: + in_row = True + emit('') + +def cancel_table(): + global in_table + if in_table: + in_table = False + cancel_row() + emit('') + +def start_table(): + global in_table + if not in_table: + in_table = True + emit('') + else: + cancel_row() + start_row() + +index = {} + +in_code = False +in_samp = False +in_table = False +in_row = False + +f = get_file() + +while True: + + line = get_line(f) + + if line == "": + cancel_table() + + emit('
\n') + last = None + ordered = OrderedDict(sorted(index.items(), key=lambda t: t[1].lower())) + for k,v in ordered.items(): + tag=k.split('_')[0] + if last != v.lower(): + if last is not None: + emit('') + last = v.lower() + anchor="index_"+last.replace(" ", "_") + emit('
'+v+'') + emit(' '+tag+'\n') + emit('
') + break + + if line.startswith("?0|"): + s = line.split("|") + anchor=s[1].strip() + emit(''+anchor+'
') + continue + + if line.startswith("?1|"): + cancel_table() + s = line.split("|") + tag = s[1].strip()+"_" + anchor=s[2].strip() + emit('

'+anchor+'

') + continue + + elif line.startswith("?2|") or line.startswith("?3|") or line.startswith("?4|"): + start_table() + + s = line.split("|") + + anchor=tag+s[1].strip() + + if line.startswith("?2|"): + link=s[1].strip()+".html" + elif line.startswith("?3|"): + link="code/"+s[1].strip()+".zip" + elif line.startswith("?4|"): + link=s[1].strip() + else: + link="code/"+s[1].strip() + + date=s[2].strip() + + title=s[3].strip() + emit(''+title+'
'+date+'
') + + index.update({anchor:title}) + + continue + + else: + emit(line.replace("\n", "
\n")) + +f.close() + diff --git a/DOC/bin/html.py b/DOC/bin/html.py new file mode 100755 index 0000000..1259430 --- /dev/null +++ b/DOC/bin/html.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 + +import sys +import sqlite3 +import time + +i_file_name = 0 +i_menu_title = 1 +i_menu_pos = 2 +i_menu_level = 3 +i_page_title = 4 +i_pic1 = 5 +i_pic2 = 6 +i_pic3 = 7 +i_body = 8 + +print(""" + + + + + + + pigpio library + + + + + +""") + +page = sys.argv[1] + +menuH = "" +menuV = "" +sitemap = "" + +header = 'pigpio library' + +footer1 = "© 2012-2020"; +footer2 = "e-mail: pigpio @ abyz.me.uk"; +footer3 = "Updated: " + time.strftime("%d/%m/%Y") + ""; + +db=sqlite3.connect("dbase/pigpio.sqlite") + +c=db.cursor() + +def menu_titles(): + + global menuV, menuH + + c.execute( + "SELECT file_name, menu_title, menu_level FROM pigpio ORDER by menu_pos") + + recs = c.fetchall() + + menuV = "" + menuH = "" + + for r in recs: + if r[2] == 1: + menuV += '' + r[1] + '\n' + menuH += '[' + r[1] + ']\n' + +def sitemap(): + + c.execute( + "SELECT file_name, menu_title, menu_level FROM pigpio ORDER by menu_pos") + + recs = c.fetchall() + + stemap = "" + + for r in recs: + if r[2] > 0: + s = "----" * (r[2]-1) + stemap += s + '' + r[1] + '
\n' + + return stemap + +def check_image(d): + + img = "images/" + d + + try: + with open("HTML/" + img) as f: + print('') + except: + pass + +titles = menu_titles() + +s_sidebar = 'style="background:#EAF2E6 url(\'images/sidebar.gif\') repeat-y; width:35px; height:100%"' + +s_header = 'style="background:url(\'images/topbar.gif\') repeat-x; height: 70px; font-size:1.5em; vertical-align: top;"' + +s_menuV = 'style="vertical-align: top; background-color: #98bf21;"' + +c.execute("SELECT * FROM pigpio WHERE file_name=?", (page,)) + +rec = c.fetchone() + +if page == "sitemap": + body = sitemap() +else: + body = rec[i_body] + +c.close() +db.close() + +print('') +print('') +print('') +print('
') +print('') +print('
' + header + '
') +print('
') +print('
') +check_image(rec[i_pic1]) +check_image(rec[i_pic2]) +check_image(rec[i_pic3]) +print('
') +print("") +print('') +print('') +print('
' + menuV + '

' + rec[i_page_title] + '

' + body + '
') +print('
' + menuH + '
') +print('') +print('') +print('') +print('') +print('
' + footer1 + '
' + footer2 + '
' + footer3 + '
') +print('
') + +print('\n') + diff --git a/DOC/bin/purge.sh b/DOC/bin/purge.sh new file mode 100755 index 0000000..54553bb --- /dev/null +++ b/DOC/bin/purge.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +# if backup same as new delete it +if cmp -s dbase/pigpio.sqlite dbase/pigpio.sqlite.bak +then + rm dbase/pigpio.sqlite.bak +else + d=$(date "+%F-%H-%M-%S") + mv -f dbase/pigpio.sqlite.bak dbase/pigpio.sqlite.$d +fi + +# delete backups older than a week +find dbase/pigpio.sqlite.2* -mtime +7 -delete &>/dev/null + diff --git a/DOC/bin/pymakdoc.py b/DOC/bin/pymakdoc.py new file mode 100755 index 0000000..c2a6e87 --- /dev/null +++ b/DOC/bin/pymakdoc.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 + +import sys + +def emit(s): + sys.stdout.write(s) + +def str2hex(s): + return ":".join("{:02x}".format(ord(c)) for c in s) + +def funchdr(line): + if len(line) > 1 and (not line.startswith(" ")) and line.find("(") != -1: + return True + else: + return False + +def get_line(f): + line = f.readline() + line = line.replace("<", "<") + line = line.replace(">", ">") + return line + +def get_file(): + try: + fn = sys.argv[1] + f = open(fn, "r") + except: + exit("aborting, can't open {}".format(fn)) + return f + + +NONE = 0 +DESCRIPTION = 1 +OVERVIEW = 2 +CLASSES = 3 +CLASS = 4 +FUNC = 5 +XREF = 6 +DATA = 7 + +f = get_file() + +param_used = [] +param_defd = [] +param_refd = [] + +at = NONE + +in_code = False +in_samp = False +in_table = False +left = 0 + +while True: + + line = get_line(f) + + if line == "": + for p in param_used: + if p not in param_defd: + sys.stderr.write("{} is used but not defined.\n".format(p)) + for p in param_defd: + if p not in param_used and p not in param_refd: + sys.stderr.write("{} is defined but not used.\n".format(p)) + break + + if line.startswith("DESCRIPTION"): + left = 4 + at = DESCRIPTION + continue + + elif line.startswith(" OVERVIEW"): + left = 4 + emit("

OVERVIEW

") + emit( + "") + at = OVERVIEW + continue + + elif line.startswith("CLASSES"): + left = 4 + emit("
") + at = NONE + continue + + elif line.startswith(" class "): + in_func = False + if line.startswith(" class error"): + at = NONE + else: + left = 8 + emit("

{}

".format(line)) + _class = line[10:-1] + at = CLASS + continue + + elif line.startswith("FUNCTIONS"): + left = 4 + emit("

FUNCTIONS

") + in_func = False + at = FUNC + continue + + elif line.startswith(" xref()"): + left = 8 + emit("

PARAMETERS

") + in_func = False + last_par = "" + at = XREF + continue + + elif line.startswith("DATA"): + at = DATA + continue + + line = line[left:] + + at_funchdr = funchdr(line) + + if at != NONE and at != OVERVIEW: + + if at == CLASS or at == FUNC: + + if not at_funchdr: + line = line[4:] + + line = line.replace(' \n', '
') + + if line.find('@') != -1: + if not in_table: + in_table = True + emit("") + emit("") + cols = line.split('@') + for col in cols: + emit("".format(col.strip())) + emit("") + continue + else: + if in_table: + in_table = False + emit("
{}
") + + if line.find(":=") != -1: + if not in_samp: + emit("
Parameters

") + in_samp = True + + if line == '...\n' or line == '. .\n': + if in_code: + in_code = False + emit("
") + else: + in_code = True + if line == '...\n': + emit("Example

") + emit("") + continue + + if line == '\n' or line == '': + if in_samp: + emit("") + in_samp = False + emit('
') + if not in_code: + emit('
') + continue + + if in_code or in_samp: + line = line.replace(" ", " ") + line = line.replace("\n", "
") + + while line.find('[*') != -1 and line.find('*]') != -1: + (b, s, e) = line.partition('[*') + (l, s, e) = e.partition('*]') + line = '{}{}{}'.format(b, l, l, e) + if l not in param_refd: + param_refd.append(l) + + while line.find('[[') != -1 and line.find(']]') != -1: + (b, s, e) = line.partition('[[') + (l, s, e) = e.partition(']]') + line = '{}{}{}'.format(b, l, l, e) + + if at == DESCRIPTION: + if line[0] == '*' and line[-2] == '*': + emit("

{}

".format(line[1:-2])) + elif line[0] == '[' and line[-2] == ']': + pass + else: + emit(line) + + elif at == OVERVIEW: + if line == "\n": + emit("") + else: + (func, sep, desc) = line.partition(' ') + if desc != '': + emit("{}{}". + format(func, func, desc)) + else: + emit("{}". + format(func).replace("_", " ")) + + elif at == CLASS or at == FUNC: + if at_funchdr: + in_func = True + + if in_code: + emit("
***C***
") + in_code = False + + if in_samp: + emit("
***S***") + in_samp = False + + (func, sep1, end1) = line.partition("(") + (parl, sep2, end2) = end1.partition(")") + pars = parl.split(",") + + func = func.strip() + + if at == FUNC: + func = "pigpio." + func + else: + if func == "__init__": + func = "pigpio." + _class + + emit("

{}".format(func,func)) + + emit('(') + + x = 0 + for p in pars: + (p, sep3, end3) = p.partition('=') + p = p.strip() + if (p != 'self') and (p != '...') and (p != ''): + if p not in param_used: + param_used.append(p) + if x > 0: + emit(", ") + x += 1 + emit("{}".format(p, p)) + emit(')

\n') + + else: + if in_func: + emit(line) + + elif at == XREF: + if line.find(':') != -1: + (par, sep, end) = line.partition(':') + par = par.strip() + end = end.strip() + emit("

{}: {}

".format(par, par, end)) + + if par.lower() < last_par.lower(): + sys.stderr.write("Out of order {} after {}.\n". + format(par, last_par)) + last_par = par + + if par in param_defd: + sys.stderr.write("Duplicate definition of {}.\n".format(par)) + else: + param_defd.append(par) + else: + emit(line) + +f.close() + diff --git a/DOC/bin/smakdoc.py b/DOC/bin/smakdoc.py new file mode 100755 index 0000000..a36975f --- /dev/null +++ b/DOC/bin/smakdoc.py @@ -0,0 +1,376 @@ +#!/usr/bin/env python3 + +import sys + +def get_file(): + try: + fn = sys.argv[1] + f = open(fn, "r") + except: + exit("aborting, can't open {}".format(fn)) + return f + +def emit(s): + sys.stdout.write(s) + +def str2hex(s): + return ":".join("{:02x}".format(ord(c)) for c in s) + +def get_line(f): + line = f.readline() + if man: + line = line.replace(" \n", "\n.br\n") + else: + line = line.replace("<", "<") + line = line.replace(">", ">") + line = line.replace(" \n", "
\n") + return line + +if len(sys.argv) > 2: # Are we creating a man page? + man = True +else: + man = False + +NONE=0 +INTRO=1 +OVERVIEW=2 +COMMANDS=3 +PARAMETERS=4 +SCRIPTS=5 + +param_used = [] +param_defd = [] + +f = get_file() + +at = NONE + +in_table = False +in_code = False + +funcdef ={} + +if man: + emit(""" +.\" Process this file with +.\" groff -man -Tascii foo.1 +.\" +.TH pigs 1 2012-2020 Linux "pigpio archive" +.SH NAME +pigs - command line socket access to the pigpio daemon.\n +/dev/pigpio - command line pipe access to the pigpio daemon.\n +.SH SYNOPSIS\n +.B sudo pigpiod\n +then\n +.B pigs {command}+\n +or\n +.B \"echo {command}+ >/dev/pigpio\"\n +.SH DESCRIPTION\n +.ad l\n +.nh\n +""") + +while True: + + line = get_line(f) + + if line == "": + for p in param_used: + if p not in param_defd: + sys.stderr.write("{} used but not defined.\n".format(p)) + for p in param_defd: + if p not in param_used: + sys.stderr.write("{} defined but not used.\n".format(p)) + break + + if line.startswith("INTRO"): + line = get_line(f) + + if man: + pass + else: + emit("

Introduction

\n") + + at = INTRO + + elif line.startswith("OVERVIEW"): + line = get_line(f) + + if man: + emit("\n.SH OVERVIEW\n") + else: + emit("

Overview

\n") + emit( + "") + at = OVERVIEW + + elif line.startswith("COMMANDS"): + line = get_line(f) + + if man: + emit("\n.SH COMMANDS\n") + else: + emit("
") + emit("

Commands

\n") + + funcs = sorted(funcdef) + at = COMMANDS + + elif line.startswith("PARAMETERS"): + line = get_line(f) + last_par = "" + + if man: + emit("\n.SH PARAMETERS\n") + else: + emit("

Parameters

\n") + + at = PARAMETERS + + elif line.startswith("SCRIPTS"): + line = get_line(f) + + if man: + emit("\n.SH SCRIPTS\n") + else: + emit("

Scripts

\n") + + at = SCRIPTS + + if at != NONE: + if line.find("@") != -1: + if not in_table: + in_table = True + + if man: + emit("\n.EX\n") + else: + emit("") + if man: + pass + else: + emit("") + + if man: + line = line.replace("@", " ") + emit(line) + else: + cols = line.split("@") + for col in cols: + emit("".format(col.strip())) + + if man: + pass + else: + emit("") + continue + else: + if in_table: + in_table = False + + if man: + emit("\n.EE\n") + else: + emit("
{}
") + + if line == "...\n" or line == ". .\n": + if in_code: + in_code = False + + if man: + emit("\n.EE\n") + else: + emit("") + + else: + in_code = True + + if at == COMMANDS: + + if line == "...\n": + if man: + emit("\n\\fBExample\\fP\n.br\n") + else: + emit("Example

") + + if man: + emit("\n.EX\n") + else: + emit("") + + continue + + if line == "\n" and at != OVERVIEW: + if man: + # emit("\n.br\n.br\n") + emit("\n.br\n") + else: + emit("

") + continue + + if in_code: + if man: + line = line.replace("\n", "\n.br\n") + else: + line = line.replace(" ", " ") + line = line.replace("\n", "
") + + while line.find("[*") != -1 and line.find("*]") != -1: + (b, s, e) = line.partition("[*") + (l, s, e) = e.partition("*]") + if man: + line = "{}\\fB{}\\fP{}".format(b, l, e) + else: + line = "{}{}{}".format(b, l, l, e) + + while line.find("[{") != -1 and line.find("}]") != -1: + (b, s, e) = line.partition("[[") + (l, s, e) = e.partition("]]") + + if man: + line = "{}\\fB{}\\fP{}".format(b, l, e) + else: + line = "{}{}{}".format(b, l, l, e) + + if at == INTRO or at == SCRIPTS: + if line[0] == "*" and line[-2] == "*": + if man: + emit(".SS {}".format(line[1:-2])) + else: + emit("

{}

".format(line[1:-2])) + else: + emit(line) + + elif at == OVERVIEW: + if line == "\n": + + if man: + pass + else: + emit("") + + elif line.find("::") == -1: + + if man: + emit(".SS {}".format(line)) + else: + emit("{}".format(line)) + else: + (funcpar, sep, desc) = line.partition("::") + funcpar = funcpar.strip() + desc = desc.strip() + if desc != "": + (func, sep, parl) = funcpar.partition(" ") + func = func.strip() + parl = parl.strip() + if func in funcdef: + sys.stderr.write("{} has been redefined.\n".format(func)) + funcdef[func]=parl+"::"+desc + + if man: + emit(".B {}\n".format(func+" "+parl+" ")) + pass + else: + emit("{}".format(func, func)) + + pars = parl.split() + + for p in pars: + + if p not in param_used: + param_used.append(p) + + if man: + pass + else: + emit(" {}".format(p, p)) + + (des, sep, c) = desc.partition("::") + c = c.strip() + + if man: + emit("{}\n.P\n".format(des)) + pass + else: + emit("{}{}".format(des, c, c)) + + else: + if man: + pass + else: + emit("{}".format(funcpar)) + + if man: + # emit(".IP {} 9\n".format(func)) + pass + else: + emit("{}".format(func, func)) + + + elif at == COMMANDS: + if line.find("::") != -1: + (func, sep, desc) = line.partition("::") + func = func.strip() + + if func not in funcdef: + parl="unknown" + desc="unknown" + else: + (parl,sep,desc) = funcdef[func].partition("::") + + (des, sep, c) = desc.partition("::") + + if man: + t = "\\fB" + func + " " + parl + "\\fP" + " - " + des.strip() + emit("\n.IP \"{}\"\n.IP \"\" 4\n".format(t)) + else: + emit("

{}\n".format(func,func)) + + pars = parl.split() + for p in pars: + + if man: + pass + else: + emit(" {}".format(p, p)) + + if man: + pass + else: + emit(" - {}

".format(des.strip())) + + else: + emit(line) + + elif at == PARAMETERS: + if line.find("::") != -1: + (par, sep, desc) = line.partition("::") + par = par.strip() + desc = desc.strip() + + if par.lower() < last_par.lower(): + sys.stderr.write("Out of order {} after {}.\n".format(par, last_par)) + last_par = par + + if par in param_defd: + sys.stderr.write("Duplicate definition of {}.\n".format(par)) + else: + param_defd.append(par) + + if man: + emit("\n.IP \"\\fB{}\\fP - {}\" 0\n".format(par, desc)) + else: + emit("

{} - {}

\n".format(par,par,desc)) + else: + emit(line) + +if man: + emit(""" +.SH SEE ALSO\n +pigpiod(1), pig2vcd(1), pigpio(3), pigpiod_if(3), pigpiod_if2(3) +.SH AUTHOR\n +joan@abyz.me.uk +""") + +f.close() + diff --git a/DOC/bin/tidy.py b/DOC/bin/tidy.py new file mode 100755 index 0000000..4a789f4 --- /dev/null +++ b/DOC/bin/tidy.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 + +import glob + +def snafu(t, s, r): + l = t + while l.find(s) != -1: + l = l.replace(s, r) + return l + +for n in glob.glob("tmp/body/*.body"): + + f = open(n, "r"); + t = f.read() + f.close() + + t = snafu(t, "

", "

") + t = snafu(t, "

", "

") + t = snafu(t, "


", "") + t = snafu(t, "\n
", "\n") + t = snafu(t, "
", "") + t = snafu(t, "\n
", "\n") + t = snafu(t, "


", "

") + + f = open(n, "w"); + f.write(t) + f.close() + diff --git a/DOC/bin/updatesql.py b/DOC/bin/updatesql.py new file mode 100755 index 0000000..56a916c --- /dev/null +++ b/DOC/bin/updatesql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +import sqlite3 +import glob + +db=sqlite3.connect("dbase/pigpio.sqlite") + +c=db.cursor() + +for fn in glob.glob("tmp/body/*.body"): + f = open(fn, encoding='utf-8') + body = f.read() + f.close() + c.execute("UPDATE pigpio SET body=? WHERE file_name=?", (body, fn[9:-5])) + +c.close() + +db.commit() + +db.close() + diff --git a/DOC/dbase/pigpio.sqlite b/DOC/dbase/pigpio.sqlite new file mode 100644 index 0000000..9088598 Binary files /dev/null and b/DOC/dbase/pigpio.sqlite differ diff --git a/DOC/makedoc b/DOC/makedoc new file mode 100755 index 0000000..4494252 --- /dev/null +++ b/DOC/makedoc @@ -0,0 +1,47 @@ +#!/bin/bash + +mkdir -p tmp/pydoc +mkdir -p tmp/body + +echo "*** making man pages ***" + +echo "pigs" +bin/smakdoc.py src/defs/pigs.def man >MAN/pigs.1 + +echo "pigpiod" +bin/cmakdoc.py pigpiod src/defs/pigpiod.def man >MAN/pigpiod.1 + +echo "pig2vcd" +bin/cmakdoc.py pig2vcd src/defs/pig2vcd.def man >MAN/pig2vcd.1 + +echo "pigpio.h" +bin/cmakdoc.py pigpio ../pigpio.h man >MAN/pigpio.3 + +echo "pigpiod_if.h" +bin/cmakdoc.py pigpiod_if ../pigpiod_if.h man >MAN/pigpiod_if.3 + +echo "pigpiod_if2.h" +bin/cmakdoc.py pigpiod_if2 ../pigpiod_if2.h man >MAN/pigpiod_if2.3 + +# *** preparing HTML bodies *** + +bin/smakdoc.py src/defs/pigs.def >tmp/body/pigs.body +bin/cmakdoc.py pigpiod src/defs/pigpiod.def >tmp/body/pigpiod.body +bin/cmakdoc.py pig2vcd src/defs/pig2vcd.def >tmp/body/pig2vcd.body +bin/cmakdoc.py pigpio ../pigpio.h >tmp/body/cif.body +bin/cmakdoc.py pigpiod_if ../pigpiod_if.h >tmp/body/pdif.body +bin/cmakdoc.py pigpiod_if2 ../pigpiod_if2.h >tmp/body/pdif2.body +pydoc ../pigpio.py >tmp/pydoc/pigpio.pydoc +bin/pymakdoc.py tmp/pydoc/pigpio.pydoc >tmp/body/python.body +bin/examples.py src/defs/examples.def >tmp/body/examples.body + +bin/body.py # get bodies of manually generated pages +bin/tidy.py # tidy the bodies +bin/backup.sh # backup database +bin/updatesql.py # update the database with the new bodies +bin/purge.sh # remove redundant datatbase copies + +echo "*** making web pages ***" + +bin/build_site.py # construct the web site + diff --git a/DOC/src/defs/examples.def b/DOC/src/defs/examples.def new file mode 100644 index 0000000..1ead75f --- /dev/null +++ b/DOC/src/defs/examples.def @@ -0,0 +1,528 @@ +The following examples show various ways pigpio may be used to communicate with sensors via the GPIO. + +Although many are complete programs they are intended to be a starting point in producing your own code, not an end point. + +?0|Index + +?0|Hardware + +?0|Shell code + +?0|C code + +?0|C++ code + +?0|pigpiod_if2 code + +?0|Python code + +?0|Miscellaneous related code + +?0|External links + +?1|Hardware|Hardware + +A few practical examples of using pigpio with hardware. + +?2|ex_ir_remote|2013-06-09|IR Receiver +Reading an infrared remote receiver. + +?2|ex_LDR|2013-06-09|Light Dependent Resistor +Measuring brightness with a light dependent resistor (LDR). Improved methods of timing the start of the capacitor recharge are given for C and Python. + +?2|ex_motor_shield|2013-12-15|Motor Shield +Using an Arduino motor shield. + +?2|ex_rotary_encoder|2013-06-09|Rotary Encoder +Reading a rotary encoder. + +?2|ex_sonar_ranger|2013-06-10|Sonar Ranger +Measuring range with a sonar ranger. + +?1|Shell|Shell code + +Examples of using pigpio with shell code. + +?3|gpiotest|2014-08-11|GPIO test +This bash script tests the user GPIO. Video + +?1|C|C code + +Examples of C pigpio programs. + +If your program is called foobar.c then build with + +gcc -Wall -o foobar foobar.c -lpigpio + +?3|freq_count_1|2014-08-20|Frequency Counter 1 +A program showing how to use the gpioSetAlertFunc function to set a callback for GPIO state changes. A frequency count is generated for each monitored GPIO (frequencies up to 500kHz with a sample rate of 1μs). + +?3|freq_count_2|2014-08-20|Frequency Counter 2 +A program showing how to use the gpioSetGetSamplesFunc function to set a callback for accumulated GPIO state changes over the last millisecond. A frequency count is generated for each monitored GPIO (frequencies up to 500kHz with a sample rate of 1μs). Generally the method used is more complicated but more efficient than frequency counter 1. + +?3|hall|2014-06-13|Hall Effect Sensor +Program to show status changes for a Hall effect sensor. + +?3|I2C_sniffer|2014-06-15|I2C Sniffer +A program to passively sniff I2C transactions (100kHz bus maximum) and display the results. This C program uses pigpio notifications. + +?3|ir_hasher_c|2015-02-25|IR Receiver +Function to hash a code from an IR receiver (reading an IR remote control). + +?3|PCF8591|2014-08-26|PCF8591 YL-40 +A program to display readings from the (I2C) PCF8591. + +?3|pot_cap_charge_c|2014-03-14|Pot + Capacitor Recharge Timing +Function to time capacitor charging (through a resistance). The time can be used to estimate the resistance. + +?3|pps_c|2020-07-28|Pulse Per Second generator +A program to generate a pulse on a GPIO every x seconds (1<=x<=60). The pulse is synced with the wall time second boundary. + +?3|rotary_encoder_c|2015-10-03|Rotary Encoder +Function to decode a mechanical rotary encoder. + +?3|rawMCP3008_c|2016-03-20|SPI bit bang MCP3008 +This program shows how to read multiple MCP3008 ADC simultaneously with accurately timed intervals. One 10-bit channel of each ADC may be sampled at up to 25k samples per second. + +?3|rawMCP3202_c|2016-03-20|SPI bit bang MCP3202 +This program shows how to read multiple MCP3202 ADC simultaneously with accurately timed intervals. One 12-bit channel of each ADC may be sampled at up to 25k samples per second. + +?3|rawMCP3XXX_c|2016-03-20|SPI bit bang MCP3008 and MCP3202 +This program shows how to read multiple MCP3008 and MCP3202 ADC simultaneously with accurately timed intervals. One channel of each ADC may be sampled at up to 25k samples per second. The 10-bit MCP3008 readings are multiplied by 4 so they have the same range (0-4095) as the 12-bit MCP3202. + +?3|servo_demo|2016-10-08|Servo Pulse Generator +This program generates servo pulses on one or more GPIO. Each connected servo is swept between 1000µs and 2000µs at a different speed. + +sudo ./servo_demo # Generate pulses on GPIO 4. + +sudo ./servo_demo 5 9 20 # Generate pulses on GPIO 5, 9, and 20. + +?4|code/spi-pigpio-speed.c|2016-11-06|SPI pigpio driver speed test +This C code is used to benchmark the pigpio SPI driver on the Pi. The code executes a given number of loops at a given baud rate and bytes per transfer. + +?3|wiegand_c|2013-12-30|Wiegand Reader +Function to read a Wiegand Reader. + +?1|C++|C++ code + +Examples of C++ pigpio programs. + +If your program is called foobar.cpp then build with + +g++ -Wall -pthread -o foobar foobar.cpp -lpigpio -lrt + +?3|ir_hasher_cpp|2015-02-22|IR Receiver +Class to hash a code from an IR receiver (reading an IR remote control). + +?3|rotary_encoder_cpp|2013-12-30|Rotary Encoder +Class to decode a mechanical rotary encoder. + +?3|wiegand_cpp|2013-12-30|Wiegand Reader +Class to read a Wiegand Reader. + +?1|pdif2|pigpiod_if2 code +The pigpiod_if2 code examples are linked with libpigpiod_if2 and are written in C. + +The pigpiod_if2 library may be compiled and run on any Linux machine and allows control of the GPIO on one or more networked Pis. + +It should be possible to adapt the library to run on Macs and PCs. + +Each Pi needs the pigpio daemon to be running. The pigpio daemon may be started with the command sudo pigpiod. + +?3|_433D|2015-11-17|433MHz Keyfob RX/TX +Code to read and transmit 313 and 434 MHz key fob codes. The codes to be read must use Manchester encoding. The transmitted codes use Manchester encoding. + +./_433D -r10 # Print fob keycodes received on GPIO 10. + +./_433D -t5 8246184 # Transmit code on GPIO 5. + +./_433D -r10 -t5 8246184 # Transmit code on GPIO 5 then listen for codes + +./_433D -? for options. + +?3|DHTXXD|2016-02-16|DHT11/21/22/33/44 Sensor +Code to read the DHT temperature and humidity sensors. The sensor may be auto detected. A DHT11 sensor may be read once per second. The other sensors should not be read more often than once every three seconds. + +The code auto detects the DHT model and generally only the GPIO needs to be specified. + +./DHTXXD -g17 # Read a DHT connected to GPIO 17. + +./DHTXXD -g5 -i3 # Read a DHT connected to GPIO 5 every three seconds. + +./DHTXXD -? # for options. + +?3|RED|2015-11-18|Rotary Encoder +Code to monitor a rotary encoder and show the position changes. By default the detent changes are shown. There is an option to show the four steps per detent instead. + +./RED -a7 -b8 -s30 # Show encoder on 7/8 detent changes for 30 seconds. + +./RED -a5 -b6 -m1 # Show encoder on 5/6 step changes forever. + +./RED -? # for options. + +?3|servo_demo_D|2016-10-08|Servo Pulse Generator +This program generates servo pulses on one or more GPIO. Each connected servo is swept between 1000µs and 2000µs at a different speed. + +./servo_demo_D # Generate pulses on GPIO 4. + +./servo_demo_D 5 9 20 # Generate pulses on GPIO 5, 9, and 20. + +?3|SRTED|2015-11-16|Sonar Ranger +Code to read the SRF-04 and SRF-05 type of sonar rangers which use the trigger echo method of operation. A 10 μs trigger pulse initiates a series of high frequency sonar chirps. The echo line then goes high and stays high until an echo from an object is received. The echo high time is used to calculate the distance of the object. + +For a one-off reading only the trigger and echo GPIO need to be specified. + +./SRTED -t5 -e6 # Read a sonar ranger connected to GPIO 5/6. + +./SRTED -t11 -e5 -i0.1 # Read a sonar ranger connected to GPIO 11/5 every 0.1 seconds. + +./SRTED -? # for options. + +?3|tx_RED|2015-11-25|Transmit Rotary Encoder Test Signals +Code to transmit quadrature signals to test rotary encoder software. + +tx_RED -aGPIO -bGPIO [options] + +tx_RED -? for options + +E.g. + +tx_RED -a5 -b6 -s20 -r-100 + +?3|tx_WD|2015-11-25|Transmit Wiegand Test Signals +Code to transmit Wiegand codes to test Wiegand decoder software. + +tx_WD -gGPIO -wGPIO [options] {code}+ + +tx_WD -? for options + +E.g. + +tx_WD -g5 -w6 -s37 12345 67890 123 899999 + +?3|WD|2015-11-25|Wiegand Reader +Code to read a Wiegand Reader. + +./WD -g7 -w8 -s30 # Read Wiegand codes from GPIO 7/8 for 30 seconds. + +./WD -g5 -w6 # Read Wiegand codes from GPIO 5/6 forever. + +./WD -? # for options. + +?1|Python|Python code +The Python code may be run on any Python machine and allows control of the GPIO on one or more networked Pis. + +The Python machine need not be a Pi, it may run Windows, Mac, Linux, anything as long as it supports Python. + +Each Pi needs the pigpio daemon to be running. The pigpio daemon may be started with the command sudo pigpiod. + +?3|_433_py|2015-10-30|433MHz Keyfob RX/TX +Classes to send and receive 433MHz wireless keyfob codes. These keyfobs are widely used for remote control of devices. + +?3|_7_segment|2016-12-12|7-Segment LED Display Multiplexing +Script to multiplex several 7-segment LED displays. Each display has the segments a-g and the decimal point connected in parallel but has an individual enable GPIO (connected to the common anode or cathode). + +?3|test-APA102_py|2017-03-28|APA102 LED strip driver +Script to drive an APA102 LED strip. Three different methods are demonstrated - using spidev SPI (only works on the local Pi), pigpio SPI, and pigpio waves. The SPI solutions only work with the dedicated SPI GPIO. Waves may use any spare GPIO. Four different examples are given including a LED strip clock. + +?3|BME280_py|2016-08-05|BME280 Sensor +Class to read the relative humidity, temperature, and pressure from a BME280 sensor. The sensor has both an I2C and a SPI interface which are both +supported by the class. + +?4|code/DHT.py|2019-11-07|DHT11/21/22/33/44 Sensor +Class to read the relative humidity and temperature from a DHT sensor. It can automatically recognize the sensor type. + +The default script prints the reading from the specified DHT every 2 seconds. E.g. ./DHT.py 22 27 displays the data for DHT connected to GPIO 22 and 27. + +The following data is printed for each DHT: timestamp, GPIO, status, temperature, and humidity. + +The timestamp is the number of seconds since the epoch (start of 1970). + +The status will be one of: 0 - a good reading, 1 - checksum failure, 2 - data had one or more invalid values, 3 - no response from sensor. + +?3|DHT22_py|2014-07-11|DHT22 AM2302 Sensor +Class to read the relative humidity and temperature from a DHT22/AM2302 sensor. + +?3|DS18B20-1_py|2016-06-29|DS18B20 Temperature Sensor +Script to read the temperature from any DS18B20 sensors connected to the 1-wire bus. + +To enable the 1-wire bus add the following line to /boot/config.txt and reboot. + +dtoverlay=w1-gpio + +By default you should connect the DS18B20 data line to GPIO 4 (pin 7). + +Connect 3V3 or 5V for power, ground to ground, 4k7 pull-up on data line to 3V3, and data line to GPIO 4. + +This script uses the file features of pigpio to access the remote file system. + +The following entry must be in /opt/pigpio/access. + +/sys/bus/w1/devices/28*/w1_slave r + +?3|PPD42NS_py|2015-11-22|Dust Sensor +Class to read a Shinyei PPD42NS Dust Sensor, e.g. as used in the Grove dust sensor. + +?3|gpio_status_py|2014-06-12|GPIO Status +Script to display the status of GPIO 0-31. + +?3|hall|2014-06-13|Hall Effect Sensor +Program to show status changes for a Hall effect sensor. + +?3|HX711_py|2018-03-05|HX711 24-bit ADC +Class to read the channels of a HX711 24-bit ADC. + +?3|i2c_ADXL345_py|2015-04-01|I2C ADXL345 Accelerometer +Script to display the X, Y, and Z values read from an ADXL345 accelerometer. + +?3|i2c_HMC5883L_py|2015-04-01|I2C HMC5883L Magnetometer +Script to display the X, Y, and Z values read from a HMC5883L Magnetometer (compass). + +?3|i2c_ITG3205_py|2015-04-01|I2C ITG3205 Gyroscope +Script to display the X, Y, Z, and temperature values read from an ITG3205 gyroscope. + +?3|i2c_lcd_py|2016-04-20|I2C LCD Display +Class to display text on a LCD character display. The class supports the PCF8574T 8-bit I2C port expander connected to a HD44780 based LCD display. These displays are commonly available in 16x2 and 20x4 character formats. + +?3|bsc_arduino_py|2016-10-31|I2C slave device +This script demonstrates how to transfer messages from an Arduino acting as the I2C bus master to the Pi acting as an I2C slave device. + +?3|I2C_sniffer|2015-06-15|I2C Sniffer +A program to passively sniff I2C transactions (100kHz bus maximum) and display the results. + +?3|i2c_sonar_py|2016-03-24|I2C Sonar +A class to read up to 8 HC-SR04 sonar rangers connected to an MCP23017 port expander. + +?3|ir_hasher_py|2014-06-12|IR Receiver +Class to hash a code from an IR receiver (reading an IR remote control). + +?3|irrp_py|2015-12-21|IR Record and Playback +This script may be used to record and play back arbitrary IR codes. + +To record the GPIO connected to the IR receiver, a file for the recorded codes, and the codes to be recorded are given. + +E.g. ./irrp.py -r -g4 -fir-codes vol+ vol- 1 2 3 4 5 6 7 8 9 0 + +To playback the GPIO connected to the IR transmitter, the file containing the recorded codes, and the codes to be played back are given. + +E.g. ./irrp.py -p -g18 -fir-codes 2 3 4 + +./irrp.py -h # for options + +?3|kivy_GPIO_py|2016-12-11|Kivy GPIO control +This example shows how to use Kivy to control a Pi's GPIO. The GPIO may be configured as inputs, outputs, or to generate Servo or PWM pulses. Kivy is an Open source Python library for rapid development of applications. + +?3|MAX6675_py|2016-05-02|MAX6675 SPI Temperature Sensor +A script to read the temperature from a MAX6675 connected to a K-type thermocouple. The MAX6675 supports readings in the range 0 - 1023.75 C. Up to 4 readings may be made per second. + +?3|monitor_py|2016-09-17|Monitor GPIO +Script to monitor GPIO for level changes. By default all GPIO are monitored. At a level change the GPIO, new level, and microseconds since the last change is printed. + +?3|morse_code_py|2015-06-17|Morse Code +Script to transmit the morse code corresponding to a text string. + +?4|code/NRF24.py|2018-01-06|NRF24 radio transceiver +Script to transmit and receive messages using the nRF24L01 radio transceiver. + +?3|PCA9685_py|2016-01-31|PCA9685 16 Channel PWM +Class to control the 16 PWM channels of the I2C PCA9685. All channels use the same frequency. The duty cycle or pulse width may be set independently for each channel. + +?3|PCF8591|2014-08-26|PCF8591 YL-40 +Script to display readings from the (I2C) PCF8591. + +?4|code/PPM.py|2016-02-19|PPM (Pulse Position Modulation) generation +Script to generate PPM signals on a chosen GPIO. + +?4|code/PPM_to_servo.py|2019-10-09|PPM (Pulse Position Modulation) to servo pulses +Script to read a PPM signal on a GPIO and generate the corresponding servo signals on chosen GPIO. + +?3|bench_1_py|2014-06-12|pigpio Benchmark +Script to benchmark the pigpio Python module's performance. + +?3|pigpio_cgi_py|2015-05-04|pigpio CGI +Script demonstrating how to access the pigpio daemon using CGI from a browser. Instructions on how to use with Apache2 on the Pi are given in the comments. + +?3|playback_py|2016-12-23|Playback piscope recordings +Script to playback GPIO data recorded in piscope format. + +To playback GPIO 4 to GPIO 4 from file data.piscope +./playback.py data.piscope 4 + +To playback GPIO 4 to GPIO 7 from file rec.txt +./playback.py rec.txt 7=4 + +?3|pot_cap_py|2016-09-26|Pot + Capacitor Recharge Timing +Class to time capacitor charging (through a resistance). The time can be used to estimate the resistance. + +?3|read_PWM_py|2015-12-08|PWM Monitor +Class to monitor a PWM signal and calculate the frequency, pulse width, and duty cycle. + +?3|rotary_encoder_py|2014-06-12|Rotary Encoder +Class to decode a mechanical rotary encoder. + +?3|read_RPM_py|2016-01-20|RPM Monitor +Class to monitor speedometer pulses and calculate the RPM (Revolutions Per Minute). + +?3|Si7021_py|2016-05-07|Si7021 I2C Temperature and Humidity Sensor +Class to read the temperature and relative humidity from a Si7021. + +?3|SPI_mon_py|2016-09-21|SPI Monitor +A program to passively sniff SPI transactions and display the results. The SPI rate should be limited to about 70kbps if using the default pigpio 5µs sampling rate. + +?3|servo_demo_py|2016-10-07|Servo Pulse Generator +This script generates servo pulses on one or more GPIO. Each connected servo is swept between 1000µs and 2000µs at a different speed. + +./servo_demo.py # Generate pulses on GPIO 4. + +./servo_demo.py 5 9 20 # Generate pulses on GPIO 5, 9, and 20. + +?3|sonar_trigger_echo_py|2014-06-12|Sonar Ranger +Class to read sonar rangers with separate trigger and echo pins. + +?3|TCS3200_py|2015-07-03|TCS3200 Colour Sensor +Class to read the TCS3200 colour sensor + +?3|vw|2015-10-31|Virtual Wire +Class to send and receive radio messages compatible with the Virtual Wire library for Arduinos. This library is commonly used with 313MHz and 434MHz radio tranceivers. + +?4|code/create_wave.py|2019-11-18|Wave create +Script to generate waves from a template defined in a text file. + +You can also specify one of py, c, or pdif - the script output will then be a complete program to generate the wave (py for Python script, c for a C program, pdif for a C program using the pigpio daemon I/F). + +If none of py, c, or pdif are chosen the waveform will be generated for 30 seconds. + +Example text file + +# GPIO levels +23 11000001 +11 01110000 +12 00011100 +4 00000111 + +To generate a pdif program with a bit time of 100 microseconds +./create_wave.py wave_file 100 pdif >wave_pdif.c + +To just transmit the wave with a bit time of 50 microseconds +./create_wave.py wave_file 50 + +?3|wave_PWM_py|2016-03-19|Wave PWM 1 +Script to show how waves may be used to generate PWM at (one) arbitrary frequency on multiple GPIO. For instance PWM at 10kHz may be generated with 100 steps between off and fully on. + +?3|wavePWM_py|2016-10-06|Wave PWM 2 +Class to generate PWM on multiple GPIO. It is more flexible than the Wave PWM 1 example in that the start of the pulse within each cycle may be specified as well as the duty cycle. The start and length of each pulse may be specified on a GPIO by GPIO basis in microseconds or as a fraction of the cycle time. The class includes a __main__ to demostrate its ability to send servo pulses. + +?3|wiegand_py|2014-06-12|Wiegand Reader +Class to read a Wiegand reader. + +?1|Misc|Miscellaneous related code + +The following code examples do not use pigpio. + +?3|adxl345_c|2014-03-12|ADXL345 +This C program reads x, y, and z accelerations from the ADXL345 via I2C address 0x53. + +?3|DS18B20_py|2016-04-25|DS18B20 Temperature Sensor +This Python script reads the temperature from any DS18B20 sensors connected to the 1-wire bus. + +To enable the 1-wire bus add the following line to /boot/config.txt and reboot. + +dtoverlay=w1-gpio + +By default you should connect the DS18B20 data line to GPIO 4 (pin 7). + +Connect 3V3 or 5V for power, ground to ground, 4k7 pull-up on data line to 3V3, and data line to GPIO 4. + +?3|EasyAsPiServer|2014-09-15|Easy as Pi Server +This Python class implements a simple server which allows broswer commands to be executed on the Pi. + +?3|minimal_clk|2015-05-20|Minimal Clock Access +This C code sets GPIO 4 to a specified clock frequency. The frequency can be set between 4.6875 kHz and 500 MHz (untested). The clock can be preferentially set from one of the sources OSC (19.2MHz), HDMI (216MHz), PLLD (500MHz), or PLLC (1000MHz). MASH can be set between 0 and 3. MASH may not work properly for clock dividers less than 5. + +?3|minimal_gpio|2019-07-03|Minimal GPIO Access +This C code has a minimal set of functions needed to control the GPIO and other Broadcom peripherals. The program requires root privileges to run. See Tiny GPIO access for an alternative which controls the GPIO (but not the other peripherals) and does not require root access. + +The code has been updated for the BCM2711 (Pi4B). + +The following functions are provided. + +gpioInitialise +gpioSetMode +gpioGetMode +gpioSetPullUpDown +gpioRead +gpioWrite +gpioTrigger +gpioReadBank1 +gpioReadBank2 +gpioClearBank1 +gpioClearBank2 +gpioSetBank1 +gpioSetBank2 +gpioHardwareRevision +gpioTick + +?3|nanopulse_c|2014-01-29|Nanosecond Pulse Generation +This C program uses the PWM peripheral to generate precisely timed pulses of very short duration. Pulses as short as 4 nano seconds can be generated. + +?3|PCF8591-x|2014-08-26|PCF8591 YL-40 +C and Python code to read the (I2C) PCF8591. + +?4|code/spi-driver-speed.c|2016-11-06|SPI Linux driver speed test +This C code is used to benchmark the Linux SPI driver on the Pi. The code executes a given number of loops at a given baud rate and bytes per transfer. + +?3|tiny_gpio|2016-04-30|Tiny GPIO Access +This C code has a minimal set of functions needed to control the GPIO without needing root privileges (it uses /dev/gpiomem to access the GPIO). + +You may need to change the permissions and ownership of /dev/gpiomem if they have not been correctly set up. + +sudo chown root:gpio /dev/gpiomem +sudo chmod g+rw /dev/gpiomem + +The user (default pi) needs to be in the gpio group. + +sudo adduser pi gpio + +The following functions are provided. + +gpioInitialise +gpioSetMode +gpioGetMode +gpioSetPullUpDown +gpioRead +gpioWrite +gpioTrigger +gpioReadBank1 +gpioReadBank2 +gpioClearBank1 +gpioClearBank2 +gpioSetBank1 +gpioSetBank2 +gpioHardwareRevision + +?1|External|External links + +Related code. + +?4|https://pypi.org/project/nrf24/|2020-04-20|NRF24 +Python Package Index (Pypi) NRF24 module. +pip install nrf24 + +?4|https://github.com/bjarne-hansen/py-nrf24|2020-04-20|NRF24 +Code and example usage of the Pypi NRF24 module. Cleaned up and added support for reading from multiple pipes using open_reading_pipe(pipe, address) and open_writing_pipe(address) in order to be more "compatible" with the way NRF24 is used on Arduinos. + +?4|https://github.com/paulvee/pigpio-serial-bb-examples|2020-11-16|bit bang serial RX +Example code showing how to use the bit banged serial links. + +One example shows how to read the serial data from an Arduino based counter, that sends results every 1,000 or 10,000 seconds. + +Another example shows how to parse into sentences the NMEA stream coming from a U-Blox GPS module. + +?4|https://github.com/stripcode/pigpio-stepper-motor|2016-08-12|Stepper Motor +Stepper motor code. + +?4|https://github.com/choeffer/360pibot|2018-11-03|Parallax ActivityBot 360 +Python 3 implementation for programming a Parallax ActivityBot 360 Robot Kit with a Raspberry Pi. + +?1|Index|Index + diff --git a/DOC/src/defs/pig2vcd.def b/DOC/src/defs/pig2vcd.def new file mode 100644 index 0000000..48e1013 --- /dev/null +++ b/DOC/src/defs/pig2vcd.def @@ -0,0 +1,110 @@ + +/*TEXT +pig2vcd is a utility which reads notifications on stdin and writes the +output as a Value Change Dump (VCD) file on stdout. + +The VCD file can be viewed using GTKWave. + +*Notifications* + +Notifications consist of 12 bytes with the following binary format. + +. . +typedef struct +{ + uint16_t seqno; + uint16_t flags; + uint32_t tick; + uint32_t level; +} gpioReport_t; +. . + +seqno: starts at 0 each time the handle is opened and then increments by one for each report. + +flags: two flags are defined, PI_NTFY_FLAGS_WDOG and PI_NTFY_FLAGS_ALIVE. If bit 5 is set (PI_NTFY_FLAGS_WDOG) then bits 0-4 of the flags indicate a gpio which has had a watchdog timeout; if bit 6 is set (PI_NTFY_FLAGS_ALIVE) this indicates a keep alive signal on the pipe/socket and is sent once a minute in the absence of other notification activity. + +tick: the number of microseconds since system boot. It wraps around after 1h12m. + +level: indicates the level of each gpio. If bit 1</dev/pigpio + +pigs will show the result of the command on screen. + +The pigs process returns an exit status (which can be displayed with +the command echo $?). + +... +PIGS_OK 0 +PIGS_CONNECT_ERR 255 +PIGS_OPTION_ERR 254 +PIGS_SCRIPT_ERR 253 +... + +The results of /dev/pigpio commands need to be read from /dev/pigout, +e.g. cat /dev/pigout (try cat /dev/pigout& so that all subsequent +results are shown on screen). + +In both cases if an error was detected a message will have been written +to /dev/pigerr (try cat /dev/pigerr&). This is likely to be more +informative than the message returned by pigs or the error code +returned by the pipe interface. + +Several commands may be entered on a line. If present PROC and PARSE must +be the last command on a line. + +E.g. + +... +pigs w 22 1 mils 1000 w 22 0 +... + +is equivalent to + +... +pigs w 22 1 +pigs mils 1000 +pigs w 22 0 +... + +and + +... +echo "m 4 w w 4 0 mils 250 m 4 r r 4" >/dev/pigpio +... + +is equivalent to + +... +echo "m 4 w" >/dev/pigpio +echo "w 4 0" >/dev/pigpio +echo "mils 250" >/dev/pigpio +echo "m 4 r" >/dev/pigpio +echo "r 4" >/dev/pigpio +... + +*Notes* + +The examples from now on will show the pigs interface but the same +commands will also work on the pipe interface. + +pigs does not show the status of successful commands unless the +command itself returns data. The status (0) will be returned to +pigs but will be discarded. + +The status/data of each command sent to the pipe interface should +be read from /dev/pigout. + +When a command takes a number as a parameter it may be entered as hex +(precede by 0x), octal (precede by 0), or decimal. + +E.g. 23 is 23 decimal, 0x100 is 256 decimal, 070 is 56 decimal. + +Some commands can return a variable number of data bytes. By +default this data is displayed as decimal. The pigs -a option +can be used to force the display as ASCII and the pigs -x +option can be used to force the display as hex. + +E.g. assuming the transmitted serial data is the letters ABCDEONM + +... +$ pigs slr 4 100 +8 65 66 67 68 69 79 78 77 + +$ pigs -a slr 4 100 +8 ABCDEONM + +$ pigs -x slr 4 100 +8 41 42 43 44 45 4f 4e 4d +... + +OVERVIEW + +BASIC + +M/MODES g m :: Set GPIO mode :: gpioSetMode +MG/MODEG g :: Get GPIO mode :: gpioGetMode + +PUD g p :: Set GPIO pull up/down :: gpioSetPullUpDown + +R/READ g :: Read GPIO level :: gpioRead +W/WRITE g L :: Write GPIO level :: gpioWrite + +PWM (overrides servo commands on same GPIO) + +P/PWM u v :: Set GPIO PWM value :: gpioPWM +PFS u v :: Set GPIO PWM frequency :: gpioSetPWMfrequency +PRS u v :: Set GPIO PWM range :: gpioSetPWMrange + +GDC u :: Get GPIO PWM dutycycle :: gpioGetPWMdutycycle +PFG u :: Get GPIO PWM frequency :: gpioGetPWMfrequency +PRG u :: Get GPIO PWM range :: gpioGetPWMrange + +PRRG u :: Get GPIO PWM real range :: gpioGetPWMrealRange + +Servo (overrides PWM commands on same GPIO) + +S/SERVO u v :: Set GPIO servo pulsewidth :: gpioServo + +GPW u :: Get GPIO servo pulsewidth :: gpioGetServoPulsewidth + +INTERMEDIATE + +TRIG u pl L :: Send a trigger pulse :: gpioTrigger + +WDOG u v :: Set GPIO watchdog :: gpioSetWatchdog + +BR1 :: Read bank 1 GPIO :: gpioRead_Bits_0_31 +BR2 :: Read bank 2 GPIO :: gpioRead_Bits_32_53 + +BC1 bits :: Clear specified GPIO in bank 1 :: gpioWrite_Bits_0_31_Clear +BC2 bits :: Clear specified GPIO in bank 2 :: gpioWrite_Bits_32_53_Clear + +BS1 bits :: Set specified GPIO in bank 1 :: gpioWrite_Bits_0_31_Set +BS2 bits :: Set specified GPIO in bank 2 :: gpioWrite_Bits_32_53_Set + +ADVANCED + +NO :: Request a notification :: gpioNotifyOpen +NC h :: Close notification :: gpioNotifyClose +NB h bits :: Start notification :: gpioNotifyBegin +NP h :: Pause notification :: gpioNotifyPause + +HC g cf :: Set hardware clock frequency :: gpioHardwareClock + +HP g pf pdc :: Set hardware PWM frequency and dutycycle :: gpioHardwarePWM + +FG u stdy :: Set a glitch filter on a GPIO :: gpioGlitchFilter +FN u stdy actv :: Set a noise filter on a GPIO :: gpioNoiseFilter + +PADS pad padma :: Set pad drive strength :: gpioSetPad +PADG pad :: Get pad drive strength :: gpioGetPad + +SHELL name str :: Execute a shell command :: shell + +Custom + +CF1 uvs :: Custom function 1 :: gpioCustom1 +CF2 uvs :: Custom function 2 :: gpioCustom1 + +Events + +EVM h bits :: Set events to monitor :: eventMonitor +EVT event :: Trigger event :: eventTrigger + +Scripts + +PROC t :: Store script :: gpioStoreScript +PROCR sid pars :: Run script :: gpioRunScript +PROCU sid pars :: Set script parameters :: gpioUpdateScript +PROCP sid :: Get script status and parameters :: gpioScriptStatus +PROCS sid :: Stop script :: gpioStopScript +PROCD sid :: Delete script :: gpioDeleteScript + +PARSE t :: Validate script :: gpioParseScript + +I2C + +I2CO ib id if :: Open I2C bus and device with flags :: i2cOpen +I2CC h :: Close I2C handle :: i2cClose + +I2CWQ h bit :: smb Write Quick: write bit :: i2cWriteQuick + +I2CRS h :: smb Read Byte: read byte :: i2cReadByte +I2CWS h bv :: smb Write Byte: write byte :: i2cWriteByte + +I2CRB h r :: smb Read Byte Data: read byte from register :: i2cReadByteData +I2CWB h r bv :: smb Write Byte Data: write byte to register :: i2cWriteByteData + +I2CRW h r :: smb Read Word Data: read word from register :: i2cReadWordData +I2CWW h r wv :: smb Write Word Data: write word to register :: i2cWriteWordData + +I2CRK h r :: smb Read Block Data: read data from register :: i2cReadBlockData +I2CWK h r bvs :: smb Write Block Data: write data to register :: i2cWriteBlockData + +I2CWI h r bvs :: smb Write I2C Block Data :: i2cWriteI2CBlockData +I2CRI h r num :: smb Read I2C Block Data: read bytes from register :: i2cReadI2CBlockData + +I2CRD h num :: i2c Read device :: i2cReadDevice +I2CWD h bvs :: i2c Write device :: i2cWriteDevice + +I2CPC h r wv :: smb Process Call: exchange register with word :: i2cProcessCall +I2CPK h r bvs :: smb Block Process Call: exchange data bytes with register :: i2cBlockProcessCall + +I2CZ h bvs :: Performs multiple I2C transactions :: i2cZip + +I2C BIT BANG + +BI2CO sda scl b :: Open bit bang I2C :: bbI2COpen +BI2CC sda :: Close bit bang I2C :: bbI2CClose + +BI2CZ sda bvs :: I2C bit bang multiple transactions :: bbI2CZip + +I2C/SPI SLAVE + +BSCX bctl bvs :: BSC I2C/SPI transfer :: bscXfer + +SERIAL + +SERO dev b sef :: Open serial device dev at baud b with flags :: serOpen +SERC h :: Close serial handle :: serClose + +SERRB :: Read byte from serial handle :: serReadByte +SERWB h bv :: Write byte to serial handle :: serWriteByte + +SERR h num :: Read bytes from serial handle :: serRead +SERW h bvs :: Write bytes to serial handle :: serWrite + +SERDA h :: Check for serial data ready to read :: serDataAvailable + +SERIAL BIT BANG (read only) + +SLRO u b db :: Open GPIO for bit bang serial data :: gpioSerialReadOpen +SLRC u :: Close GPIO for bit bang serial data :: gpioSerialReadClose + +SLRI u v :: Sets bit bang serial data logic levels :: gpioSerialReadInvert + +SLR u num :: Read bit bang serial data from GPIO :: gpioSerialRead + +SPI + +SPIO c b spf :: SPI open channel at baud b with flags :: spiOpen +SPIC h :: SPI close handle :: spiClose + +SPIR h num :: SPI read bytes from handle :: spiRead +SPIW h bvs :: SPI write bytes to handle :: spiWrite +SPIX h bvs :: SPI transfer bytes to handle :: spiXfer + +SPI BIT BANG + +BSPIO cs miso mosi sclk b spf :: Open bit bang SPI :: bbSPIOpen +BSPIC cs :: Close bit bang SPI :: bbSPIClose + +BSPIX cs bvs :: SPI bit bang transfer :: bbSPIXfer + +FILES + +FO file mode :: Open a file in mode :: fileOpen +FC h :: Close file handle :: fileClose + +FR h num :: Read bytes from file handle :: fileRead +FW h bvs :: Write bytes to file handle :: fileWrite + +FS h num from :: Seek to file handle position :: fileSeek + +FL pat num :: List files which match pattern :: fileList + +WAVES + +WVCLR :: Clear all waveforms :: gpioWaveClear + +WVNEW :: Initialise a new waveform :: gpioWaveAddNew +WVAG trips :: Add generic pulses to waveform :: gpioWaveAddGeneric +WVAS u b db sb o bvs :: Add serial data to waveform :: gpioWaveAddSerial + +WVCRE :: Create a waveform :: gpioWaveCreate +WVCAP percent :: Create a waveform of fixed size :: gpioWaveCreatePad +WVDEL wid :: Delete selected waveform :: gpioWaveDelete + +WVTX wid :: Transmits waveform once :: gpioWaveTxSend +WVTXM wid wmde :: Transmits waveform using mode :: gpioWaveTxSend +WVTXR wid :: Transmits waveform repeatedly :: gpioWaveTxSend + +WVCHA bvs :: Transmits a chain of waveforms :: gpioWaveChain + +WVTAT :: Returns the current transmitting waveform :: gpioWaveTxAt + +WVBSY :: Check if waveform is being transmitted :: gpioWaveTxBusy + +WVHLT :: Stop waveform :: gpioWaveTxStop + +WVSC ws :: Get waveform DMA CB stats :: gpioWaveGetCbs +WVSM ws :: Get waveform time stats :: gpioWaveGetMicros +WVSP ws :: Get waveform pulse stats :: gpioWaveGetPulses + +UTILITIES + +H/HELP :: Display command help :: +HWVER :: Get hardware version :: gpioHardwareRevision +MICS v :: Microseconds delay :: gpioDelay +MILS v :: Milliseconds delay :: gpioDelay +PIGPV :: Get pigpio library version :: gpioVersion +T/TICK :: Get current tick :: gpioTick + +CONFIGURATION + +CGI :: Configuration get internals :: gpioCfgGetInternals +CSI v :: Configuration set internals :: gpioCfgSetInternals + +COMMANDS + +BC1 :: +This command clears (sets low) the GPIO specified by [*bits*] in bank 1. +Bank 1 consists of GPIO 0-31. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs bc1 0x400010 # clear GPIO 4 (1<<4) and 22 (1<<22) + +$ pigs bc1 32 # clear GPIO 5 (1<<5) +-42 +ERROR: no permission to update one or more GPIO +... + +BC2 :: +This command clears (sets low) the GPIO specified by [*bits*] in bank 2. +Bank 2 consists of GPIO 32-53. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs bc2 0x8000 # clear GPIO 47 (activity LED on A+/B+/Pi2/Pi3) + +$ pigs bc2 1 # clear GPIO 32 (first in bank 2) +-42 +ERROR: no permission to update one or more GPIO +... + +BI2CC :: +This command signals that bit banging I2C on [*sda*] (and [*scl*]) is no +longer required. + +... +$ pigs bi2cc 5 +... + +BI2CO :: +This command signals that GPIO [*sda*] and [*scl*] are to be used +for bit banging I2C at [*b*] baud. + +Bit banging I2C allows for certain operations which are not possible +with the standard I2C driver. + +o baud rates as low as 50 +o repeated starts +o clock stretching +o I2C on any pair of spare GPIO + +The baud rate may be between 50 and 500000 bits per second. + +The GPIO used for SDA and SCL must have pull-ups to 3V3 connected. As +a guide the hardware pull-ups on pins 3 and 5 are 1k8 in value. + +BI2CZ :: +This function executes a sequence of bit banged I2C operations. The +operations to be performed are specified by the contents of [*bvs*] +which contains the concatenated command codes and associated data. + +The following command codes are supported: + +Name @ Cmd & Data @ Meaning +End @ 0 @ No more commands +Escape @ 1 @ Next P is two bytes +Start @ 2 @ Start condition +Stop @ 3 @ Stop condition +Address @ 4 P @ Set I2C address to P +Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8) +Read @ 6 P @ Read P bytes of data +Write @ 7 P ... @ Write P bytes of data + +The address, read, and write commands take a parameter P. +Normally P is one byte (0-255). If the command is preceded by +the Escape command then P is two bytes (0-65535, least significant +byte first). + +The address and flags default to 0. The address and flags maintain +their previous value until updated. + +No flags are currently defined. + +... +Set address 0x53 +start, write 0x32, (re)start, read 6 bytes, stop +Set address 0x1E +start, write 0x03, (re)start, read 6 bytes, stop +Set address 0x68 +start, write 0x1B, (re)start, read 8 bytes, stop +End + +0x04 0x53 +0x02 0x07 0x01 0x32 0x02 0x06 0x06 0x03 + +0x04 0x1E +0x02 0x07 0x01 0x03 0x02 0x06 0x06 0x03 + +0x04 0x68 +0x02 0x07 0x01 0x1B 0x02 0x06 0x08 0x03 + +0x00 +... + +BR1 :: +This command read GPIO 0-31 (bank 1) and returns the levels as a +32-bit hexadecimal value. + +... +$ pigs br1 +1001C1CF +... + +BR2 :: +This command read GPIO 32-53 (bank 2) and returns the levels as a +32-bit hexadecimal value. + +... +$ pigs br2 +003F0000 +... + +BS1 :: +This command sets (sets high) the GPIO specified by [*bits*] in bank 1. +Bank 1 consists of GPIO 0-31. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs bs1 16 # set GPIO 4 (1<<4) + +$ pigs bs1 1 # set GPIO 1 (1<<0) +-42 +ERROR: no permission to update one or more GPIO +... + +BS2 :: +This command sets (sets high) the GPIO specified by [*bits*] in bank 2. +Bank 2 consists of GPIO 32-53. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs bs2 0x40 # set GPIO 38 (enable high current mode A+/B+/Pi2/Pi3) + +$ pigs bs2 1 # set GPIO 32 (first in bank 2) +-42 +ERROR: no permission to update one or more GPIO +... + +BSCX :: + +This command performs a BSC I2C/SPI slave transfer as defined by +[*bctl*] with data [*bvs*]. + +This function provides a low-level interface to the SPI/I2C Slave +peripheral on the BCM chip. + +This peripheral allows the Pi to act as a hardware slave device +on an I2C or SPI bus. + +This is not a bit bang version and as such is OS timing +independent. The bus timing is handled directly by the chip. + +The output process is simple. You simply append data to the FIFO +buffer on the chip. This works like a queue, you add data to the +queue and the master removes it. + +The command sets the BSC mode and writes any data [*bvs*] +to the BSC transmit FIFO. It returns the data count (at least 1 +for the status word), the status word, followed by any data bytes +read from the BSC receive FIFO. + +Note that the control word sets the BSC mode. The BSC will stay in +that mode until a different control word is sent. + +For I2C use a control word of (I2C address << 16) + 0x305. + +E.g. to talk as I2C slave with address 0x13 use 0x130305. + +GPIO used for models other than those based on the BCM2711. + + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE +I2C @ 18 @ 19 @ - @ - @ - @ - +SPI @ - @ - @ 20 @ 19 @ 18 @ 21 + +GPIO used for models based on the BCM2711 (e.g. the Pi4B). + + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE +I2C @ 10 @ 11 @ - @ - @ - @ - +SPI @ - @ - @ 9 @ 11 @ 10 @ 8 + +When a zero control word is received the used GPIO will be reset +to INPUT mode. + +The control word consists of the following bits. + +. . +22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + a a a a a a a - - IT HC TF IR RE TE BK EC ES PL PH I2 SP EN +. . + +Bits 0-13 are copied unchanged to the BSC CR register. See +pages 163-165 of the Broadcom peripherals document for full +details. + +aaaaaaa @ defines the I2C slave address (only relevant in I2C mode) +IT @ invert transmit status flags +HC @ enable host control +TF @ enable test FIFO +IR @ invert receive status flags +RE @ enable receive +TE @ enable transmit +BK @ abort operation and clear FIFOs +EC @ send control register as first I2C byte +ES @ send status register as first I2C byte +PL @ set SPI polarity high +PH @ set SPI phase high +I2 @ enable I2C mode +SP @ enable SPI mode +EN @ enable BSC peripheral + +The returned status has the following format + +. . +20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + S S S S S R R R R R T T T T T RB TE RF TF RE TB +. . + +Bits 0-15 are copied unchanged from the BSC FR register. See +pages 165-166 of the Broadcom peripherals document for full +details. + +SSSSS @ number of bytes successfully copied to transmit FIFO +RRRRR @ number of bytes in receieve FIFO +TTTTT @ number of bytes in transmit FIFO +RB @ receive busy +TE @ transmit FIFO empty +RF @ receive FIFO full +TF @ transmit FIFO full +RE @ receive FIFO empty +TB @ transmit busy + +This example assumes that GPIO 2/3 are connected to GPIO 18/19 +(GPIO 10/11 on the BCM2711). + +... +$ pigs bscx 0x130305 # start BSC as I2C slave 0x13 +1 18 + +$ i2cdetect -y 1 + 0 1 2 3 4 5 6 7 8 9 a b c d e f +00: -- -- -- -- -- -- -- -- -- -- -- -- -- +10: -- -- -- 13 -- -- -- -- -- -- -- -- -- -- -- -- +20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +70: -- -- -- -- -- -- -- -- + +$ pigs i2co 1 0x13 0 # get handle for device 0x13 on bus 1 +0 + +$ pigs i2cwd 0 90 87 51 9 23 # write 5 bytes + +$ pigs bscx 0x130305 # check for data +6 18 90 87 51 9 23 + +$ pigs bscx 0x130305 11 13 15 17 # check for data and send 4 bytes +1 262338 + +$ pigs i2crd 0 4 # read 4 bytes +4 11 13 15 17 + +$ pigs i2cwd 0 90 87 51 9 23 # write 5 bytes +$ pigs bscx 0x130305 11 13 15 17 # check for data and send 4 bytes +6 262338 90 87 51 9 23 + +$ pigs i2crd 0 4 +4 11 13 15 17 + +$ pigs bscx 0x130305 22 33 44 55 66 +1 327938 +$ pigs i2crd 0 5 +5 22 33 44 55 66 +... + +The BSC slave in SPI mode deserializes data from the MOSI pin into its receiver/ +FIFO when the LSB of the first byte is a 0. No data is output on the MISO pin. +When the LSB of the first byte on MOSI is a 1, the transmitter/FIFO data is +serialized onto the MISO pin while all other data on the MOSI pin is ignored. + +The BK bit of the BSC control register is non-functional when in the SPI mode. +The transmitter along with its FIFO can be dequeued by successively disabling +and re-enabling the TE bit on the BSC control register while in SPI mode. + +This example demonstrates a SPI master talking to the BSC as SPI slave: +Requires SPI master SCLK / MOSI / MISO / CE GPIO are connected to +BSC peripheral GPIO 11 / 9 / 10 / 8 respectively, on a Pi4B (BCM2711). + +... +$ pigs bspio 15 26 13 14 10000 0 # open bit-bang spi master on random gpio + +$ pigs bscx 0x303 # start BSC as SPI slave, both rx and tx enabled +1 18 + +$ pigs bspix 15 0 0xd 0xe 0xa 0xd # write 0xdead to BSC +5 0 0 0 0 0 + +$ pigs bscx 0x303 0xb 0xe 0xe 0xf # place 0xbeef in BSC tx FIFO, read rx FIFO +5 262338 13 14 10 13 + +$ pigs bspix 15 1 0 0 0 0 # read four bytes from BSC +5 0 11 14 14 15 +... + +BSPIC :: + +This command stops bit banging SPI on a set of GPIO +opened with [*BSPIO*]. + +The set of GPIO is specifed by [*cs*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs bspic 10 + +$ pigs bspic 10 +-142 +ERROR: no bit bang SPI in progress on GPIO +... + +BSPIO :: + +This command starts bit banging SPI on a group of GPIO with slave +select [*cs*], MISO [*miso*], MOSI [*mosi*], and clock [*sclk*]. + +Data will be transferred at baud [*b*] bits per second (which may +be set in the range 50-250000). + +The flags [*spf*] may be used to modify the default behaviour of +mode 0, active low chip select. + +The flags consists of the least significant 22 bits. + +. . +21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + 0 0 0 0 0 0 R T 0 0 0 0 0 0 0 0 0 0 0 p m m +. . + +mm defines the SPI mode. + +. . +Mode POL PHA + 0 0 0 + 1 0 1 + 2 1 0 + 3 1 1 +. . + +p is 0 if CS is active low (default) and 1 for active high. + +T is 1 if the least significant bit is transmitted on MOSI first, the +default (0) shifts the most significant bit out first. + +R is 1 if the least significant bit is received on MISO first, the +default (0) receives the most significant bit first. + +The other bits in flags should be set to zero. + +Upon success 0 is returned. On error a negative status code +will be returned. + +If more than one device is connected to the SPI bus (defined by +SCLK, MOSI, and MISO) each must have its own CS. + +... +$ pigs bspio 9 11 12 13 50000 0 + +$ pigs bspio 10 11 12 13 50000 0 + +$ pigs bspio 29 19 20 21 50000 0 # GPIO 29 not avaialble on this Pi +-41 +ERROR: no permission to update GPIO +... + +BSPIX:: + +This command writes bytes [*bvs*] to the bit bang SPI device +associated with slave select [*cs*]. It returns the same +number of bytes read from the device. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +... +$ pigs bspio 5 13 19 12 10000 0 # MCP4251 DAC +$ pigs bspio 6 13 19 12 20000 3 # MCP3008 ADC + +$ pigs bspix 5 0 16 # set DAC to 16 +2 255 255 + +$ pigs bspix 5 12 0 # read back DAC +2 254 16 + +$ pigs bspix 6 1 128 0 # read ADC input 0 +3 0 3 184 # 952 + +$ pigs bspix 5 0 240 # set DAC to 240 +2 255 255 + +$ pigs bspix 5 12 0 # read back DAC +2 254 240 + +$ pigs bspix 6 1 128 0 # read ADC input 0 +3 0 0 63 # 63 + +$ pigs bspix 5 0 128 # set DAC to 128 +2 255 255 + +$ pigs bspix 5 12 0 # read back DAC +2 254 128 + +$ pigs bspix 6 1 128 0 # read ADC input 0 +3 0 1 255 # 511 + +$ pigs bspic 5 # close SPI CS 5 +$ pigs bspic 6 # close SPI CS 6 + +$ pigs bspic 5 # try to close SPI CS 5 again +-142 +ERROR: no bit bang SPI in progress on GPIO +... + + +CF1:: + +This command calls a user customised function. The meaning of +any paramaters and the returned value is defined by the +customiser. + +CF2:: + +This command calls a user customised function. The meaning of +any paramaters and the returned value is defined by the +customiser. + +CGI:: +This command returns the value of the internal library +configuration settings. + +CSI:: +This command sets the value of the internal library +configuration settings to [*v*]. + +EVM :: +This command starts event reporting on handle [*h*] (returned by +a prior call to [*NO*]). + +Upon success nothing is returned. On error a negative status code +will be returned. + +The notification gets reports for each event specified by [*bits*]. + +... +$ pigs evm 0 -1 # Shorthand for events 0-31. +$ pigs evm 0 0xf0 # Get notifications for events 4-7. + +$ pigs evm 1 0xf +-25 +ERROR: unknown handle +... + +EVT :: +This command triggers event [*event*]. + +One event, number 31, is predefined. This event is +auto generated on BSC slave activity. + +... +$ pigs evt 12 +$ pigs evt 5 + +$ pigs evt 32 +-143 +ERROR: bad event id +... + +FC:: +This command closes a file handle [*h*] previously opened with [*FO*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs fc 0 # First close okay. + +$ pigs fc 0 # Second fails. +-25 +ERROR: unknown handle +... + +FG :: + +Level changes on the GPIO [*u*] are not reported unless the level +has been stable for at least [*stdy*] microseconds. The +level is then reported. Level changes of less than [*stdy*] +microseconds are ignored. + +The filter only affects callbacks (including pipe notifications). + +The [*R/READ*], [*BR1*], and [*BR2*] commands are not affected. + +Note, each (stable) edge will be timestamped [*stdy*] microseconds +after it was first detected. + +... +$ pigs fg 4 250 + +$ pigs fg 4 1000000 +-125 +ERROR: bad filter parameter +... + +FL :: +This command returns a list of the files matching [*pat*]. Up +to [*num*] bytes may be returned. + +Upon success the count of returned bytes followed by the matching +files is returned. On error a negative status code will be returned. + +A newline (0x0a) character separates each file name. + +Only files which have a matching entry in /opt/pigpio/access may +be listed. + +Suppose /opt/pigpio/access contains + +/sys/bus/w1/devices/28*/w1_slave r + +... +$ pigs -a fl "/sys/bus/w1/devices/28*/w1_slave" 5000 +90 /sys/bus/w1/devices/28-000005d34cd2/w1_slave +/sys/bus/w1/devices/28-001414abbeff/w1_slave + +$ pigs -a fl "/sys/bus/*" 5000 +ERROR: no permission to access file +-137 +... + +FN :: + +Level changes on the GPIO [*u*] are ignored until a level which has +been stable for [*stdy*] microseconds is detected. Level +changes on the GPIO are then reported for [*actv*] microseconds +after which the process repeats. + +The filter only affects callbacks (including pipe notifications). + +The [*R/READ*], [*BR1*], and [*BR2*] commands are not affected. + +Note, level changes before and after the active period may +be reported. Your software must be designed to cope with +such reports. + +... +$ pigs fn 7 250 1000 + +$ pigs fn 7 2500000 1000 +-125 +ERROR: bad filter parameter +... + +FO :: +This function returns a handle to a file [*file*] opened +in a specified mode [*mode*]. + +Upon success a handle (>=0) is returned. On error a negative status code +will be returned. + +File + +A file may only be opened if permission is granted by an entry in +/opt/pigpio/access. This is intended to allow remote access to files +in a more or less controlled manner. + +Each entry in /opt/pigpio/access takes the form of a file path +which may contain wildcards followed by a single letter permission. +The permission may be R for read, W for write, U for read/write, +and N for no access. + +Where more than one entry matches a file the most specific rule +applies. If no entry matches a file then access is denied. + +Suppose /opt/pigpio/access contains the following entries + +. . +/home/* n +/home/pi/shared/dir_1/* w +/home/pi/shared/dir_2/* r +/home/pi/shared/dir_3/* u +/home/pi/shared/dir_1/file.txt n +. . + +Files may be written in directory dir_1 with the exception +of file.txt. + +Files may be read in directory dir_2. + +Files may be read and written in directory dir_3. + +If a directory allows read, write, or read/write access then files may +be created in that directory. + +In an attempt to prevent risky permissions the following paths are +ignored in /opt/pigpio/access. + +. . +a path containing .. +a path containing only wildcards (*?) +a path containing less than two non-wildcard parts +. . + +Mode + +The mode may have the following values. + + @ Value @ Meaning +READ @ 1 @ open file for reading +WRITE @ 2 @ open file for writing +RW @ 3 @ open file for reading and writing + +The following values may be or'd into the mode. + + @ Value @ Meaning +APPEND @ 4 @ All writes append data to the end of the file +CREATE @ 8 @ The file is created if it doesn't exist +TRUNC @ 16 @ The file is truncated + +Newly created files are owned by root with permissions owner read and write. + +... +$ ls /ram/*.c +/ram/command.c /ram/pigpiod.c /ram/pigs.c +/ram/x_pigpiod_if.c /ram/pig2vcd.c /ram/pigpiod_if2.c +/ram/x_pigpio.c /ram/x_repeat.c /ram/pigpio.c +/ram/pigpiod_if.c /ram/x_pigpiod_if2.c + +# assumes /opt/pigpio/access contains the following line +# /ram/*.c r + +$ pigs fo /ram/pigpio.c 1 +0 + +$ pigs fo /ram/new.c 1 +-128 +ERROR: file open failed + +$ pigs fo /ram/new.c 9 +1 + +$ ls /ram/*.c -l +-rw-r--r-- 1 joan joan 42923 Jul 10 11:22 /ram/command.c +-rw------- 1 root root 0 Jul 10 16:54 /ram/new.c +-rw-r--r-- 1 joan joan 2971 Jul 10 11:22 /ram/pig2vcd.c +-rw------- 1 joan joan 296235 Jul 10 11:22 /ram/pigpio.c +-rw-r--r-- 1 joan joan 9266 Jul 10 11:22 /ram/pigpiod.c +-rw-r--r-- 1 joan joan 37331 Jul 10 11:22 /ram/pigpiod_if2.c +-rw-r--r-- 1 joan joan 33088 Jul 10 11:22 /ram/pigpiod_if.c +-rw-r--r-- 1 joan joan 7990 Jul 10 11:22 /ram/pigs.c +-rw-r--r-- 1 joan joan 19970 Jul 10 11:22 /ram/x_pigpio.c +-rw-r--r-- 1 joan joan 20804 Jul 10 11:22 /ram/x_pigpiod_if2.c +-rw-r--r-- 1 joan joan 19844 Jul 10 11:22 /ram/x_pigpiod_if.c +-rw-r--r-- 1 joan joan 19907 Jul 10 11:22 /ram/x_repeat.c +... + +FR:: +This command returns up to [*num*] bytes of data read from the +file associated with handle [*h*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +... +$ pigs fr 0 10 +5 48 49 128 144 255 + +$ pigs fr 0 10 +0 +... + +FS :: +This command seeks to a position within the file associated +with handle [*h*]. + +The number of bytes to move is [*num*]. Positive offsets +move forward, negative offsets backwards. The move start +position is determined by [*from*] as follows. + + @ From +0 @ start +1 @ current position +2 @ end + +Upon success the new byte position within the file (>=0) is +returned. On error a negative status code will be returned. + +... +$ pigs fs 0 200 0 # Seek to start of file plus 200 +200 + +$ pigs fs 0 0 1 # Return current position +200 + +$ pigs fs 0 0 2 # Seek to end of file, return size +296235 +... + +FW:: +This command writes bytes [*bvs*] to the file +associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs fw 0 23 45 67 89 +... + +GDC :: + +This command returns the PWM dutycycle in use on GPIO [*u*]. + +Upon success the dutycycle is returned. On error a negative +status code will be returned. + +For normal PWM the dutycycle will be out of the defined range +for the GPIO (see [*PRG*]). + +If a hardware clock is active on the GPIO the reported +dutycycle will be 500000 (500k) out of 1000000 (1M). + +If hardware PWM is active on the GPIO the reported dutycycle +will be out of a 1000000 (1M). + +... +$ pigs p 4 129 +$ pigs gdc 4 +129 + +pigs gdc 5 +-92 +ERROR: GPIO is not in use for PWM +... + +GPW :: + +This command returns the servo pulsewidth in use on GPIO [*u*]. + +Upon success the servo pulsewidth is returned. On error a negative +status code will be returned. + +... +$ pigs s 4 1235 +$ pigs gpw 4 +1235 + +$ pigs gpw 9 +-93 +ERROR: GPIO is not in use for servo pulses +... + +H/HELP :: +This command displays a brief list of the commands and their parameters. + +... +$ pigs h + +$ pigs help +... + +HC :: +This command sets the hardware clock associated with GPIO [*g*] to +frequency [*cf*]. Frequencies above 30MHz are unlikely to work. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs hc 4 5000 # start a 5 KHz clock on GPIO 4 (clock 0) + +$ pigs hc 5 5000000 # start a 5 MHz clcok on GPIO 5 (clock 1) +-99 +ERROR: need password to use hardware clock 1 +... + +The same clock is available on multiple GPIO. The latest +frequency setting will be used by all GPIO which share a clock. + +The GPIO must be one of the following. + +4 @clock 0 @All models +5 @clock 1 @All models but A and B (reserved for system use) +6 @clock 2 @All models but A and B +20 @clock 0 @All models but A and B +21 @clock 1 @All models but A and B Rev.2 (reserved for system use) + +32 @clock 0 @Compute module only +34 @clock 0 @Compute module only +42 @clock 1 @Compute module only (reserved for system use) +43 @clock 2 @Compute module only +44 @clock 1 @Compute module only (reserved for system use) + +Access to clock 1 is protected by a password as its use will +likely crash the Pi. The password is given by or'ing 0x5A000000 +with the GPIO number. + +HP :: +This command sets the hardware PWM associated with GPIO [*g*] to +frequency [*pf*] with dutycycle [*pdc*]. Frequencies above 30MHz +are unlikely to work. + +NOTE: Any waveform started by [*WVTX*], [*WVTXR*], or [*WVCHA*] +will be cancelled. + +This function is only valid if the pigpio main clock is PCM. The +main clock defaults to PCM but may be overridden when the pigpio +daemon is started (option -t). + +Upon success nothing is returned. On error a negative status code +will be returned. + +. . +$ pigs hp 18 100 800000 # 80% dutycycle + +$ pigs hp 19 100 200000 # 20% dutycycle + +$ pigs hp 19 400000000 100000 +-96 +ERROR: invalid hardware PWM frequency +. . + +The same PWM channel is available on multiple GPIO. The latest +frequency and dutycycle setting will be used by all GPIO which +share a PWM channel. + +The GPIO must be one of the following. + +12 @PWM channel 0 @All models but A and B +13 @PWM channel 1 @All models but A and B +18 @PWM channel 0 @All models +19 @PWM channel 1 @All models but A and B + +40 @PWM channel 0 @Compute module only +41 @PWM channel 1 @Compute module only +45 @PWM channel 1 @Compute module only +52 @PWM channel 0 @Compute module only +53 @PWM channel 1 @Compute module only + +The actual number of steps beween off and fully on is the +integral part of 250M/[*pf*] (375M/[*pf*] for the BCM2711). + +The actual frequency set is 250M/steps (375M/steps for the BCM2711). + +There will only be a million steps for a [*pf*] of 250 (375 for +the BCM2711). Lower frequencies will have more steps and higher +frequencies will have fewer steps. [*pdc*] is +automatically scaled to take this into account. + +HWVER :: +This command returns the hardware revision of the Pi. + +The hardware revision is found in the last 4 characters on the revision +line of /proc/cpuinfo. + +If the hardware revision can not be found or is not a valid hexadecimal +number the command returns 0. + +The revision number can be used to determine the assignment of GPIO +to pins (see [*g*]). + +There are currently three types of board. + +Type 1 boards have hardware revision numbers of 2 and 3. + +Type 2 boards have hardware revision numbers of 4, 5, 6, and 15. + +Type 3 boards have hardware revision numbers of 16 or greater. + +for "Revision : 0002" the command returns 2. + +for "Revision : 000f" the command returns 15. + +for "Revision : 000g" the command returns 0. + +... +$ pigs hwver # On a B+ +16 +... + +I2CC :: +This command closes an I2C handle [*h*] previously opened with [*I2CO*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs i2cc 0 # First close okay. + +$ pigs i2cc 0 # Second fails. +-25 +ERROR: unknown handle +... + +I2CO :: +This command returns a handle to access device [*id*] on I2C bus [*ib*]. +The device is opened with flags [*if*]. + +Physically buses 0 and 1 are available on the Pi. Higher +numbered buses will be available if a kernel supported bus +multiplexor is being used. + +The GPIO used are given in the following table. + + @ SDA @ SCL +I2C 0 @ 0 @ 1 +I2C 1 @ 2 @ 3 + +No flags are currently defined. The parameter [*if*] should be 0. + +Upon success the next free handle (>=0) is returned. On error a +negative status code will be returned. + +... +$ pigs i2co 1 0x70 0 # Bus 1, device 0x70, flags 0. +0 + +$ pigs i2co 1 0x53 0 # Bus 1, device 0x53, flags 0. +1 +... + +I2CPC :: +This command writes [*wv*] to register [*r*] of the I2C device +associated with handle [*h*] and returns a 16-bit word read from the +device. + +Upon success a value between 0 and 65535 will be returned. On error +a negative status code will be returned. + +... +$ pigs i2cpc 0 37 43210 +39933 + +$ pigs i2cpc 0 256 43210 +ERROR: bad i2c/spi/ser parameter +-81 +... + +I2CPK :: + +This command writes the data bytes [*bvs*] to register [*r*] of the I2C device +associated with handle [*h*] and returns a device specific number of bytes. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +... +$ pigs i2cpk 0 0 0x11 0x12 +6 0 0 0 0 0 0 +... + +I2CRB :: + +This command returns a single byte read from register [*r*] of the I2C device +associated with handle [*h*]. + +Upon success a value between 0 and 255 will be returned. On error +a negative status code will be returned. + +... +$ pigs i2crb 0 0 +6 +... + +I2CRD :: + +This command returns [*num*] bytes read from the I2C device associated with +handle [*h*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +This command operates on the raw I2C device. The maximum value of the +parameter [*num*] is dependent on the I2C drivers and the device +itself. pigs imposes a limit of about 8000 bytes. + +... +$ pigs i2crd 0 16 +16 6 24 0 0 0 0 0 0 0 0 0 0 0 0 32 78 +... + +I2CRI :: + +This command returns [*num*] bytes from register [*r*] of the I2C device +associated with handle [*h*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +The parameter [*num*] may be 1-32. + +... +$ pigs i2cri 0 0 16 +16 237 155 155 155 155 155 155 155 155 155 155 155 155 155 155 155 +... + +I2CRK :: + +This command returns between 1 and 32 bytes read from register [*r*] of +the I2C device associated with handle [*h*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +The number of bytes of returned data is specific to the device and +register. + +... +$ pigs i2crk 0 0 +6 0 0 0 0 0 0 + +$ pigs i2crk 0 1 +24 0 0 0 0 0 0 0 0 0 0 0 0 120 222 105 215 128 87 195 217 0 0 0 0 +... + +I2CRS :: + +This command returns a single byte read from the I2C device +associated with handle [*h*]. + +Upon success a value between 0 and 255 will be returned. On error +a negative status code will be returned. + +... +$ pigs i2crs 0 +0 +... + +I2CRW :: + +This command returns a single 16 bit word read from register [*r*] of +the I2C device associated with handle [*h*]. + +Upon success a value between 0 and 65535 will be returned. On error +a negative status code will be returned. + +... +$ pigs i2crw 0 0 +6150 +... + +I2CWB :: + +This command writes a single byte [*bv*] to register [*r*] of the +I2C device associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs i2cwb 0 10 0x54 +... + +I2CWD :: + +This command writes a block of bytes [*bvs*] to the I2C device +associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The number of bytes which may be written in one transaction is +dependent on the I2C drivers and the device itself. pigs imposes +a limit of about 500 bytes. + +This command operates on the raw I2C device. + +... +$ pigs i2cwd 0 0x01 0x02 0x03 0x04 +... + +I2CWI :: + +This command writes between 1 and 32 bytes [*bvs*] to register [*r*] of +the I2C device associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs i2cwi 0 4 0x01 0x04 0xc0 +... + +I2CWK :: + +This command writes between 1 and 32 bytes [*bvs*] to register [*r*] of +the I2C device associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +pigs i2cwk 0 4 0x01 0x04 0xc0 +... + +I2CWQ :: + +This command writes a single [*bit*] to the I2C device associated +with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs i2cwq 0 1 +... + +I2CWS :: + +This command writes a single byte [*bv*] to the I2C device associated +with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs i2cws 0 0x12 + +$ pigs i2cws 0 0xff +-82 +ERROR: I2C write failed +... + +I2CWW :: + +This command writes a single 16 bit word [*wv*] to register [*r*] of +the I2C device associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs i2cww 0 0 0xffff +... + +I2CZ :: +This command executes a sequence of I2C operations. The +operations to be performed are specified by the contents of [*bvs*] +which contains the concatenated command codes and associated data. + +The following command codes are supported: + +Name @ Cmd & Data @ Meaning +End @ 0 @ No more commands +Escape @ 1 @ Next P is two bytes +On @ 2 @ Switch combined flag on +Off @ 3 @ Switch combined flag off +Address @ 4 P @ Set I2C address to P +Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8) +Read @ 6 P @ Read P bytes of data +Write @ 7 P ... @ Write P bytes of data + +The address, read, and write commands take a parameter P. +Normally P is one byte (0-255). If the command is preceded by +the Escape command then P is two bytes (0-65535, least significant +byte first). + +The address defaults to that associated with the handle [*h*]. +The flags default to 0. The address and flags maintain their +previous value until updated. + +... +Set address 0x53, write 0x32, read 6 bytes +Set address 0x1E, write 0x03, read 6 bytes +Set address 0x68, write 0x1B, read 8 bytes +End + +0x04 0x53 0x07 0x01 0x32 0x06 0x06 +0x04 0x1E 0x07 0x01 0x03 0x06 0x06 +0x04 0x68 0x07 0x01 0x1B 0x06 0x08 +0x00 +... + + +M/MODES :: + +This command sets GPIO [*g*] to mode [*m*], typically input (read) +or output (write). + +Upon success nothing is returned. On error a negative status code +will be returned. + +Each GPIO can be configured to be in one of 8 different modes. The modes +are named Input, Output, ALT0, ALT1, ALT2, ALT3, ALT4, and ALT5. + +To set the mode use the code for the mode. + +Mode @Input@Output@ALT0@ALT1@ALT2@ALT3@ALT4@ALT5 +Code @ R@ W@ 0@ 1@ 2@ 3@ 4@ 5 + +... +$ pigs m 4 r # Input (read) +$ pigs m 4 w # Output (write) +$ pigs m 4 0 # ALT 0 +$ pigs m 4 5 # ALT 5 +... + +MG/MODEG :: + +This command returns the current mode of GPIO [*g*]. + +Upon success the value of the GPIO mode is returned. +On error a negative status code will be returned. + +Value @ 0@ 1@ 2@ 3@ 4@ 5@ 6@ 7 +Mode @Input@Output@ALT5@ALT4@ALT0@ALT1@ALT2@ALT3 + +... +$ pigs mg 4 +1 +... + +MICS :: +This command delays execution for [*v*] microseconds. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The main use of this command is expected to be within [*Scripts*]. + +... +$ pigs mics 20 # Delay 20 microseconds. +$ pigs mics 1000000 # Delay 1 second. + +$ pigs mics 2000000 +-64 +ERROR: bad MICS delay (too large) +... + +MILS :: + +This command delays execution for [*v*] milliseconds. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs mils 2000 # Delay 2 seconds. + +$ pigs mils 61000 +-65 +ERROR: bad MILS delay (too large) +... + +NB :: + +This command starts notifications on handle [*h*] returned by +a prior call to [*NO*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The notification gets state changes for each GPIO specified by [*bits*]. + +... +$ pigs nb 0 -1 # Shorthand for GPIO 0-31. +$ pigs nb 0 0xf0 # Get notifications for GPIO 4-7. + +$ pigs nb 1 0xf +-25 +ERROR: unknown handle +... + +NC :: + +This command stops notifications on handle [*h*] returned by +a prior call to [*NO*] and releases the handle for reuse. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs nc 0 # First call succeeds. + +$ pigs nc 1 # Second call fails. +-25 +ERROR: unknown handle +... + +NO :: + +This command requests a free notification handle. + +A notification is a method for being notified of GPIO state changes via a pipe. + +Upon success the command returns a handle greater than or equal to zero. +On error a negative status code will be returned. + +Notifications for handle x will be available at the pipe named /dev/pigpiox +(where x is the handle number). + +E.g. if the command returns 15 then the notifications must be read +from /dev/pigpio15. + +... +$ pigs no +0 +... + +NP :: + +This command pauses notifications on handle [*h*] returned by +a prior call to [*NO*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +Notifications for the handle are suspended until a new [*NB*] command +is given for the handle. + +... +$ pigs np 0 +... + +P/PWM :: + +This command starts PWM on GPIO [*u*] with dutycycle [*v*]. The dutycycle +varies from 0 (off) to range (fully on). The range defaults to 255. + +Upon success nothing is returned. On error a negative status code +will be returned. + +This and the servo functionality use the DMA and PWM or PCM peripherals +to control and schedule the pulsewidths and dutycycles. + +The [*PRS*] command may be used to change the default range of 255. + +... +$ pigs p 4 64 # Start PWM on GPIO 4 with 25% dutycycle +$ pigs p 4 128 # 50% +$ pigs p 4 192 # 75% +$ pigs p 4 255 # 100% +... + +PADG :: + +This command gets the [*pad*] drive strength [*padma*] in mA. + +Returns the pad drive strength if OK. On error a negative status code +will be returned. + +Pad @ GPIO +0 @ 0-27 +1 @ 28-45 +2 @ 46-53 + +... +$ pigs padg 0 +8 +$ pigs pads 0 16 +$ pigs padg 0 +16 +pigs padg 3 +-126 +ERROR: bad pad number +... + +PADS:: + +This command sets the [*pad*] drive strength [*padma*] in mA. + +Upon success nothing is returned. On error a negative status code +will be returned. + +Pad @ GPIO +0 @ 0-27 +1 @ 28-45 +2 @ 46-53 + +... +$ pigs pads 0 16 +$ pigs padg 0 +16 +$ pigs pads 0 17 +-127 +ERROR: bad pad drive strength +... + +PARSE :: + +Validates the text [*t*] of a script without storing the script. + +Upon success nothing is returned. On error a list of detected +script errors will be given. + +See [*Scripts*]. + +This command may be used to find script syntax faults. + +... +$ pigs parse tag 100 w 22 1 mils 200 w 22 0 mils 800 jmp 100 + +$ pigs parse tag 0 w 22 1 mills 50 w 22 0 dcr p10 jp 99 +Unknown command: mills +Unknown command: 50 +Bad parameter to dcr +Can't resolve tag 99 +... + +PFG :: + +This command returns the PWM frequency in Hz used for GPIO [*u*]. + +Upon success the PWM frequency is returned. On error a negative +status code will be returned. + +For normal PWM the frequency will be that defined for the GPIO +by [*PFS*]. + +If a hardware clock is active on the GPIO the reported frequency +will be that set by [*HC*]. + +If hardware PWM is active on the GPIO the reported frequency +will be that set by [*HP*]. + +... +$ pigs pfg 4 +800 + +$ pigs pfg 34 +ERROR: GPIO not 0-31 +-2 +... + +PFS :: +This command sets the PWM frequency [*v*] to be used for GPIO [*u*]. + +The numerically closest frequency to [*v*] will be selected. + +Upon success the new frequency is returned. On error a negative status code +will be returned. + +If PWM is currently active on the GPIO it will be +switched off and then back on at the new frequency. + +Each GPIO can be independently set to one of 18 different PWM +frequencies. + +The selectable frequencies depend upon the sample rate which +may be 1, 2, 4, 5, 8, or 10 microseconds (default 5). The +sample rate is set when the pigpio daemon is started. + +The frequencies for each sample rate are: + +. . + Hertz + + 1: 40000 20000 10000 8000 5000 4000 2500 2000 1600 + 1250 1000 800 500 400 250 200 100 50 + + 2: 20000 10000 5000 4000 2500 2000 1250 1000 800 + 625 500 400 250 200 125 100 50 25 + + 4: 10000 5000 2500 2000 1250 1000 625 500 400 + 313 250 200 125 100 63 50 25 13 +sample + rate + (us) 5: 8000 4000 2000 1600 1000 800 500 400 320 + 250 200 160 100 80 50 40 20 10 + + 8: 5000 2500 1250 1000 625 500 313 250 200 + 156 125 100 63 50 31 25 13 6 + + 10: 4000 2000 1000 800 500 400 250 200 160 + 125 100 80 50 40 25 20 10 5 +. . + +... +pigs pfs 4 0 # 0 selects the lowest frequency. +10 + +$ pigs pfs 4 1000 # Set 1000Hz PWM. +1000 + +$ pigs pfs 4 100000 # Very big number selects the highest frequency. +8000 +... + +PIGPV :: + +This command returns the pigpio library version. + +... +$ pigs pigpv +17 +... + +PRG :: + +This command returns the dutycycle range for GPIO [*u*]. + +Upon success the range is returned. On error a negative status code +will be returned. + +If a hardware clock or hardware PWM is active on the GPIO the reported +range will be 1000000 (1M). + +... +$ pigs prg 4 +255 +... + +PROC :: + +This command stores a script [*t*] for later execution. + +If the script is valid a script id (>=0) is returned which is passed +to the other script commands. On error a negative status code +will be returned. + +See [*Scripts*]. + +... +$ pigs proc tag 123 w 4 0 mils 200 w 4 1 mils 300 dcr p0 jp 123 +0 + +$ pigs proc tag 123 w 4 0 mils 5 w 4 1 mils 5 jmp 12 +ERROR: script has unresolved tag +-63 +... + +PROCD :: + +This command deletes script [*sid*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +See [*Scripts*]. + +... +$ pigs procd 1 + +$ pigs procd 1 +ERROR: unknown script id +-48 +... + +PROCP :: + +This command returns the status of script [*sid*] as well as the +current value of its 10 parameters. + +Upon success the script status and parameters are returned. +On error a negative status code will be returned. + +The script status may be one of + +0 @ being initialised +1 @ halted +2 @ running +3 @ waiting +4 @ failed + +See [*Scripts*]. + +... +$ pigs procp 0 +1 0 0 0 0 0 0 0 0 0 0 +... + +PROCR :: + +This command runs stored script [*sid*] passing it up to 10 optional +parameters. + +Upon success nothing is returned. On error a negative status code +will be returned. + +See [*Scripts*]. + +... +$ pigs proc tag 123 w 4 0 mils 200 w 4 1 mils 300 dcr p0 jp 123 +0 + +$ pigs procr 0 50 # Run script 0 with parameter 0 of 50. + +$ pigs procp 0 +2 44 0 0 0 0 0 0 0 0 0 +$ pigs procp 0 +2 37 0 0 0 0 0 0 0 0 0 +$ pigs procp 0 +2 10 0 0 0 0 0 0 0 0 0 +$ pigs procp 0 +2 5 0 0 0 0 0 0 0 0 0 +$ pigs procp 0 +2 2 0 0 0 0 0 0 0 0 0 +$ pigs procp 0 +1 -1 0 0 0 0 0 0 0 0 0 +... + +PROCS :: + +This command stops a running script [*sid*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +See [*Scripts*]. + +... +$ pigs procs 0 + +$ pigs procs 1 +-48 +ERROR: unknown script id +... + +PROCU :: + +This command sets the parameters of a stored script [*sid*] passing +it up to 10 parameters. + +Upon success nothing is returned. On error a negative status code +will be returned. + +See [*Scripts*]. + +... +$ pigs proc tag 0 hp 18 p0 p1 mils 1000 jmp 0 +0 +$ pigs procu 0 50 500000 +$ pigs procr 0 +$ pigs procu 0 100 +$ pigs procu 0 200 +$ pigs procu 0 200 100000 +... + +PRRG :: + +This command returns the real underlying range used by GPIO [*u*]. + +If a hardware clock is active on the GPIO the reported +real range will be 1000000 (1M). + +If hardware PWM is active on the GPIO the reported real range +will be approximately 250M divided by the set PWM frequency. + +On error a negative status code will be returned. + +See [*PRS*]. + +... +$ pigs prrg 17 +250 + +$ pigs pfs 17 0 +10 +$ pigs prrg 17 +20000 + +$ pigs pfs 17 100000 +8000 +$ pigs prrg 17 +25 +... + +PRS :: + +This command sets the dutycycle range [*v*] to be used for GPIO [*u*]. +Subsequent uses of command [*P/PWM*] will use a dutycycle between 0 (off) +and [*v*] (fully on). + +Upon success the real underlying range used by the GPIO is returned. +On error a negative status code will be returned. + +If PWM is currently active on the GPIO its dutycycle will be scaled to +reflect the new range. + +The real range, the number of steps between fully off and fully on +for each frequency, is given in the following table. + + #1@ #2@ #3@ #4@ #5@ #6@ #7@ #8@ #9 + 25@ 50@ 100@ 125@ 200@ 250@ 400@ 500@ 625 + @ @ @ @ @ @ @ @ +#10@ #11@ #12@ #13@ #14@ #15@ #16@ #17@ #18 +800@1000@1250@2000@2500@4000@5000@10000@20000 + +The real value set by [*PRS*] is (dutycycle * real range) / range. + +See [*PRRG*] + +... +$ pigs prs 18 1000 +250 +... + +PUD :: + +This command sets the internal pull/up down for GPIO [*g*] to mode [*p*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The mode may be pull-down (D), pull-up (U), or off (O). + +... +$ pigs pud 4 d # Set pull-down on GPIO 4. +$ pigs pud 4 u # Set pull-up on GPIO 4. +$ pigs pud 4 o # No pull-up/down on GPIO 4. +... + +R/READ :: + +This reads the current level of GPIO [*g*]. + +Upon success the current level is returned. On error a negative status code +will be returned. + +... +$ pigs r 17 # Get level of GPIO 17. +0 + +$ pigs r 4 # Get level of GPIO 4. +1 +... + +S/SERVO :: + +This command starts servo pulses of [*v*] microseconds on GPIO [*u*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The servo pulsewidth may be 0 (off), 500 (most anti-clockwise) +to 2500 (most clockwise). + +The range supported by servos varies and should probably be determined +by experiment. Generally values between 1000-2000 should be safe. +A value of 1500 should always be safe and represents +the mid-point of rotation. + +You can DAMAGE a servo if you command it to move beyond its limits. + +... +$ pigs SERVO 17 1500 +... + +This example causes an on pulse of 1500 microseconds duration to be +transmitted on GPIO 17 at a rate of 50 times per second. + +This will command a servo connected to GPIO 17 to rotate to its mid-point. + +... +pigs s 17 0 # Switch servo pulses off. +... + +SERC :: + +This command closes a serial handle [*h*] previously opened with [*SERO*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs serc 0 # First close okay. + +$ pigs serc 0 # Second close gives error. +-25 +ERROR: unknown handle +... + +SERDA :: + +This command returns the number of bytes of data available +to be read from the serial device associated with handle [*h*]. + +Upon success the count of bytes available to be read is +returned (which may be 0). On error a negative status code +will be returned. + +... +$ pigs serda 0 +0 +... + +SERO:: + +This command opens the serial [*dev*] at [*b*] bits per second. + +No flags are currently defined. [*sef*] should be set to zero. + +Upon success a handle (>=0) is returned. On error a negative status code +will be returned. + +The device name must start with /dev/tty or /dev/serial. + + +The baud rate must be one of 50, 75, 110, 134, 150, +200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, +38400, 57600, 115200, or 230400. + +... +$ pigs sero /dev/ttyAMA0 9600 0 +0 + +$ pigs sero /dev/tty1 38400 0 +1 +... + +SERR:: + +This command returns up to [*num*] bytes of data read from the +serial device associated with handle [*h*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +... +$ pigs serr 0 10 +5 48 49 128 144 255 + +$ pigs serr 0 10 +0 +... + +SERRB:: + +This command returns a byte of data read from the serial +device associated with handle [*h*]. + +Upon success a number between 0 and 255 is returned. +On error a negative status code will be returned. + +... +$ pigs serrb 0 +23 +$ pigs serrb 0 +45 +... + +SERW:: + +This command writes bytes [*bvs*] to the serial device +associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs serw 0 23 45 67 89 +... + +SERWB:: + +This command writes a single byte [*bv*] to the serial device +associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs serwb 0 23 +$ pigs serwb 0 0xf0 +... + +SHELL :: + +This command uses the system call to execute a shell script [*name*] +with the given string [*str*] as its parameter. + +The exit status of the system call is returned if OK, otherwise +PI_BAD_SHELL_STATUS. + +[*name*] must exist in /opt/pigpio/cgi and must be executable. + +The returned exit status is normally 256 times that set +by the shell script exit function. If the script can't +be found 32512 will be returned. + +The following table gives some example returned statuses. + +Script exit status @ Returned system call status +1 @ 256 +5 @ 1280 +10 @ 2560 +200 @ 51200 +script not found @ 32512 + +... +# pass two parameters, hello and world +$ pigs shell scr1 hello world +256 + +# pass three parameters, hello, string with spaces, and world +$ pigs shell scr1 "hello 'string with spaces' world" +256 + +# pass one parameter, hello string with spaces world +$ pigs shell scr1 "\"hello string with spaces world\"" +256 + +# non-existent script +$ pigs shell scr78 par1 +32512 +... + +SLR :: + +This command returns up to [*num*] bytes of bit bang serial data +read from GPIO [*u*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +The GPIO [*u*] should have been initialised with the [*SLRO*] command. + +The bytes returned for each character depend upon the number of +data bits [*db*] specified in the [*SLRO*] command. + +For [*db*] 1-8 there will be one byte per character. +For [*db*] 9-16 there will be two bytes per character. +For [*db*] 17-32 there will be four bytes per character. + +... +$ pigs slr 15 20 +6 1 0 23 45 89 0 +... + +SLRC :: + +This command closes GPIO [*u*] for reading bit bang serial data. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs slrc 23 + +$ pigs slrc 23 +-38 +ERROR: no serial read in progress on GPIO +... + +SLRI :: + +This command sets the logic level for reading bit bang serial data +on GPIO [*u*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The invert parameter [*v*] is 1 for inverted signal, 0 for normal. + +... +$ pigs slri 17 1 # invert logic on GPIO 17 + +$ pigs slri 23 0 # use normal logic on GPIO 23 +... + +SLRO :: + +This command opens GPIO [*u*] for reading bit bang serial data +at [*b*] baud and [*db*] data bits. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The baud rate may be between 50 and 250000 bits per second. + +The received data is held in a cyclic buffer. + +It is the user's responsibility to read the data (with [*SLR*]) +in a timely fashion. + +... +$ pigs slro 23 19200 8 + +$ pigs slro 23 19200 8 +-50 +ERROR: GPIO already in use +... + +SPIC :: + +This command closes the SPI handle [*h*] returned by a prior +call to [*SPIO*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs spic 1 + +$ pigs spic 1 +-25 +ERROR: unknown handle +... + +SPIO :: + +This command returns a handle to a SPI device on channel [*c*]. + +Data will be transferred at [*b*] bits per second. The flags [*spf*] +may be used to modify the default behaviour of 4-wire operation, +mode 0, active low chip select. + +Speeds between 32kbps and 125Mbps are allowed. Speeds above 30Mbps +are unlikely to work. + +The Pi has two SPI peripherals: main and auxiliary. + +The main SPI has two chip selects (channels), the auxiliary has +three. + +The auxiliary SPI is available on all models but the A and B. + +The GPIO used are given in the following table. + + @ MISO @ MOSI @ SCLK @ CE0 @ CE1 @ CE2 +Main SPI @ 9 @ 10 @ 11 @ 8 @ 7 @ - +Aux SPI @ 19 @ 20 @ 21 @ 18 @ 17 @ 16 + +The flags consists of the least significant 22 bits. + +. . +21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m +. . + +mm defines the SPI mode. + +Warning: modes 1 and 3 do not appear to work on the auxiliary SPI. + +. . +Mode POL PHA + 0 0 0 + 1 0 1 + 2 1 0 + 3 1 1 +. . + +px is 0 if CEx is active low (default) and 1 for active high. + +ux is 0 if the CEx GPIO is reserved for SPI (default) and 1 otherwise. + +A is 0 for the main SPI, 1 for the auxiliary SPI. + +W is 0 if the device is not 3-wire, 1 if the device is 3-wire. Main +SPI only. + +nnnn defines the number of bytes (0-15) to write before switching +the MOSI line to MISO to read data. This field is ignored +if W is not set. Main SPI only. + +T is 1 if the least significant bit is transmitted on MOSI first, the +default (0) shifts the most significant bit out first. Auxiliary SPI +only. + +R is 1 if the least significant bit is received on MISO first, the +default (0) receives the most significant bit first. Auxiliary SPI +only. + +bbbbbb defines the word size in bits (0-32). The default (0) +sets 8 bits per word. Auxiliary SPI only. + +The [*SPIR*], [*SPIW*], and [*SPIX*] commands transfer data +packed into 1, 2, or 4 bytes according to the word size in bits. + +For bits 1-8 there will be one byte per character. +For bits 9-16 there will be two bytes per character. +For bits 17-32 there will be four bytes per character. + +Multi-byte transfers are made in least significant byte first order. + +E.g. to transfer 32 11-bit words 64 bytes need to be sent. + +E.g. to transfer the 14 bit value 0x1ABC send the bytes 0xBC followed +by 0x1A. + +The other bits in flags should be set to zero. + +Upon success a handle (>=0) is returned. On error a negative status code +will be returned. + +... +$ pigs spio 0 100000 3 # Open channel 0 at 100kbps in mode 3. +0 + +$ pigs spio 0 32000 256 # Open channel 0 of auxiliary spi at 32kbps. +1 +... + +SPIR :: + +This command returns [*num*] bytes read from the SPI device +associated with handle [*h*]. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +... +$ pigs spir 0 10 # Read 10 bytes from the SPI device. +10 0 0 0 0 0 0 0 0 0 0 +... + +SPIW :: + +This command writes bytes [*bvs*] to the SPI device +associated with handle [*h*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs spiw 0 0x22 0x33 0xcc 0xff +... + +SPIX:: + +This command writes bytes [*bvs*] to the SPI device +associated with handle [*h*]. It returns the same +number of bytes read from the device. + +Upon success the count of returned bytes followed by the bytes themselves +is returned. On error a negative status code will be returned. + +... +$ pigs spix 0 0x22 0x33 0xcc 0xff +4 0 0 0 0 +... + +T/TICK :: + +This command returns the current system tick. + +Tick is the number of microseconds since system boot. + +As tick is an unsigned 32 bit quantity it wraps around after 2^32 microseconds, +which is approximately 1 hour 12 minutes. + +... +$ pigs t mils 1000 t +3691823946 +3692833987 +... + +TRIG :: + +This command sends a trigger pulse of [*pl*] microseconds at level [*L*] +to GPIO [*u*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The GPIO is set to not level at the end of the pulse. + +... +$ pigs trig 4 10 1 + +$ pigs trig 4 51 1 +-46 +ERROR: trigger pulse > 50 microseconds +... + +W/WRITE :: + +This command sets GPIO [*g*] to level [*L*]. The level may be 0 +(low, off, clear) or 1 (high, on, set). + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs w 23 0 +$ pigs w 23 1 + +$ pigs w 23 2 +-5 +ERROR: level not 0-1 +... + +WDOG :: + +This command sets a watchdog of [*v*] milliseconds on GPIO [*u*]. + +Upon success nothing is returned. On error a negative status code +will be returned. + +The watchdog is nominally in milliseconds. + +One watchdog may be registered per GPIO. + +The watchdog may be cancelled by setting timeout to 0. + +Once a watchdog has been started monitors of the GPIO +will be triggered every timeout interval after the last +GPIO activity. The watchdog expiry will be indicated by +a special TIMEOUT value. + +... +$ pigs wdog 23 90000 +-15 +ERROR: timeout not 0-60000 + +$ pigs wdog 23 9000 +... + +This example causes a report to be written to any notification pipes +listening on GPIO 23 whenever GPIO 23 changes state or approximately +every 9000 ms. + +WVAG :: + +This command adds 1 one or more triplets [*trips*] of GPIO on, GPIO off, +delay to the existing waveform (if any). + +Upon success the total number of pulses in the waveform so far is +returned. On error a negative status code will be returned. + +The triplets will be added at the start of the existing waveform. If +they are to start offset from the start then the first triplet should +consist solely of a delay i.e. 0 0 offset. + +... +$ pigs wvag 0x10 0x80 1000 0x80 0x10 9000 +2 + +$ pigs wvag 0 0 10000 0x10 0x80 1000 0x80 0x10 9000 +4 +... + +WVAS :: + +This command adds a waveform representing serial data [*bvs*] to +GPIO [*u*] at [*b*] baud to the existing waveform (if any). +The serial data starts [*o*] microseconds from the start of the +waveform. + +Upon success the total number of pulses in the waveform so far is +returned. On error a negative status code will be returned. + +The serial data is formatted as one start bit, [*db*] data bits, and +[*sb*]/2 stop bits. + +The baud rate may be between 50 and 1000000 bits per second. + +It is legal to add serial data streams with different baud rates to +the same waveform. + +The bytes required for each character depend upon [*db*]. + +For [*db*] 1-8 there will be one byte per character. +For [*db*] 9-16 there will be two bytes per character. +For [*db*] 17-32 there will be four bytes per character. + +... +$ pigs wvas 4 9600 8 2 0 0x30 0x31 0x32 0x33 +23 + +$ pigs wvas 7 38400 8 2 0 0x41 0x42 +35 +... + +WVTAT :: + +This command returns the id of the waveform currently +being transmitted. Chained waves are not supported. + +Returns the waveform id or one of the following special +values: + +9998 - transmitted wave not found +9999 - no wave being transmitted + +... +$ pigs wvtat +9999 +... + +WVBSY :: + +This command checks to see if a waveform is currently being transmitted. + +Returns 1 if a waveform is currently being transmitted, otherwise 0. + +... +$ pigs wvbsy +0 +... + +WVCHA :: + +This command transmits a chain of waveforms. + +NOTE: Any hardware PWM started by [*HP*] will +be cancelled. + +The waves to be transmitted are specified by the contents of +[*bvs*] which contains an ordered list of wave_ids and optional +command codes and related data. + +Upon success 0 is returned. On error a negative status code +will be returned. + +Each wave is transmitted in the order specified. A wave may +occur multiple times per chain. + +A blocks of waves may be transmitted multiple times by using +the loop commands. The block is bracketed by loop start and +end commands. Loops may be nested. + +Delays between waves may be added with the delay command. + +The following command codes are supported: + +Name @ Cmd & Data @ Meaning +Loop Start @ 255 0 @ Identify start of a wave block +Loop Repeat @ 255 1 x y @ loop x + y*256 times +Delay @ 255 2 x y @ delay x + y*256 microseconds +Loop Forever @ 255 3 @ loop forever + +If present Loop Forever must be the last entry in the chain. + +The code is currently dimensioned to support a chain with roughly +600 entries and 20 loop counters. + +... +#!/bin/bash + +GPIO=4 +WAVES=5 + +pigs m $GPIO w + +for ((i=0; i<$WAVES; i++)) +do + pigs wvag $((1<=0) is returned. On error a negative status +code will be returned. + +The data provided by the [*WVAG*] and [*WVAS*] commands is +consumed by this command. + +As many waveforms may be created as there is space available. +The wave id is passed to [*WVTX*] or [*WVTXR*] to specify the +waveform to transmit. + +Normal usage would be + +Step 1. [*WVCLR*] to clear all waveforms and added data. + +Step 2. [*WVAG*]/[*WVAS*] calls to supply the waveform data. + +Step 3. [*WVCRE*] to create the waveform and get a unique id. + +Repeat steps 2 and 3 as needed. + +Step 4. [*WVTX*] or [*WVTXR*] with the id of the waveform to transmit. + +A waveform comprises of one or more pulses. + +A pulse specifies + +1) the GPIO to be switched on at the start of the pulse. +2) the GPIO to be switched off at the start of the pulse. +3) the delay in microseconds before the next pulse. + +Any or all the fields can be zero. It doesn't make any sense to +set all the fields to zero (the pulse will be ignored). + +When a waveform is started each pulse is executed in order with +the specified delay between the pulse and the next. + +... +$ pigs wvas 4 9600 0 23 45 67 89 90 +37 +$ pigs wvcre +0 + +$ pigs wvcre +-69 +ERROR: attempt to create an empty waveform +... + +WVCAP :: + +Create a waveform of fixed size. Similar to [*WVCRE*], this command creates a waveform but pads the consumed resources to a fixed size, specified as a [*percent*] of the total resources. Padded waves of equal size can be re-cycled efficiently allowing newly created waves to re-use the resources of deleted waves of the same dimension. + +Upon success a wave id (>=0) is returned. On error a negative status code will be returned. + +The data provided by the [*WVAG*] and [*WVAS*] commands are consumed by this command. + +As many waveforms may be created as there is space available. The wave id is passed to [*WVTX*] or [*WVTXR*] to specify the waveform to transmit. + +Normal usage would be + +Step 1. [*WVCLR*] to clear all waveforms and added data. + +Step 2. [*WVAG*]/[*WVAS*] calls to supply the waveform data. + +Step 3. [*WVCAP*] to create a waveform of a uniform size. + +Step 4. [*WVTX*] or [*WVTXR*] with the id of the waveform to transmit. + +Repeat steps 2 - 4 as needed. + +Step 5. Any wave id can now be deleted and another wave of the same size can be created in its place. + +Example + +... +# Create a wave that consumes 50% of the total resource: + +$ pigs wvag 16 0 5000000 0 16 5000000 +2 +$ pigs wvcap 50 +0 +$ pigs wvtx 0 +11918 +... + +WVDEL :: + +This command deletes the waveform with id [*wid*]. + +The wave is flagged for deletion. The resources used by the wave +will only be reused when either of the following apply. + +- all waves with higher numbered wave ids have been deleted or have +been flagged for deletion. + +- a new wave is created which uses exactly the same resources as +the current wave (see the C source for gpioWaveCreate for details). + +Upon success nothing is returned. On error a negative status code +will be returned. + +... +$ pigs wvdel 0 + +$ pigs wvdel 0 +-66 +ERROR: non existent wave id +... + +WVHLT :: + +This command aborts the transmission of the current waveform. + +Nothing is returned. + +This command is intended to stop a waveform started in the repeat mode. + +... +$ pigs wvhlt +... + +WVNEW :: + +This clears any existing waveform data ready for the creation of a new +waveform. + +Nothing is returned. + +... +$ pigs wvnew +... + +WVSC :: + +The statistic requested by [*ws*] is returned. + +[*ws*] identifies the subcommand as follows. + +0 Get Cbs +1 Get High Cbs +2 Get Max Cbs + +... +$ pigs wvas 4 9600 0 23 45 67 89 90 +37 + +$ pigs wvsc 0 +74 +$ pigs wvsc 1 +74 +$ pigs wvsc 2 +25016 +... + +WVSM :: + +The statistic requested by [*ws*] is returned. + +[*ws*] identifies the subcommand as follows. + +0 Get Micros +1 Get High Micros +2 Get Max Micros + +... +$ pigs wvsm 0 +5314 +$ pigs wvsm 1 +5314 +$ pigs wvsm 2 +1800000000 +... + +WVSP :: + +The statistic requested by [*ws*] is returned. + +[*ws*] identifies the subcommand as follows. + +0 Get Pulses +1 Get High Pulses +2 Get Max Pulses + +... +$ pigs wvsp 0 +37 +$ pigs wvsp 1 +37 +$ pigs wvsp 2 +12000 +... + +WVTX :: + +This command transmits the waveform with id [*wid*] once. + +NOTE: Any hardware PWM started by [*HP*] will be cancelled. + +Upon success the number of DMA control blocks in the waveform is returned. +On error a negative status code will be returned. + +... +$ pigs wvtx 1 +75 + +$ pigs wvtx 2 +-66 +ERROR: non existent wave id +... + +WVTXM :: + +This command transmits the waveform with id [*wid*] using mode [*wmde*]. + +The mode may be send once (0), send repeatedly (1), send once but +first sync with previous wave (2), or send repeatedly but first +sync with previous wave (3). + +WARNING: bad things may happen if you delete the previous +waveform before it has been synced to the new waveform. + +NOTE: Any hardware PWM started by [*HP*] will be cancelled. + +Upon success the number of DMA control blocks in the waveform is returned. +On error a negative status code will be returned. + +... +$ pigs wvtxm 1 3 +75 + +$ pigs wvtxm 2 0 +-66 +ERROR: non existent wave id +... + +WVTXR :: + +This command transmits the waveform with id [*wid*] repeatedly. + +NOTE: Any hardware PWM started by [*HP*] will be cancelled. + +Upon success the number of DMA control blocks in the waveform is returned. +On error a negative status code will be returned. + +... +$ pigs wvtxr 1 +75 + +$ pigs wvtxr 2 +-66 +ERROR: non existent wave id +... + +PARAMETERS + +actv :: 0-1000000 + +The number of microseconds level changes are reported for once +a noise filter has been triggered (by [*stdy*] microseconds of +a stable level). + +b :: baud +The command expects the baud rate in bits per second for +the transmission of serial data (I2C/SPI/serial link, waves). + +bctl :: BSC control word +The command expects a BSC control word, see [*BSCX*]. + +bit :: bit value (0-1) +The command expects 0 or 1. + +bits :: a bit mask +A mask is used to select one or more GPIO. A GPIO is selected +if bit (1<=0) +The command expects a handle. + +A handle is a number referencing an object opened by one of [*FO*], +[*I2CO*], [*NO*], [*SERO*], [*SPIO*]. + +ib :: I2C bus (>=0) +The command expects an I2C bus number. + +id :: I2C device (0-0x7F) +The command expects the address of an I2C device. + +if :: I2C flags (0) +The command expects an I2C flags value. No flags are currently defined. + +L :: level (0-1) +The command expects a GPIO level. + +m :: mode (RW540123) +The command expects a mode character. + +Each GPIO can be configured to be in one of 8 different modes. The modes +are named Input, Output, ALT0, ALT1, ALT2, ALT3, ALT4, and ALT5. + +To set the mode use the code for the mode. + +The value is returned by the mode get command. + +Mode @ Input @ Output @ ALT0 @ ALT1 @ ALT2 @ ALT3 @ ALT4 @ ALT5 +Code @ R @ W @ 0 @ 1 @ 2 @ 3 @ 4 @ 5 +Value @ 0 @ 1 @ 4 @ 5 @ 6 @ 7 @ 3 @ 2 + +miso :: GPIO (0-31) +The GPIO used for the MISO signal when bit banging SPI. + +mode :: file open mode +One of the following values. + + @ Value @ Meaning +READ @ 1 @ open file for reading +WRITE @ 2 @ open file for writing +RW @ 3 @ open file for reading and writing + +The following values can be or'd into the mode. + + @ Value @ Meaning +APPEND @ 4 @ All writes append data to the end of the file +CREATE @ 8 @ The file is created if it doesn't exist +TRUNC @ 16 @ The file is truncated + +mosi :: GPIO (0-31) +The GPIO used for the MOSI signal when bit banging SPI. + +name :: the name of a script +Only alphanumeric characters, '-' and '_' are allowed in the name. + +num :: maximum number of bytes to return (1-) +The command expects the maximum number of bytes to return. + +For the I2C and SPI commands the requested number of bytes will always +be returned. + +For the serial and file commands the smaller of the number of +bytes available to be read (which may be zero) and [*num*] bytes +will be returned. + +o :: offset (>=0) +Serial data is stored offset microseconds from the start of the waveform. + +p :: PUD (ODU) +The command expects a PUD character. + +Each GPIO can be configured to use or not use an internal pull up or +pull down resistor. This is useful to provide a default state for inputs. + +A pull up will default the input to 1 (high). + +A pull down will default the input to 0 (low). + +To set the pull up down state use the command character for the state. + +Pull Up Down @Off@Pull Down@Pull Up +Command Character@ O@ D@ U + +There is no mechanism to read the pull up down state. + +pad :: 0-2 +A set of GPIO which share common drivers. + +Pad @ GPIO +0 @ 0-27 +1 @ 28-45 +2 @ 46-53 + +padma:: 1-16 +The mA which may be drawn from each GPIO whilst still guaranteeing the +high and low levels. + +pars :: script parameters +The command expects 0 to 10 numbers as parameters to be passed to the script. + +pat :: a file name pattern +A file path which may contain wildcards. To be accessible the path +must match an entry in /opt/pigpio/access. + +pdc :: hardware PWM dutycycle (0-1000000) +The command expects a dutycycle. + +percent :: percent (1-100) +The percent of wave resources to allocate to a wave. It can be useful +to create waves of fixed sizes to prevent wave fragmentation (where +there are plenty of resources but not a large enough contiguous space). + +pf :: hardware PWM frequency (1-125M, 1-187.5M for the BCM2711) +The command expects a frequency. + +pl :: pulse length (1-100) +The command expects a pulse length in microseconds. + +r :: register (0-255) +The command expects an I2C register number. + +sb :: serial stop (half) bits (2-8) +The command expects the number of stop (half) bits per serial character. + +scl :: user GPIO (0-31) +The command expects the number of the GPIO to be used for SCL +when bit banging I2C. + +sclk :: user GPIO (0-31) +The GPIO used for the SCLK signal when bit banging SPI. + +sda :: user GPIO (0-31) +The command expects the number of the GPIO to be used for SDA +when bit banging I2C. + +sef :: serial flags (32 bits) +The command expects a flag value. No serial flags are currently defined. + +sid :: script id (>= 0) +The command expects a script id as returned by a call to [*PROC*]. + +spf :: SPI flags (32 bits) +See [*SPIO*] and [*BSPIO*]. + +stdy :: 0-300000 + +The number of microseconds level changes must be stable for +before reporting the level changed ([*FG*]) or triggering +the active part of a noise filter ([*FN*]). + +str :: a string +The command expects a string. + +t :: a string +The command expects a string. + +trips :: triplets +The command expects 1 or more triplets of GPIO on, GPIO off, delay. + +E.g. 0x400000 0 100000 0 0x400000 900000 defines two pulses as follows + + GPIO on @ GPIO off @ delay +0x400000 (GPIO 22)@ 0 (None)@100000 (1/10th s) + 0 (None)@0x400000 (GPIO 22)@900000 (9/10th s) + +u :: user GPIO (0-31) +The command expects the number of a user GPIO. + +A number of commands are restricted to GPIO in bank 1, +in particular the PWM commands, the servo command, +the watchdog command, and the notification command. + +It is your responsibility to ensure that the PWM and servo commands +are only used on safe GPIO. + +See [*g*] + +uvs :: values +The command expects an arbitrary number of >=0 values (possibly none). +Any after the first two must be <= 255. + +v :: value +The command expects a number. + +wid :: wave id (>=0) +The command expects a wave id. + +When a waveform is created it is given an id (0, 1, 2, ...). + +wmde :: mode (0-3) +The command expects a wave transmission mode. + +0 = send once +1 = send repeatedly +2 = send once but first sync with previous wave +3 = send repeatedly but first sync with previous wave + +ws :: wave stats sucommand (0-2) +The command expects a subcommand. + +0 = current value. +1 = highest value so far. +2 = maximum possible value. + +wv :: word value (0-65535) +The command expects a word value. + +SCRIPTS + +Scripts are programs to be stored and executed by the pigpio daemon. +They are intended to mitigate any performance problems associated with +the pigpio daemon server/client model. + +*Example* + +A trivial example might be useful. Suppose you want to toggle a GPIO +on and off as fast as possible. + +From the command line you could write + +... +for ((i=0; i<1000;i++)); do pigs w 22 1 w 22 0; done +... + +Timing that you will see it takes about 14 seconds, or roughly +70 toggles per second. + +Using the pigpio Python module you could use code such as + +... +#!/usr/bin/env python + +import time + +import pigpio + +PIN=4 + +TOGGLE=10000 + +pi = pigpio.pi() # Connect to local Pi. + +s = time.time() + +for i in range(TOGGLE): + pi.write(PIN, 1) + pi.write(PIN, 0) + +e = time.time() + +print("pigpio did {} toggles per second".format(int(TOGGLE/(e-s)))) + +pi.stop() +... + +Timing that shows a speed improvement to roughly 800 toggles per second. + +Now let's use a script. + +... +pigs proc tag 999 w 22 1 w 22 0 dcr p0 jp 999 +... + +Ignore the details for now. + +Let's time the script running. + +Again, ignore the details for now. + +... +time (pigs procr 0 10000000; while a=$(pigs procp 0); [[ ${a::1} -eq 2 ]];\ + do sleep 0.2; done) +... + +The script takes roughly 12 seconds to complete, or 800,000 toggles per second. + +That is the advantage of a stored script. + +Some details. + +... +pigs proc tag 999 w 22 1 w 22 0 dcr p0 jp 999 +... + +proc introduces a script. Everything after proc is part of the script. +tag 999 names the current position in the script. +w 22 1 writes 1 to GPIO 22. +w 22 0 writes 0 to GPIO 22. +dcr p0 decrements parameter 0. +jp 999 jumps to tag 999 if the result is positive. + +... +time (pigs procr 0 10000000; while a=$(pigs procp 0); [[ ${a::1} -eq 2 ]];\ + do sleep 0.2; done) +... + +pigs procr 0 10000000 starts script 0 with parameter 0 of 10 million. + +The rest is bash apart from + +pigs procp 0 asks for the status and parameters of script 0. +The status will be 2 while the script is running and 1 when it is complete. + +*Virtual machine* + +A script runs within a virtual machine with + +a 32 bit accumulator A. +a flags register F. +a program counter PC. + +Each script has + +10 parameters named 0 through 9. +150 variables named 0 through 149. +50 labels which are named by any unique number. + +*Commands* + +Many pigpio commands may be used within a script. However +some commands do not work within the script model as designed and +are not permitted. + +The following commands are not permitted within a script: + +File - FL FO FR FW + +I2C - BI2CZ I2CPK I2CRD I2CRI I2CRK I2CWD I2CWI I2CWK I2CZ + +Misc - BSCX CF1 CF2 SHELL + +Script control - PARSE PROC PROCD PROCP PROCR PROCS PROCU + +Serial - SERO SERR SERW SLR + +SPI - BSPIO BSPIX SPIR SPIW SPIX + +Waves - WVAG WVAS WVCHA WVGO WVGOR + +The following commands are only permitted within a script: + +Command@Description @Definition +ADD x @Add x to accumulator @A+=x; F=A +AND x @And x with accumulator @A&=x; F=A +CALL L @Call subroutine at tag L @push(PC+1); PC=L +CMP x @Compare x with accumulator @F=A-x +DCR y @Decrement register @--*y; F=*y +DCRA @Decrement accumulator @--A; F=A +DIV x @Divide x into accumulator @A/=x; F=A +EVTWT @Wait for an event to occur @A=wait(x); F=A +HALT @Halt @Halt +INR y @Increment register @++*y; F=*y +INRA @Increment accumulator @++A; F=A +JM L @Jump if minus to tag L @if (F<0) PC=L +JMP L @Jump to tag L @PC=L +JNZ L @Jump if non-zero to tag L @if (F) PC=L +JP L @Jump if positive to tag L @if (F>=0) PC=L +JZ L @Jump if zero to tag L @if (!F) PC=L +LD y x @Load register with x @*y=x +LDA x @Load accumulator with x @A=x +MLT x @Multiply x with accumulator @A*=x; F=A +MOD x @Modulus x with accumulator @A%=x; F=A +OR x @Or x with accumulator @A|=x; F=A +POP y @Pop register @y=pop() +POPA @Pop accumulator @A=pop() +PUSH y @Push register @push(y) +PUSHA @Push accumulator @push(A) +RET @Return from subroutine @PC=pop() +RL y x @Rotate left register x bits @*y<<=x; F=*y +RLA x @Rotate left accumulator x bits @A<<=x; F=A +RR y x @Rotate right register x bits @*y>>=x; F=*y +RRA x @Rotate right accumulator x bits @A>>=x; F=A +STA y @Store accumulator in register @y=A +SUB x @Subtract x from accumulator @A-=x; F=A +SYS str@Run external script (/opt/pigpio/cgi/str) @system(str); F=A +TAG L @Label the current script position @N/A +WAIT x @Wait for a GPIO in x to change state @A=wait(x); F=A +X y1 y2@Exchange contents of registers y1 and y2 @t=*y1;*y1=*y2;*y2=t +XA y @Exchange contents of accumulator and register@t=A;A=*y;*y=t +XOR x @Xor x with accumulator @A^=x; F=A + +x may be a constant, a parameter (p0-p9), or a variable (v0-v149). + +y may be a parameter (p0-p9), or a variable (v0-v149). If p or v isn't +specified y is assumed to be a variable. + +The EVTWT command parameter is a bit-mask with 1 set for events of interest. + +The WAIT command parameter is a bit-mask with 1 set for GPIO of interest. + +The SYS script receives two unsigned parameters: the accumulator A and +the current GPIO levels. + diff --git a/DOC/src/html/download.html b/DOC/src/html/download.html new file mode 100644 index 0000000..740a3c8 --- /dev/null +++ b/DOC/src/html/download.html @@ -0,0 +1,68 @@ + + + + + +download + + +If the pigpio daemon is running it should be killed (sudo killall +pigpiod) before make install and restarted afterwards (sudo +pigpiod).
+
+The initial part of the make, the +compilation of pigpio.c, takes 100 seconds on early model +Pis.  Be patient.  The overall install takes just over 3 +minutes.
+

Download and install latest version

+ +wget https://github.com/joan2937/pigpio/archive/master.zip
+unzip master.zip
+cd pigpio-master
+make
+sudo make install
+
+
+If the Python part of the install fails it may be because you need +the setup tools.
+
+sudo apt install python-setuptools +python3-setuptools

+
+

To check the library

+These tests make extensive use of GPIO 25 (pin 22).  Make sure +nothing, or only a LED, is connected to the GPIO before running the +tests.  Most tests are statistical in nature and so may on +occasion fail.  Repeated failures on the same test or many +failures in a group of tests indicate a problem.
+
+sudo ./x_pigpio # check C I/F
+
+sudo pigpiod    # start daemon
+
+./x_pigpiod_if2 # check C      I/F to +daemon
+./x_pigpio.py   # check Python I/F to daemon
+./x_pigs        # check +pigs   I/F to daemon
+./x_pipe        # check +pipe   I/F to daemon
+
+
+

To compile, link, and run a C program

+gcc -Wall -pthread -o foobar foobar.c -lpigpio -lrt
+sudo ./foobar


+

To start the pigpio daemon

+sudo pigpiod
+

To stop the pigpio daemon

+sudo killall pigpiod

+

github

+git clone https://github.com/joan2937/pigpio
+

Raspbian (raspberrypi.org image)

+

This may not be the most recent version.  You can check the +version with the command pigpiod -v.

+sudo apt-get update
+sudo apt-get install pigpio python-pigpio python3-pigpio

+
+ + diff --git a/DOC/src/html/ex_LDR.html b/DOC/src/html/ex_LDR.html new file mode 100644 index 0000000..3c54c68 --- /dev/null +++ b/DOC/src/html/ex_LDR.html @@ -0,0 +1,150 @@ + + + + + +LDR example + + +

The following code shows a method of reading analogue sensors on +the digital input only Pi.  A Light Dependent Resistor (LDR) +varies its resistance according to the incident light +intensisty.

+

SETUP

+fritzing diagramThe LDR +used is a Cadmium Sulphide device with a 1MOhm dark resistance and +2-4KOhm at 100 lux.  The capacitor is a 104 +ceramic.
+
+One end of the capacitor is connected to Pi ground.
+
+One end of the LDR is connected to Pi 3V3.
+
+The other ends of the capacitor and LDR are connected to a spare +gpio.

+

Here P1-1 is used for 3V3, P1-20 is used for ground, and gpio 18 +(P1-12) is used for the gpio.

+

photo of set-up

+

CODE

+#include <stdio.h>
+
+#include <pigpio.h>
+
+/* +-----------------------------------------------------------------------
+ +
+   3V3 ----- Light Dependent Resistor --+-- Capacitor +----- Ground
+                                        +|
+                                        ++-- gpio
+
+
+  cc -o LDR LDR.c -lpigpio -lpthread -lrt
+  sudo ./LDR
+
+*/
+
+#define LDR 18
+
+/* forward declaration */
+
+void alert(int pin, int level, uint32_t tick);
+
+int main (int argc, char *argv[])
+{
+   if (gpioInitialise()<0) return 1;
+
+   gpioSetAlertFunc(LDR, alert); /* call alert when LDR +changes state */
+    
+   while (1)
+   {
+      gpioSetMode(LDR, PI_OUTPUT); /* +drain capacitor */
+
+      gpioWrite(LDR, PI_OFF);
+
+      gpioDelay(200); /* 50 micros is +enough, 200 is overkill */
+
+      gpioSetMode(LDR, PI_INPUT); /* start +capacitor recharge */
+
+      gpioDelay(10000); /* nominal 100 +readings per second */
+   }
+
+   gpioTerminate();
+}
+
+void alert(int pin, int level, uint32_t tick)
+{
+   static uint32_t inited = 0;
+   static uint32_t lastTick, firstTick;
+
+   uint32_t diffTick;
+
+   if (inited)
+   {
+      diffTick = tick - lastTick;
+      lastTick = tick;
+
+      if (level == 1) printf("%u %d\ ", +tick-firstTick, diffTick);
+   }
+   else
+   {
+      inited = 1;
+      firstTick = tick;
+      lastTick = firstTick;
+   }
+}
+

BUILD

+cc -o LDR LDR.c -lpigpio -lrt -lpthread
+

RUN

+sudo ./LDR >LDR.dat &
+
+While the program is running you can capture the waveform using the +notification feature built in to pigpio.  Issue the following +commands on the Pi.
+
+pigs no
+pig2vcd  </dev/pigpio0 >LDR.vcd &
+pigs nb 0 0x40000 # set bit for gpio 18
+

Change the light falling on the LDR for a few seconds (e.g. +shine a torch on it or shade it with your hands).

+pigs nc 0
+

The file LDR.vcd will contain the captured waveform, which can +be viewed using GTKWave.

+

Overview

+LDR waveform 1
+

Reading circa every 10ms

+LDR waveform 2
+

One reading, circa 400us

+LDR waveform 3
+

The file LDR.dat will contain pairs of timestamps and recharge +time (in us).  The following  script will convert the +timestamps into seconds.

+

awk '{print $1/1000000, $2}' LDR.dat +>LDR-secs.dat

+

Gnuplot is a useful tool to graph data.

+plot [14:24] 'LDR-secs.dat' with lines title 'LDR' +

Gnuplot readings 14-24 seconds

+

gnuplot 1

+plot [18:21] 'LDR-secs.dat' with lines title 'LDR'
+
+Gnuplot readings 18-21 seconds +

Gnuplot 2

+ + diff --git a/DOC/src/html/ex_ir_remote.html b/DOC/src/html/ex_ir_remote.html new file mode 100644 index 0000000..2400a11 --- /dev/null +++ b/DOC/src/html/ex_ir_remote.html @@ -0,0 +1,253 @@ + + + + + +IR remote example + + +

The following code shows one way to read an infrared remote +control device (the sort used in TVs and stereo systems).

+

SETUP

+fritzing diagramThe device used +is a SFH5110 (IR Receiver for remote control, +carrier 38 kHz).
+
Pin 1 (left from front) may be connected to any spare +gpio.  Here it's connected via a 4K7 current limiting +resistor.  This isn't really needed as the device has an +internal 23K resistor in-line.  It does no harm though.
+
+Pin 2 should be connected to a Pi ground pin.
+
+Pin 3 should be connected to a Pi 5V pin.
+

Here pin 1 to gpio7 (P1-26) via a 4K7 resistor, pin 2 to ground +(P1-14), and pin 3 to 5V (P1-2).

+

photo of set-up

+

CODE

+#include <stdio.h>
+
+#include <pigpio.h>
+
+#define IR_PIN 7
+
+#define OUTSIDE_CODE 0
+#define INSIDE_CODE  1
+
+#define MIN_MESSAGE_GAP 3000
+#define MAX_MESSAGE_END 3000
+
+#define MAX_TRANSITIONS 500
+
+/*
+   using the FNV-1a +hash                
+ +   from +http://isthe.com/chongo/tech/comp/fnv/#FNV-param
+*/
+
+#define FNV_PRIME_32 16777619
+#define FNV_BASIS_32 2166136261U
+
+static volatile uint32_t ir_hash = 0;
+
+typedef struct
+{
+   int state;
+   int count;
+   int level;
+   uint16_t micros[MAX_TRANSITIONS];
+} decode_t;
+
+/* forward declarations */
+
+void     alert(int gpio, int level, uint32_t +tick);
+uint32_t getHash(decode_t * decode);
+void     updateState(decode_t * decode, int +level, uint32_t micros);
+
+int main(int argc, char * argv[])
+{
+   if (gpioInitialise()<0)
+   {
+      return 1 ;
+   }
+
+   /* IR pin as input */
+
+   gpioSetMode(IR_PIN, PI_INPUT);
+
+   /* 5ms max gap after last pulse */
+
+   gpioSetWatchdog(IR_PIN, 5);
+
+   /* monitor IR level changes */
+
+   gpioSetAlertFunc(IR_PIN, alert);
+
+   while (1)
+   {
+      if (ir_hash)
+      {
+         /* non-zero means +new decode */
+         printf("ir code is +%u\ ", ir_hash);
+         ir_hash = 0;
+      }
+
+      gpioDelay(100000); /* check remote +10 times per second */
+   }
+
+   gpioTerminate();
+}
+
+void alert(int gpio, int level, uint32_t tick)
+{
+   static int inited = 0;
+
+   static decode_t activeHigh, activeLow;
+
+   static uint32_t lastTick;
+
+   uint32_t diffTick;
+
+   if (!inited)
+   {
+      inited = 1;
+
+      activeHigh.state = OUTSIDE_CODE; +activeHigh.level = PI_LOW;
+      activeLow.state  = +OUTSIDE_CODE; activeLow.level  = PI_HIGH;
+
+      lastTick = tick;
+      return;
+   }
+
+   diffTick = tick - lastTick;
+
+   if (level != PI_TIMEOUT) lastTick = tick;
+
+   updateState(&activeHigh, level, diffTick);
+   updateState(&activeLow, level, diffTick);
+}
+
+void updateState(decode_t * decode, int level, uint32_t micros)
+{
+   /*
+      We are dealing with active high as +well as active low
+      remotes.  Abstract the common +functionality.
+   */
+
+   if (decode->state == OUTSIDE_CODE)
+   {
+      if (level == decode->level)
+      {
+         if (micros > +MIN_MESSAGE_GAP)
+         {
+            +decode->state = INSIDE_CODE;
+            +decode->count = 0;
+         }
+      }
+   }
+   else
+   {
+      if (micros > MAX_MESSAGE_END)
+      {
+         /* end of message +*/
+
+         /* ignore if last +code not consumed */
+
+         if (!ir_hash) +ir_hash = getHash(decode);
+
+         decode->state = +OUTSIDE_CODE;
+      }
+      else
+      {
+         if +(decode->count < (MAX_TRANSITIONS-1))
+         {
+            +if (level != PI_TIMEOUT)
+               +decode->micros[decode->count++] = micros;
+         }
+      }
+   }
+}
+
+int compare(unsigned int oldval, unsigned int newval)
+{
+   if      (newval < (oldval +* 0.75)) {return 1;}
+   else if (oldval < (newval * 0.75)) {return 2;}
+   +else                               +{return 4;}
+}
+
+uint32_t getHash(decode_t * decode)
+{
+   /* use FNV-1a */
+
+   uint32_t hash;
+   int i, value;
+
+   if (decode->count < 6) {return 0;}
+
+   hash = FNV_BASIS_32;
+
+   for (i=0; i<(decode->count-2); i++)
+   {
+      value = +compare(decode->micros[i], decode->micros[i+2]);
+
+      hash = hash ^ value;
+      hash = (hash * FNV_PRIME_32);
+   }
+
+   return hash;
+}
+

BUILD

+cc -o ir_remote ir_remote.c -lpigpio -lrt +-lpthread
+

RUN

+sudo ./ir_remote
+

A hash code is formed from the level transitions detected during +a remote key press.  This is likely to be unique over multiple +remotes and keys.

+

While the program is running you can capture the waveform using +the notification feature built in to pigpio.  Issue the +following commands on the Pi.

+pigs no
+pig2vcd  </dev/pigpio0 >ir.vcd &
+pigs nb 0 0x80 # set bits for gpios 7 (0x80)
+

Press a few different remotes and keys.  Then enter

+pigs nc 0
+

The file ir.vcd will contain the captured waveform, which can be +viewed using GTKWave.

+

Overview

+ir remote waveform 1
+

Remote A typical waveform

+ir remote waveform 2
+

Remote B typical waveform

++"ir + + diff --git a/DOC/src/html/ex_motor_shield.html b/DOC/src/html/ex_motor_shield.html new file mode 100644 index 0000000..777ba9e --- /dev/null +++ b/DOC/src/html/ex_motor_shield.html @@ -0,0 +1,254 @@ + + + + + +Arduino motor shield example + + +The following example demonstrates the use of an Arduino shield +from the Rasperry Pi.
+
+The shield used is a clone of the Adafruit motor shield.  See +shieldlist.org +for details.
+
+For the demonstration DC motors 3 and 4 are being driven forwards +and backwards with changing speeds (speeds are controlled via +PWM).
+
+Seven connections are made between the Pi and the shield.  +Four to latch the motor states (latch, enable, data, clock); Two to +control motor speed (PWM 3 and 4); and ground.
+
+The code used was ported from the Adafruit Arduino code and +converted to use the pigpio library.  Only the DC motor code +was ported.
+
+A video of the shield in use is available at youtube.com
+
+#include <stdio.h>

+
+#include <pigpio.h>
+
+/*
+   This code may be used to drive the Adafruit (or +clones) Motor Shield.
+
+   The code as written only supports DC motors.
+
+   http://shieldlist.org/adafruit/motor
+
+   The shield pinouts are
+
+   D12 MOTORLATCH
+   D11 PMW motor 1
+   D10 Servo 1
+   D9  Servo 2
+   D8  MOTORDATA
+
+   D7  MOTORENABLE
+   D6  PWM motor 4
+   D5  PWM motor 3
+   D4  MOTORCLK
+   D3  PWM motor 2
+
+   The motor states (forward, backward, brake, release) +are encoded using the
+   MOTOR_ latch pins.  This saves four gpios.
+*/
+
+typedef unsigned char uint8_t;
+
+#define BIT(bit) (1 << (bit))
+
+/* assign gpios to drive the shield pins */
+
+/*      +Shield      Pi */
+
+#define MOTORLATCH  14
+#define MOTORCLK    24
+#define MOTORENABLE 25
+#define MOTORDATA   15
+
+#define MOTOR_3_PWM  7
+#define MOTOR_4_PWM  8
+
+/*
+   The only other connection needed between the Pi and +the shield
+   is ground to ground. I used Pi P1-6 to shield gnd +(next to D13).
+*/
+
+/* assignment of motor states to latch */
+
+#define MOTOR1_A 2
+#define MOTOR1_B 3
+#define MOTOR2_A 1
+#define MOTOR2_B 4
+#define MOTOR4_A 0
+#define MOTOR4_B 6
+#define MOTOR3_A 5
+#define MOTOR3_B 7
+
+#define FORWARD  1
+#define BACKWARD 2
+#define BRAKE    3
+#define RELEASE  4
+
+static uint8_t latch_state;
+
+void latch_tx(void)
+{
+   unsigned char i;
+
+   gpioWrite(MOTORLATCH, PI_LOW);
+
+   gpioWrite(MOTORDATA, PI_LOW);
+
+   for (i=0; i<8; i++)
+   {
+      gpioDelay(10);  // 10 micros +delay
+
+      gpioWrite(MOTORCLK, PI_LOW);
+
+      if (latch_state & BIT(7-i)) +gpioWrite(MOTORDATA, PI_HIGH);
+      +else                        +gpioWrite(MOTORDATA, PI_LOW);
+
+      gpioDelay(10);  // 10 micros +delay
+
+      gpioWrite(MOTORCLK, PI_HIGH);
+   }
+
+   gpioWrite(MOTORLATCH, PI_HIGH);
+}
+
+void init(void)
+{
+   latch_state = 0;
+
+   latch_tx();
+
+   gpioWrite(MOTORENABLE, PI_LOW);
+}
+
+void DCMotorInit(uint8_t num)
+{
+   switch (num)
+   {
+      case 1: latch_state &= +~BIT(MOTOR1_A) & ~BIT(MOTOR1_B); break;
+      case 2: latch_state &= +~BIT(MOTOR2_A) & ~BIT(MOTOR2_B); break;
+      case 3: latch_state &= +~BIT(MOTOR3_A) & ~BIT(MOTOR3_B); break;
+      case 4: latch_state &= +~BIT(MOTOR4_A) & ~BIT(MOTOR4_B); break;
+      default: return;
+   }
+
+   latch_tx();
+
+   printf("Latch=%08X\ ", latch_state);
+}
+
+void DCMotorRun(uint8_t motornum, uint8_t cmd)
+{
+   uint8_t a, b;
+
+   switch (motornum)
+   {
+      case 1: a = MOTOR1_A; b = MOTOR1_B; +break;
+      case 2: a = MOTOR2_A; b = MOTOR2_B; +break;
+      case 3: a = MOTOR3_A; b = MOTOR3_B; +break;
+      case 4: a = MOTOR4_A; b = MOTOR4_B; +break;
+      default: return;
+   }

+   switch (cmd)
+   {
+      case FORWARD:  latch_state +|=  BIT(a); latch_state &= ~BIT(b); break;
+      case BACKWARD: latch_state &= +~BIT(a); latch_state |=  BIT(b); break;
+      case RELEASE:  latch_state +&= ~BIT(a); latch_state &= ~BIT(b); break;
+      default: return;
+   }
+
+   latch_tx();
+
+   printf("Latch=%08X\ ", latch_state);
+}
+
+int main (int argc, char *argv[])
+{
+   int i;
+
+   if (gpioInitialise()<0) return 1;
+
+   gpioSetMode(MOTORLATCH,  PI_OUTPUT);
+   gpioSetMode(MOTORENABLE, PI_OUTPUT);
+   gpioSetMode(MOTORDATA,   PI_OUTPUT);
+   gpioSetMode(MOTORCLK,    +PI_OUTPUT);
+
+   gpioSetMode(MOTOR_3_PWM, PI_OUTPUT);
+   gpioSetMode(MOTOR_4_PWM, PI_OUTPUT);
+
+   gpioPWM(MOTOR_3_PWM, 0);
+   gpioPWM(MOTOR_4_PWM, 0);
+
+   init();
+
+   for (i=60; i<160; i+=20)
+   {
+      gpioPWM(MOTOR_3_PWM, i);
+      gpioPWM(MOTOR_4_PWM, 220-i);
+
+      DCMotorRun(3, FORWARD);
+      DCMotorRun(4, BACKWARD);
+
+      sleep(2);
+
+      DCMotorRun(3, RELEASE);
+      DCMotorRun(4, RELEASE);
+
+      sleep(2);
+
+      gpioPWM(MOTOR_4_PWM, i);
+      gpioPWM(MOTOR_3_PWM, 220-i);
+
+      DCMotorRun(3, BACKWARD);
+      DCMotorRun(4, FORWARD);
+
+      sleep(2);
+
+      DCMotorRun(3, RELEASE);
+      DCMotorRun(4, RELEASE);
+
+      sleep(2);
+   }
+
+   gpioPWM(MOTOR_4_PWM, 0);
+   gpioPWM(MOTOR_3_PWM, 0);
+
+   DCMotorRun(3, RELEASE);
+   DCMotorRun(4, RELEASE);
+
+   gpioTerminate();
+}
+ + diff --git a/DOC/src/html/ex_rotary_encoder.html b/DOC/src/html/ex_rotary_encoder.html new file mode 100644 index 0000000..b95711e --- /dev/null +++ b/DOC/src/html/ex_rotary_encoder.html @@ -0,0 +1,185 @@ + + + + + +Rotary encoder sample + + +

The following code shows one way to read an incremental +mechanical rotary enoder (the sort used for volume control in audio +systems).  These rotary encoders have two switches A and B +which return a quadrature output, i.e. they are 90 degrees out of +phase.

+

SETUP

+fritzing diagramThe common +(centre) terminal should be connected to a Pi ground. +

The A and B terminals may be connected to any spare gpios.

+

Here A to gpio18 (P1-12), common to ground (P1-20), B to gpio7 +(P1-26).

+

photo of set-up

+

CODE

+#include <stdio.h>
+
+#include <pigpio.h>
+
+/*
+   Rotary encoder connections:
+
+   Encoder A      - gpio +18   (pin P1-12)
+   Encoder B      - gpio +7    (pin P1-26)
+   Encoder Common - Pi ground (pin P1-20)
+*/
+
+#define ENCODER_A 18
+#define ENCODER_B  7
+
+static volatile int encoderPos;
+
+/* forward declaration */
+
+void encoderPulse(int gpio, int lev, uint32_t tick);
+
+int main(int argc, char * argv[])
+{
+   int pos=0;
+
+   if (gpioInitialise()<0) return 1;
+
+   gpioSetMode(ENCODER_A, PI_INPUT);
+   gpioSetMode(ENCODER_B, PI_INPUT);
+
+   /* pull up is needed as encoder common is grounded +*/
+
+   gpioSetPullUpDown(ENCODER_A, PI_PUD_UP);
+   gpioSetPullUpDown(ENCODER_B, PI_PUD_UP);
+
+   encoderPos = pos;
+
+   /* monitor encoder level changes */
+
+   gpioSetAlertFunc(ENCODER_A, encoderPulse);
+   gpioSetAlertFunc(ENCODER_B, encoderPulse);
+
+   while (1)
+   {
+      if (pos != encoderPos)
+      {
+         pos = +encoderPos;
+         printf("pos=%d\ ", +pos);
+      }
+      gpioDelay(20000); /* check pos 50 +times per second */
+   }
+
+   gpioTerminate();
+}
+
+void encoderPulse(int gpio, int level, uint32_t tick)
+{
+   /*
+
+             ++---------+         ++---------+      0
+             +|         +|         +|         |
+   A         +|         +|         +|         |
+             +|         +|         +|         |
+   ++---------+         ++---------+         +----- +1
+
+       ++---------+         ++---------+            +0
+       +|         +|         +|         |
+   B   +|         +|         +|         |
+       +|         +|         +|         |
+   ----+         ++---------+         ++---------+  1
+
+   */
+
+   static int levA=0, levB=0, lastGpio = -1;
+
+   if (gpio == ENCODER_A) levA = level; else levB = +level;
+
+   if (gpio != lastGpio) /* debounce */
+   {
+      lastGpio = gpio;
+
+      if ((gpio == ENCODER_A) && +(level == 0))
+      {
+         if (!levB) +++encoderPos;
+      }
+      else if ((gpio == ENCODER_B) +&& (level == 1))
+      {
+         if (levA) +--encoderPos;
+      }
+   }
+}
+

BUILD

+cc -o rotary_encoder rotary_encoder.c -lpigpio -lrt +-lpthread
+

RUN

+sudo ./rotary_encoder
+

While the program is running you can capture the waveform using +the notification feature built in to pigpio.  Issue the +following commands on the Pi.

+pigs no
+pig2vcd  </dev/pigpio0 >re.vcd &
+pigs nb 0 0x40080 # set bits for gpios 7 (0x80) and 18 +(0x40000)
+

Twiddle the rotary encoder forwards and backwards for a few +seconds.  Then enter

+pigs nc 0
+

The file re.vcd will contain the captured waveform, which can be +viewed using GTKWave.

+
+Overview
+
++"rotary
+
+Detail of switch bounce.  Contact A bounces for circa 700 us +before completing the level transition
+
++"rotary
+ + diff --git a/DOC/src/html/ex_sonar_ranger.html b/DOC/src/html/ex_sonar_ranger.html new file mode 100644 index 0000000..8edb9c2 --- /dev/null +++ b/DOC/src/html/ex_sonar_ranger.html @@ -0,0 +1,164 @@ + + + + + +Sonar ranger example + + +

The following code shows a method of reading a class of sonar +rangers.  These rangers requires a trigger pulse.  +Shortly after receiving a trigger they transmit a noise pulse and +set the echo line high.  When the echo is received the echo +line is set low.

+

SETUP

+fritzing diagram
+
+
+
+
+The ranger used is a SRF05 (check the pinouts, there are many +variants).
+
+The fritzing diagram shows the back of the ranger, i.e. pin 1 is +the rightmost.
+
+Pin 1 is 5V.
+Pin 2 is the trigger line.
+Pin 3 is the echo line.
+Pin 4 is out (unused).
+Pin 5 is ground.
+
+

photo of set-up

+

CODE

+#include <stdio.h>
+
+#include <pigpio.h>
+
+/*
+
+P1  Name  gpio    used for
+
+ 2  5V    ---     +5V
+ 6  GND   ---     +Ground
+24  CE0   8       +Sonar echo
+26  CE1   7       +Sonar trigger
+
+*/
+
+#define SONAR_TRIGGER 7
+#define SONAR_ECHO    8
+
+/* forward prototypes */
+
+void sonarTrigger(void);
+
+void sonarEcho(int gpio, int level, uint32_t tick);
+
+int main(int argc, char *argv[])
+{
+   if (gpioInitialise()<0) return 1;
+
+   gpioSetMode(SONAR_TRIGGER, PI_OUTPUT);
+   gpioWrite  (SONAR_TRIGGER, PI_OFF);
+
+   gpioSetMode(SONAR_ECHO,    +PI_INPUT);
+
+   /* update sonar 20 times a second, timer #0 */
+
+   gpioSetTimerFunc(0, 50, sonarTrigger); /* every 50ms +*/
+
+   /* monitor sonar echos */
+
+   gpioSetAlertFunc(SONAR_ECHO, sonarEcho);
+
+   while (1) sleep(1);
+
+   gpioTerminate();
+
+   return 0;
+}
+
+void sonarTrigger(void)
+{
+   /* trigger a sonar reading */
+
+   gpioWrite(SONAR_TRIGGER, PI_ON);
+
+   gpioDelay(10); /* 10us trigger pulse */
+
+   gpioWrite(SONAR_TRIGGER, PI_OFF);
+}
+
+void sonarEcho(int gpio, int level, uint32_t tick)
+{
+   static uint32_t startTick, firstTick=0;
+
+   int diffTick;
+
+   if (!firstTick) firstTick = tick;
+
+   if (level == PI_ON)
+   {
+      startTick = tick;
+   }
+   else if (level == PI_OFF)
+   {
+      diffTick = tick - startTick;
+
+      printf("%u %u\ ", tick-firstTick, +diffTick);
+   }
+}
+

BUILD

+cc -o sonar sonar.c -lpigpio -lrt -lpthread
+

RUN

+sudo ./sonar >sonar.dat &
+
+While the program is running you can capture the waveform using the +notification feature built in to pigpio.  Issue the following +commands on the Pi.
+
+pigs no
+pig2vcd  </dev/pigpio0 >sonar.vcd &
+pigs nb 0 0x180 # set bits for gpios 7 and 8
+

Move an object in front of the sonar ranger for a few +seconds.

+pigs nc 0
+

The file sonar.vcd will contain the captured waveform, which can +be viewed using GTKWave.

+

Overview

+LDR waveform 1
+

Reading circa every 10ms

+Sonar waveform 2
+

One reading, circa 400us

+Sonar waveform 3
+

another

+Sonar waveform 4
+

The file sonar.dat will contain pairs of timestamps and echo +length (in us).  The following  script will convert the +timestamps into seconds.

+

awk '{print $1/1000000, $2}' sonar.dat +>sonar-secs.dat

+

Gnuplot is a useful tool to graph data.

+plot 'sonar-secs.dat' title 'Sonar'
+

gnuplot 1
+ plot [10:25] 'sonar-secs.dat' title 'Sonar'

+

gnuplot 1

+ + diff --git a/DOC/src/html/faq.html b/DOC/src/html/faq.html new file mode 100644 index 0000000..b8d6df5 --- /dev/null +++ b/DOC/src/html/faq.html @@ -0,0 +1,462 @@ + + + + + +faq + + +Are my GPIO broken?
+
+Audio is broken
+
+Can´t initialise pigpio +library
+
+Can´t lock +var/run/pigpio.pid
+
+Hello World!
+
+Clock skew, make fails
+
+Have I fried my GPIO?
+
+How do I debounce +inputs?
+
+How fast is SPI?
+
+Library update didn't work
+
+make fails with clock skew
+
+Porting pigpio to another CPU/SoC
+
+Sound isn't working
+
+Symbol not found
+
+What is I2C?
+
+What is Serial?
+
+What is SPI?
+
+Which library should I use?
+
+

Are my +GPIO broken?

+

See Have I fried my +GPIO?

+

Audio is +broken

+

See Sound isn't +working

+

Can´t lock +/var/run/pigpio.pid

+

See Can´t_initialise_pigpio_library
+

+

Can´t initialise pigpio +library

+

This message means the pigpio daemon is already running.

+

The default daemon is called pigpiod and may be removed as +follows.

+Check that it is running with the command +

ps aux | grep pigpiod

+

Kill the daemon with

+

sudo killall pigpiod

+

If your own program is acting as the daemon it may be removed as +follows.

+

Find its process id (pid).

+

cat /var/run/pigpio.pid

+

Kill the program with

+

sudo kill -9 pid

+If the above doesn't work do the following and try starting the +daemon again +

sudo rm /var/run/pigpio.pid

+

To start the daemon do

+

sudo pigpiod

+

Have I fried my GPIO?

+

If you think you have damaged one or more GPIO you can carry out +a diagnostic test.

+

The test is a command line script called gpiotest

+For the duration of the test nothing must be connected to the GPIO +(no LEDs, wires, ribbon cables etc.). +

The test checks that each GPIO may be read and written and that +the internal resistor pull-ups and pull-downs are functional.

+

A video +showing what happens to the GPIO during a test.

+

A test with all GPIO okay.

+
This program checks the Pi's (user) gpios.
+
+The program reads and writes all the gpios.  Make sure NOTHING
+is connected to the gpios during this test.
+
+The program uses the pigpio daemon which must be running.
+
+To start the daemon use the command sudo pigpiod.
+
+Press the ENTER key to continue or ctrl-C to abort...
+
+Testing...
+Skipped non-user gpios: 0 1 28 29 30 31 
+Tested user gpios: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 +Failed user gpios: None +
+

A test showing failed GPIO.

+
This program checks the Pi's (user) gpios.
+
+The program reads and writes all the gpios. Make sure NOTHING
+is connected to the gpios during this test.
+
+The program uses the pigpio daemon which must be running.
+
+To start the daemon use the command sudo pigpiod.
+
+Press the ENTER key to continue or ctrl-C to abort...
+
+Testing...
+Write 1 to gpio 17 failed.
+Pull up on gpio 17 failed.
+Write 1 to gpio 18 failed.
+Pull up on gpio 18 failed.
+Write 0 to gpio 23 failed.
+Pull down on gpio 23 failed.
+Write 0 to gpio 24 failed.
+Pull down on gpio 24 failed.
+Write 1 to gpio 27 failed.
+Pull up on gpio 27 failed.
+Skipped non-user gpios: 0 1 28 29 30 31
+Tested user gpios: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 +Failed user gpios: 17 18 23 24 27 +
+

How do I debounce inputs?

+

Some devices like mechanical switches can generate multiple +interrupts as they bounce between on and off.  It is possible +to debounce the inputs in hardware by the correct use of resistors +and capacitors.

+

In software use the glitch filter which ignores all events +shorter than a set number of microseconds.  C gpioGlitchFilter, Python set_glitch_filter.

+

How fast is +SPI?

+The SPI throughput in samples per second depends on a number of +factors.
+
+
    +
  • The SPI bit rate (transfer rate in bits per second)
  • +
+
    +
  • The number of bytes transferred per sample (a 12 bit ADC sample +may require 3 bytes to transfer)
  • +
+
    +
  • The driver used
  • +
+

Two of those factors are fixed, the variable is the driver +used.

+

The pigpio driver is considerably faster than the Linux SPI +driver as is demonstrated by the following graphs.

+

Each graph shows the SPI bit rate in bits per second along the +horizontal axis.  The samples per second achieved is shown on +the vertical axis.  Each graph contains plots assuming 1 to 5 +bytes per transfer.

+

The source code used for the tests is spi-driver-speed.c and spi-pigpio-speed.c

+

spi-lnx-pibr1.png

+
+

spi-pig-pibr1.png

+
+

spi-lnx-pi3b.png

+
+

spi-pig-pi3b.png

+

Library update didn't work

+

pigpio places files in the following locations

+

/usr/local/include (pigpio.h, pigpiod_if.h, pigpiod_if2.h)
+/usr/local/lib (libpigpio.so, libpigpiod_if.so, +libpigpiod_if2.so)
+/usr/local/bin (pig2vcd, pigpiod, pigs)
+/usr/local/man (man pages)

+The raspberrypi.org image containing pigpio uses different +locations.
+

/usr/include (pigpio.h, pigpiod_if.h, pigpiod_if2.h)
+/usr/lib (libpigpio.so, libpigpiod_if.so, libpigpiod_if2.so)
+/usr/bin (pig2vcd, pigpiod, pigs)
+/usr/man (man pages)

+

Mostly this doesn't matter as the /usr/local directories will +generally be earlier in the search path.  The pigpio built +includes, binaries, and manuals are normally found first.

+

However the wrong libraries may be linked during the +compilation.  If this is the case remove the /usr/lib entries +for libpigpio.so , libpigpiod_if.so, and libpigpiod_if2.so

+

Hello World!

+

The following examples show how to use the various components of +the pigpio library.

+

Each example shows how to read the level of a GPIO.

+

C

+read_cif.c +
+#include <stdio.h>
+#include <pigpio.h>
+
+int main(int argc, char *argv[])
+{
+   int GPIO=4;
+   int level;
+
+   if (gpioInitialise() < 0) return 1;
+
+   level = gpioRead(GPIO);
+
+   printf("GPIO %d is %d\n", GPIO, level);
+
+   gpioTerminate();
+}
+    
+

Build

+gcc -pthread -o read_cif read_cif.c -lpigpio +

Run

+sudo ./read_cif +

C via pigpio daemon

+read_pdif.c +
+#include <stdio.h>
+#include <pigpiod_if2.h>
+
+int main(int argc, char *argv[])
+{
+   int pi;
+   int GPIO=4;
+   int level;
+
+   pi = pigpio_start(0, 0); /* Connect to local Pi. */
+
+   if (pi < 0)
+   {
+      printf("Can't connect to pigpio daemon\n");
+      return 1;
+   }
+
+   level = gpio_read(pi, GPIO);
+
+   printf("GPIO %d is %d\n", GPIO, level);
+
+   pigpio_stop(pi); /* Disconnect from local Pi. */
+   
+   return 0;
+}
+
+

Build

+gcc -pthread -o read_pdif read_pdif.c -lpigpiod_if2 +

Run

+./read_pdif +

Python

+read_gpio.py +
+#!/usr/bin/env python
+
+import pigpio
+
+GPIO=4
+
+pi = pigpio.pi()
+if not pi.connected:
+   exit()
+
+level = pi.read(GPIO)
+
+print("GPIO {} is {}".format(GPIO, level))
+
+pi.stop()
+    
+

Run

+python read_gpio.py +

pigs

+
+pigs r 4
+    
+

pipe I/F

+
+echo "r 4" >/dev/pigpio
+cat /dev/pigout
+    
+

make fails with clock +skew

+

If make fails with one of the following messages it is probably +because the Pi's clock is wrong.

+

make: Warning: File 'xxx' has modification time x s in the +future
+make: warning: Clock skew detected. Your build may be +incomplete.

+

make uses the current time to work out which files need to be +rebuilt (a file is rebuilt if it depends on other files which have +a later time-stamp).

+

The solution is to make sure the system clock is correct.  +If the Pi is networked this will not normally be a problem.

+

To set the date and time use the date command as in the +following example.

+

sudo date -d "2017-03-01 18:47:00"

+

Porting pigpio +to another CPU/SoC

+

Sound +isn't working

+

The Pi contains two pieces of hardware, a PWM peripheral and a +PCM peripheral, to generate sound.  The PWM peripheral is +normally used and generates medium quality audio out of the +headphone jack.  The PCM peripheral may be used by add-ons +such as HATs and generates high quality audio.

+

pigpio uses at least one of these peripherals during normal +operation (for timing DMA transfers).  pigpio will use both +peripherals if waves or the hardware PWM function is used.

+

By default pigpio uses the PCM peripheral leaving the PWM +peripheral free for medium quality audio.

+

You can change the default with a configuration option.  +For C use gpioCfgClock, for the +pigpio daemon use the -t option.

+

What is I2C?

+

I2C is a data link between the Pi (master) and one or more +slaves.

+

Data may be sent and received but the Pi initiates all +transfers.

+

I2C is a medium speed link.  On the Pi the default speed is +100 kbps, but 400 kbps also works.

+

I2C is implemented as a bus with two lines called

+
    +
  • SDA - for data
  • +
  • SCL - for a clock
  • +
+On the Pi bus 1 is used which uses GPIO 2 (pin 3) for SDA and GPIO +3 (pin 5) for SCL.
+
+Only one slave device may be communicated with at a time.  +Each message from the Pi includes the slave to be addressed and +whether a read or write is to be performed.
+
+When the Pi (master) wishes to talk to a slave it begins by issuing +a start sequence on the I2C bus. A start sequence is one of two +special sequences defined for the I2C bus, the other being the stop +sequence. The start sequence and stop sequence are special in that +these are the only places where the SDA (data line) is allowed to +change while the SCL (clock line) is high. When data is being +transferred, SDA must remain stable and not change whilst SCL is +high. The start and stop sequences mark the beginning and end of a +transaction with the slave device.
+
+I2C start and stop sequences
+
+Data is transferred in 8-bit bytes. The bytes are placed on the SDA +line starting with the most significant bit. The SCL line is then +pulsed high, then low. For every byte transferred, the device +receiving the data sends back an acknowledge bit, so there are +actually 9 SCL clock pulses to transfer each 8-bit byte of data. If +the receiving device sends back a low ACK bit, then it has received +the data and is ready to accept another byte. If it sends back a +high then it is indicating it cannot accept any further data and +the master should terminate the transfer by sending a stop +sequence.
+
+

I2C waveform

+

What is +Serial?

+

Serial is a data link between the Pi and one other +device.

+

Data may be sent and received.  Either the Pi or the device +can initiate a transfer.

+

Serial is a low to medium speed link.  On the Pi speeds of +50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, +19200, 38400, 57600, 115200, and 230400 bps may be used.

+

Serial is implemented with one line for transmit called TXD and +one line for receive called RXD.

+

If only receive or transmit are required the other line need not +be connected.

+

The Pi uses GPIO 14 (pin 8) for TXD and GPIO 15 (pin 10) for +RXD.

+

Data is normally transmitted in 8-bit bytes with a start bit, +eight data bits, no parity, and one stop bit.  This is +represented as 8N1.  The number of transmitted bits per second +(bps) is called the baud rate.   The time for each bit, +1 / baud rate seconds, is +referred to as the bit period.

+

The lines are in the high state when no data is being +transmitted.  The start of a byte is signalled by the line +going low for one bit period (the start bit).  The data bits +are then sent least significant bit firsts (low if the bit is 0, +high if the bit is 1).  The data bits are followed by the +optional parity bit.  Finally the line is set high for at +least the number of stop bit periods.  The line will stay high +if there are no more bytes to be transmitted.

+

Serial waveform

+

What is SPI?

+

SPI is a data link between the Pi (master) and one or more +slaves.

+

Data may be sent and received but the Pi initiates all +transfers.

+

SPI is a medium to high speed link.  On the Pi speeds of 32 +kbps to 8 Mbps may be used.

+

SPI is implemented as a bus with three lines called

+
    +
  • MOSI - for data from the Pi to the slave
  • +
  • MISO - for data from the slave to the Pi
  • +
  • SCLK - for a clock
  • +
+Only one slave device may be communicated with at a time.  An +additional line per slave called slave select is used to identify +the slave to be addressed. +

The Pi has two SPI buses

+
    +
  1. the main SPI bus +
      +
    • MOSI GPIO 10 (pin 19)
    • +
    • MISO GPIO 9 (pin 21)
    • +
    • SCLK GPIO 11 (pin 23)
    • +
    • Slave selects
    • +
    • +
        +
      • CE0 GPIO 8 (pin 24)
      • +
      • CE1 GPIO 7 (pin 26)
      • +
      +
    • +
    +
  2. +
  3. the auxiliary SPI bus +
      +
    • MOSI GPIO 20 (pin 38)
    • +
    • MISO GPIO 19 (pin 35)
    • +
    • SCLK GPIO 21 (pin 40)
    • +
    • Slave selects
    • +
    • +
        +
      • CE0 GPIO 18 (pin 12)
      • +
      • CE1 GPIO 17 (pin 11)
      • +
      • CE2 GPIO 16 (pin 36)
      • +
      +
    • +
    +
  4. +
+

SPI waveform

+


+

Which library +should I use?

+


+ + diff --git a/DOC/src/html/index.html b/DOC/src/html/index.html new file mode 100644 index 0000000..b607206 --- /dev/null +++ b/DOC/src/html/index.html @@ -0,0 +1,676 @@ + + + + + +pigpio + + +pigpio is a library for the Raspberry which allows control of the +General Purpose Input Outputs (GPIO).  pigpio works on all +versions of the Pi. +

Download

+

Features

+
    +
  • +

    hardware timed sampling and time-stamping of GPIO 0-31 every 5 +us

    +
  • +
  • +

    hardware timed PWM on all of GPIO 0-31

    +
  • +
  • +

    hardware timed servo pulses on all of GPIO 0-31

    +
  • +
  • +

    callbacks on GPIO 0-31 level change (time accurate to a few +us)

    +
  • +
  • +

    notifications via pipe on GPIO 0-31 level change

    +
  • +
  • +

    callbacks at timed intervals

    +
  • +
  • +

    reading/writing all of the GPIO in a bank (0-31, 32-53) as a +single operation

    +
  • +
  • +

    GPIO reading, writing, modes, and internal pulls

    +
  • +
  • +

    socket and pipe interfaces for the bulk of the functionality

    +
  • +
  • +

    waveforms to generate GPIO level changes (time accurate to a few +us)

    +
  • +
  • +

    software serial links using any user GPIO

    +
  • +
  • +

    rudimentary permission control through the socket and pipe +interfaces

    +
  • +
  • creating and running scripts on the pigpio daemon
  • +
+

General

+The pigpio library is written in the C +programming language.
+
+The pigpio daemon offers a socket and pipe interface to +the underlying C library.
+
+A C library and a Python module allow control of the GPIO via the +pigpio daemon.
+
+There is third party support for a number of other languages.  +

piscope

+

piscope is a logic analyser (digital +waveform viewer).

+piscope is a GTK+3 application and uses pigpio to provide raw GPIO +level data.  piscope may be run on a Pi or on any machine +capable of compiling a GTK+3 application. +

GPIO

+

ALL GPIO are identified +by their Broadcom +number.  See +elinux.org

+There are 54 GPIO in total, arranged in two banks.
+

Bank 1 contains GPIO 0-31.  Bank 2 contains GPIO +32-53.

+For all types of Pi it is safe to read all the GPIO. If you try to +write a system GPIO or change its mode you can crash the Pi or +corrupt the data on the SD card.
+
+There are several types of board, each with different expansion +headers, giving physical access to different GPIO.  + +

Type 1 - Model B (original +model)

+
    +
  • 26 pin header (P1).
  • +
+
    +
  • Hardware revision numbers of 2 and 3.
  • +
+
    +
  • User GPIO 0-1, 4, 7-11, 14-15, 17-18, 21-25.
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+GPIOpinpin +GPIO
3V3-12-5V
SDA0
34-5V
SCL1
56-Ground

47814TXD
Ground-91015RXD
ce117111218ce0

211314-Ground

22151623
3V3-
171824
MOSI101920-Ground
MISO9212225
SCLK1123248CE0
Ground-25267CE1
+
+

Type 2 - Model A, B (revision +2)

+26 pin header (P1) and an additional 8 pin header (P5). +
    +
  • Hardware revision numbers of 4, 5, 6 (B), 7, 8, 9 (A), and 13, +14, 15 (B).
  • +
+
    +
  • User GPIO 2-4, 7-11, 14-15, 17-18, 22-25, 27-31.
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+GPIOpinpin +GPIO
3V3-12-5V
SDA234-5V
SCL356-Ground

47814TXD
Ground-91015RXD
ce117111218ce0

271314-Ground

22151623
3V3-
171824
MOSI101920-Ground
MISO9212225
SCLK1123248CE0
Ground-25267CE1
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+GPIOpinpin +GPIO
5V
-12-3V3
SDA
283429SCL

305631
Ground
-
78-
Ground
+
+

Type 3 - Model A+, B+, Pi +Zero, Pi Zero W, Pi2B, Pi3B, Pi4B

+
    +
  • 40 pin expansion header (J8).
  • +
+
    +
  • Hardware revision numbers of 16 or greater.
  • +
+
    +
  • User GPIO 2-27 (0 and 1 are reserved).
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+GPIOpinpin +GPIO
3V3-12-5V
SDA234-5V
SCL356-Ground

47814TXD
Ground-91015RXD
ce117111218ce0

271314-Ground

22151623
3V3-
171824
MOSI101920-Ground
MISO9212225
SCLK1123248CE0
Ground-25267CE1
ID_SD027281ID_SC

52930-Ground

6313212

133334-Ground
miso19353616ce2

26373820mosi
Ground-394021sclk
+
+

Compute Module

+

All 54 GPIO may be physically accessed.  Some are reserved +for system use - refer to the Compute Module documentation.

+

Only GPIO 0-31 are supported for hardware timed sampling, PWM, +servo pulses, alert callbacks, waves, and software serial +links.

+

Other +Languages

+

There are several third party projects which provide wrappers +for pigpio.

+

Some are listed here:

+
    + +
  • Docker +Note that pigpio does not support or accept issues relating to problems of running in docker. Use the docker projects own issue tracker for that (zinen)
  • + +
  • Erlang(skvamme)
  • + +
  • Forth(skvamme)
  • + +
  • Java JNI +wrapper around the pigpio C library (mattlewis)
  • + +
  • Java via +diozero, a high level wrapper around pigpio, Pi4J, wiringPi etc +(mattlewis)
  • + +
  • Java +(nkolban)
  • + +
  • .NET/mono +(unosquare)
  • + +
  • Node.js +A wrapper for the pigpio C library (fivdi)
  • + +
  • Node.js +A client for pigpio socket interface (guymcswain)
  • + +
  • Perl (Gligan +Calin Horea)
  • + +
  • Ruby +(Nak)
  • + +
  • Smalltalk(Instantiations)
  • + +
  • Xojo(UBogun)
  • + +
  • Xojo(Eugene Dakin)
  • + +
+
+

The PWM and servo pulses are timed using the DMA +and PWM/PCM peripherals.  This use was inspired by Richard +Hirst's servoblaster kernel module.

+ + diff --git a/DOC/src/html/misc.html b/DOC/src/html/misc.html new file mode 100644 index 0000000..4c6f305 --- /dev/null +++ b/DOC/src/html/misc.html @@ -0,0 +1,33 @@ + + + + + +Miscellaneous + + +There are two C libraries which provide a socket interface to the +pigpio daemon.  They provide an interface very similar to the +pigpio Python module.
+
    +
  • The original pigpiod_if library is +now deprecated and will no longer be updated.  This library is +limited to controlling one Pi at a time.
  • +
+
    +
  • The new pigpiod_if2 library which +should be used for new code.  This library allows multiple Pis +to be controlled at one time.
  • +
+Additional details of the pigpio socket +interface.
+
+Additional details of the pigpio pipe +interface.
+
+pig2vcd is a utility which converts +pigpio notifications into the VCD (Value Change Dump) format.  +VCD can be read by many programs, in particular GTKWave. + + diff --git a/DOC/src/html/pif.html b/DOC/src/html/pif.html new file mode 100644 index 0000000..bc924ff --- /dev/null +++ b/DOC/src/html/pif.html @@ -0,0 +1,30 @@ + + + + + +Pipe interface + + +pigpio provides a pipe interface to many of its functions.
+
+The pipe interface is available whenever pigpio is running, either +because it has been started as a daemon, or it has been linked in +to a running user program.  The pipe interface can be disabled +by the program which initialises the library.  pigpiod offers +the -f option to disable the pipe interface.  User programs +should call gpioCfgInterfaces +if they wish to disable the pipe interface.
+
+pigpio listens for commands on pipe /dev/pigpio.  The commands +consist of a command identifier with, depending on the command, +zero, one, or two parameters.  The result, if any, may be read +from pipe /dev/pigout.  If any errors are detected a message +will be written to pipe /dev/pigerr.
+
+
+The format of the commands is identical to those used by pigs. + + diff --git a/DOC/src/html/piscope.html b/DOC/src/html/piscope.html new file mode 100644 index 0000000..c381057 --- /dev/null +++ b/DOC/src/html/piscope.html @@ -0,0 +1,216 @@ + + + + + +piscope + + +

Introduction

+piscope is a logic analyser (digital +waveform viewer) for the Raspberry.  It shows the state (high +or low) of selected GPIO in real-time.
+
+See video.
+
+piscope uses the services of the pigpio library.  pigpio needs to be running on +the Pi whose GPIO are to be monitored.
+
+The pigpio library may be started as a daemon (background process) +by the following command.
+
+sudo pigpiod

+piscope may be invoked in several different ways
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Pi
pi_host ~ $ piscope +&
Pi captures +data
+Pi processes data
+Pi displays data
Pi plus Linux PC
+
+(with the
+display on a remote
+  Linux PC)
remote_host ~ $ ssh -X pi_host
pi_host ~ $ piscope +&
Pi captures data
+Pi processes data
+Remote Linux PC displays data
Pi plus Windows PC
+
+(with the
+display on a remote
+  Windows PC)
You need to install an SSH +client (putty suggested) and a X11 server (xming suggested).
+
+Run Program Files -> Xming -> XLaunch and accept the +defaults.
+
+Run putty and enter the Pi's host name or IP address.  Click +on SSH X11 and tick Enable X11 forwarding and then select +Open.

+
pi_host ~ $ piscope +&
Pi captures data
+Pi processes data
+Remote Windows PC displays data
Pi plus Linux PC
+
+(with the display and processing on a remote Linux +PC)
remote_host ~ $ export +PIGPIO_ADDR=pi_host
+remote_host ~ $ piscope +&
Pi captures data
+Remote processes data
+Remote displays data
+
+piscope operates in one of three modes
+
+ + + + + + + + + + + + + + + + + + +
Live
The latest GPIO samples are +displayed.
+
+The mode will automatically change to Pause if a sampling trigger +is detected.
+
+There are four triggers.  Each trigger is made up of a +combination of GPIO states (one of don't care, low, high, edge, +falling, or rising per GPIO).  Triggers are always +counted.  In addition a trigger may be sample to, sample +around, or sample from, a so called sampling trigger.
New samples are added to the +sample buffer.
+
+Once the sample buffer is full the oldest samples are discarded.
Play
Recorded GPIO samples are +displayed.
+
+The play speed may be varied between 64 times real-time to 1/32768 +of real-time.
+
+The page up key increases the play speed by a factor of 2.  +The page down key decreases the play speed by a factor of 2.  +The home key sets the play speed to 1X.
New samples are added to the +sample buffer.
+
+Once the sample buffer is full new samples are discarded.
Pause
Recorded GPIO samples are +displayed.
+
+The left and right cursor keys move the blue marker to the previous +or next edge.  By default all GPIO edges are considered.  +Clicking on a GPIO name will limit edge searches to the highlighted +GPIO only.
+
+The left and right square bracket keys move the blue marker to the +previous or next trigger.
+
+The time between the blue and gold markers is displayed.  The +gold marker is set to the blue marker by a press of the 'g' +key.
New samples are added to the +sample buffer.
+
+Once the sample buffer is full new samples are discarded.
+
+In all modes the down and up cursor keys zoom the time scale in and +out.
+
+Samples can be saved with File Save All Samples or File Save +Selected Samples. +

To select samples enter pause mode. Press 1 to specify the start +of the samples (green marker) and 2 to specify the end of the +samples (red marker).

+

The samples may be saved in the native piscope format or in VCD +format.

+

Data saved in VCD format may be viewed and further processed +with GTKWave.

+

Data saved in the native piscope format may be restored later +with File Restore Saved Data.

+

Installation

+

To download and install piscope.

+

Pi (pre-built image)

+wget abyz.me.uk/rpi/pigpio/piscope.tar
+tar xvf piscope.tar
+cd PISCOPE
+make hf
+make install

+

Linux 64 bit X86/AMD (pre-built image)

+wget abyz.me.uk/rpi/pigpio/piscope.tar
+tar xvf piscope.tar
+cd PISCOPE
+make x86_64
+make install
+

All machines (building from source)

+You only need to perform this step if you want to build the +executable from the source files.  This is not needed if you +use a pre-built image.
+
+WARNING
: Installing gtk+-3.0 uses a lot of SD card +space.
+
+Most of the space used by gtk+-3.0 is taken up by unneeded *-dbg +packages.
+
+With *-dbg packages an additional 3753MB SD space is required.
+
+If you edit the list of packages to be downloaded and remove the +*-dbg packages only 134MB of additional SD space is needed (as at +the time of writing).
+
+#
# *** This may take a lot of time and use +a lot of SD card space ***
#
+sudo apt-get install gtk+-3.0
#
+wget abyz.me.uk/rpi/pigpio/piscope.tar
+tar xvf piscope.tar
+cd PISCOPE
+make
+make install

+ + diff --git a/DOC/src/html/sif.html b/DOC/src/html/sif.html new file mode 100644 index 0000000..67b880b --- /dev/null +++ b/DOC/src/html/sif.html @@ -0,0 +1,2004 @@ + + + + + +Socket interface + + +pigpio provides a socket interface to many of its functions.
+
+The socket interface is available whenever pigpio is running, +either because it has been started as a daemon, or it has been +linked in to a running user program.
+
+The socket interface can be disabled by the program which +initialises the library.  pigpiod offers the -k option to +disable the socket interface.  User programs should call +gpioCfgInterfaces if they +wish to disable the socket interface.
+
+pigpio listens for connections on port 8888 by default.  This +default may be overridden when pigpio starts by the gpioCfgSocketPort function +call.  The pigpio daemon uses this function to provide an +option to change the port number.
+
+The pigs utility is an example of using the socket interface from +C.
+

Request

+

pigpio expects messages of type cmdCmd_t immediately followed with an +extension for a few commands.
+
+The caller should fill in cmd, p1, p2, p3/res, and any extension as +needed.  p3 will always be zero unless the command requires an +extension in which case p3 will be the length in bytes of the +extension.
+
+The cmdCmd_t is echoed back with +the result, if any, in p3/res, and an extension immediately +afterwards for a few commands.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
COMMANDcmd
p1p2p3Extension
MODES0gpiomode0-
MODEG1gpio00-
PUD2gpiopud0-
READ3gpio00-
WRITE4gpiolevel0-
PWM5gpiodutycycle0-
PRS6gpiorange0-
PFS7gpiofrequency0-
SERVO8gpiopulsewidth0-
WDOG9gpiotimeout0-
BR110000-
BR211000-
BC112bits00-
BC213bits00-
BS114bits00-
BS215bits00-
TICK16000-
HWVER17000-
NO18000-
NB19handlebits0-
NP20handle00-
NC21handle00-
PRG22gpio00-
PFG23gpio00-
PRRG24gpio00-
HELP
25N/A
N/A
N/A
N/A
PIGPV26000-
WVCLR27000-
WVAG280012*XgpioPulse_t pulse[X]
WVAS29gpiobaud12+Xuint32_t databits
+uint32_t stophalfbits
+uint32_t offset
+uint8_t data[X]
N/A
30000-
N/A
31000-
WVBSY32000-
WVHLT33000-
WVSM34subcmd00-
WVSP35subcmd00-
WVSC36subcmd00-
TRIG37gpiopulselen4uint32_t level
PROC3800Xuint8_t text[X]
PROCD39script_id00-
PROCR40script_id04*X
uint32_t pars[X]
PROCS41script_id00-
SLRO42gpiobaud4uint32_t databits
SLR43gpiocount0-
SLRC44gpio00-
PROCP45script_id00-
MICS46micros00-
MILS47millis00-
PARSE48N/AN/A
N/A
N/A
WVCRE49000-
WVDEL50wave_id00-
WVTX51wave_id00-
WVTXR52wave_id00-
WVNEW53000-
I2CO54busdevice4uint32_t flags
I2CC55handle00-
I2CRD56handlecount0-
I2CWD57handle0Xuint8_t data[X]
I2CWQ58handlebit0-
I2CRS59handle00-
I2CWS60handlebyte0-
I2CRB61handleregister0-
I2CWB62handleregister4uint32_t byte
I2CRW63handleregister0-
I2CWW64handleregister4uint32_t word
I2CRK65handleregister
0-
I2CWK66handleregister
Xuint8_t bvs[X]
I2CRI67handleregister
4uint32_t num
I2CWI68handleregister
X
uint8_t bvs[X]
I2CPC69handleregister
4uint32_t word
I2CPK70handleregister
X
uint8_t data[X]
SPIO
71channelbaud4uint32_t flags
SPIC72handle00-
SPIR73handlecount0-
SPIW74handle0Xuint8_t data[X]
SPIX75handle0Xuint8_t data[X]
SERO76baudflagsXuint8_t device[X]
SERC77handle00-
SERRB78handle00-
SERWB79handlebyte0-
SERR80handlecount0-
SERW81handle0Xuint8_t data[X]
SERDA82handle00-
GDC
83
gpio
0
0
-
GPW
84
gpio
0
0
-
HC
85
gpio
frequency
0
-
HP
86
gpio
frequency
4
uint32_t dutycycle
CF1
87
arg1
arg2
X
uint8_t argx[X]
CF2
88
arg1
retMax
X
uint8_t argx[X]
BI2CC
89
sda
0
0
-
BI2CO
90
sda
scl
4
uint32_t baud
BI2CZ
91
sda
0
X
uint8_t data[X]
I2CZ
92
handle
0
X
uint8_t data[X]
WVCHA
93
0
0
X
uint8_t data[X]
SLRI
94
gpio
invert
0
-
CGI
95
0
0
0
-
CSI
96
config
0
0
-
FG
97
gpio
steady
0
-
FN
98
gpio
steady
4
uint32_t active
NOIB99000-
WVTXM
100
wave_id
mode
0
-
WVTAT
101
0
0
0
-
PADS
102
pad
strength
0
-
PADG
103
pad
0
0
-
FO
104
mode
0
X
uint8_t file[X]
FC
105
handle
0
0
-
FR
106
handle
count
0
-
FW
107
handle
0
X
uint8_t data[X]
FS
108
handle
offset
4
uint32_t from
FL
109
count
0
X
uint8_t pattern[X]
SHELL
110
len(name)
0
len(name)+
+1+
+len(string)
uint8_t name[len(name)]
+uint8_t null (0)
+uint8_t string[len(string)]
BSPIC
111
CS
0
0
-
BSPIO
112
CS
0
20
uint32_t MISO
+uint32_t MOSI
+uint32_t SCLK
+uint32_t baud
+uint32_t spi_flags
BSPIX
113
CS
0
X
uint8_t data[X]
BSCX
114
control
0
X
uint8_t data[X]
EVM
115
handle
bits
0
-
EVT
116
event
0
0
-
PROCU
117
script_id
0
4*X
uint32_t pars[X]
+

Response

+

The response has cmd/p1/p2 as in the request.  p3/res holds +the return value.  If the command returns additional values +they will be in the immediately following extension.

+Normally res should be treated as a 32 bit signed value and will be +greater than or equal to zero.  Upon failure res will be less +than 0 and contains an error code.
+

There are a few commands where the returned value should be +treated as a 32 bit unsigned value.  These commands can not +fail.  They are indicated with a * after the command +name.

+

Commands with an extension have the size of the extension in +bytes returned in res (or <0 on error as above).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
COMMANDcmd
p1
p2
res
Extension
MODES0-
-
0-
MODEG1-
-
mode
-
PUD2-
-
0-
READ3-
-
level
-
WRITE4-
-
0-
PWM5-
-
0-
PRS6-
-
0-
PFS7-
-
0-
SERVO8-
-
0-
WDOG9-
-
0-
BR1 *10-
-
bits
-
BR2 *11-
-
bits
-
BC112-
-
0-
BC213-
-
0-
BS114-
-
0-
BS215-
-
0-
TICK *
16-
-
tick
-
HWVER *
17-
-
version
-
NO18-
-
handle
-
NB19-
-
0-
NP20-
-
0-
NC21-
-
0-
PRG22-
-
range
-
PFG23-
-
frequency
-
PRRG24-
-
real range
-
HELP25-
-
N/A
N/A
PIGPV *
26-
-
version
-
WVCLR27-
-
0-
WVAG28-
-
wave pulses
-
WVAS29-
-
wave pulses
-
N/A
30-
-
-
-
N/A
31-
-
-
-
WVBSY32-
-
busy (1) or not busy (0)
-
WVHLT33-
-
0-
WVSM34-
-
wave micros
+wave micros - high
+wave micros - max
-
WVSP35-
-
wave pulses
+wave pulses - high
+wave pulses - max
-
WVSC36-
-
wave DMA CBs
+wave DMA CBs - high
+wave DMA CBs - max
-
TRIG37-
-
0
-
PROC38-
-
script id
-
PROCD39-
-
0-
PROCR40-
-
script status
-
PROCS41-
-
0-
SLRO42-
-
0
-
SLR43-
-
X
uint8_t data[X]
SLRC44-
-
0-
PROCP45-
-
44uint32_t script_status
+uint32_t pars[10]
MICS46-
-
0-
MILS47-
-
0-
PARSE48-
-
N/A
-
WVCRE49-
-
wave id
-
WVDEL50-
-
0-
WVTX51-
-
wave DMA CBs
-
WVTXR52-
-
wave DMA CBs
-
WVNEW53-
-
0-
I2CO54-
-
handle-
I2CC55-
-
0-
I2CRD56-
-
X
uint8_t data[X]
I2CWD57-
-
0
-
I2CWQ58-
-
0-
I2CRS59-
-
byte value
-
I2CWS60-
-
0-
I2CRB61-
-
byte value
-
I2CWB62-
-
0
-
I2CRW63-
-
word value
-
I2CWW64-
-
0
-
I2CRK65-
-
0-
I2CWK66-
-
0
-
I2CRI67-
-
X
uint8_t data[X]
I2CWI68-
-
0
-
I2CPC69-
-
word value
-
I2CPK70-
-
X
uint8_t data[X]
SPIO
71-
-
handle
-
SPIC72-
-
0-
SPIR73-
-
X
uint8_t data[X]
SPIW74-
-
0
-
SPIX75-
-
Xuint8_t data[X]
SERO76-
-
handle
-
SERC77-
-
0-
SERRB78-
-
byte value
-
SERWB79-
-
0-
SERR80-
-
X
uint8_t data[X]
SERW81-
-
0
-
SERDA82-
-
data ready count
-
GDC
83
-
-
dutycycle
-
GPW
84
-
-
pulsewidth
-
HC
85
-
-
0
-
HP
86
-
-
0
-
CF1
87
-
-
value
-
CF2
88
-
-
X
uint8_t retBuf[X]
BI2CC
89
-
-
0
-
BI2CO
90
-
-
handle
-
BI2CZ
91
-
-
X
uint8_t data[X]
I2CZ
92
-
-
X
uint8_t data[X]
WVCHA
93
-
-
0
-
SLRI
94
-
-
0
-
CGI
95
-
-
config
-
CSI
96
-
-
0
-
FG
97
-
-
0
-
FN
98
-
-
0
-
NOIB99-
-
0-
WVTXM
100
-
-
wave DMA CBs
-
WVTAT
101
-
-
wave id
-
PADS
102
-
-
0
-
PADG
103
-
-
strength
-
FO
104
-
-
handle
-
FC
105
-
-
0
-
FR
106
-
-
X
uint8_t data[X]
FW
107
-
-
0
-
FS
108
-
-
position
-
FL
109
-
-
X
uint8_t filenames[X]
SHELL
110
-
-
exit status
-
BSPIC
111
-
-
0
-
BSPIO
112
-
-
0
-
BSPIX
113
-
-
X
uint8_t data[X]
BSCX
114
-
-
X+4
uint32_t status
+uint8_t data[X]
EVM
115
-
-
0
-
EVT
116
-
-
0
-
PROCU
117
-
-
0
-
+
+

cmdCmd_t

+typedef struct
+{
+   uint32_t cmd;
+   uint32_t p1;
+   uint32_t p2;
+   union
+   {
+      uint32_t p3;
+      uint32_t ext_len;
+      uint32_t res;
+   };
+} cmdCmd_t;

+ + diff --git a/EXAMPLES/Python/SENT_PROTOCOL/README.md b/EXAMPLES/Python/SENT_PROTOCOL/README.md new file mode 100644 index 0000000..8f3c83b --- /dev/null +++ b/EXAMPLES/Python/SENT_PROTOCOL/README.md @@ -0,0 +1,28 @@ +# Python Class for Reading Single Edge Nibble Transmission (SENT) using the Raspberry Pi + +A full description of this Python script is described at [www.surfncircuits.com](https://surfncircuits.com) in the blog entry: [Implementing a Single Edge Nibble Transmission (SENT) protocol in Python for the Raspberry Pi Zero](https://surfncircuits.com/?p=3725) + + +This python library will read a Raspberry Pi GPIO pin connected. Start the pigpiod daemon with one microsecond sampling to read SENT transmissions with three microsecond tick times. + +## To start the daemon on Raspberry Pi +- sudo pigpiod -s 1 + +## SENT packet frame summary + +- Sync Pulse: 56 ticks +- 4 bit Status and Message Pulse: 17-32 ticks +- 4 bit (9:12) Data1 Field: 17-32 ticks +- 4 bit (5:8) Data1 Field: 17-32 ticks +- 4 bit (1:4) Data1 Field: 17-32 ticks +- 4 bit (9-12) Data2 Field: 17-32 ticks +- 4 bit (5-8) Data2 Field: 17-32 ticks +- 4 bit (1-4) Data2 Field: 17-32 ticks +- 4 bit CRC: 17-32 ticks + + +## requirements +[pigpiod](http://abyz.me.uk/rpi/pigpio/) library required + +## To run the script for a signal attached to GPIO BCD 18 (pin 12) +- python3 sent_READ.py diff --git a/EXAMPLES/Python/SENT_PROTOCOL/read_SENT.py b/EXAMPLES/Python/SENT_PROTOCOL/read_SENT.py new file mode 100644 index 0000000..1bc9709 --- /dev/null +++ b/EXAMPLES/Python/SENT_PROTOCOL/read_SENT.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 + +# read_PWM.py +# Public Domain by mark smith, www.surfncircuits.com +# blog:https://surfncircuits.com/2020/11/27/implementing-a-single-edge-nibble-transmission-sent-protocol-in-python-for-the-raspberry-pi-zero/ + +import time +import pigpio # http://abyz.co.uk/rpi/pigpio/python.html +import threading + +class SENTReader: + """ + A class to read short Format SENT frames + (see the LX3302A datasheet for a SENT reference from Microchip) + (also using sent transmission mode where ) + from wikiPedia: The SAE J2716 SENT (Single Edge Nibble Transmission) protocol + is a point-to-point scheme for transmitting signal values + from a sensor to a controller. It is intended to allow for + transmission of high resolution data with a low system cost. + + Short sensor format: + The first is the SYNC pulse (56 ticks) + first Nibble : Status (4 bits) + 2nd NIbble : DAta1 (4 bits) + 3nd Nibble : Data2 (4 bits) + 4th Nibble : Data3 (4 bits) + 5th Nibble : Data1 (4 bits) + 6th Nibble : Data2 (4 bits) + 7th Nibble : Data3 (4 bits) + 8th Nibble : CRC (4 bits) + """ + def __init__(self, pi, gpio, Mode = 0): + """ + Instantiate with the Pi and gpio of the SENT signal + to monitor. + SENT mode = A0: Microchip LX3302A where the two 12 bit data values are identical. there are other modes + + """ + self.pi = pi + self.gpio = gpio + self.SENTMode = Mode + + # the time that pulse goes high + self._high_tick = 0 + # the period of the low tick + self._low_tick = 0 + # the period of the pulse (total data) + self._period = 0 + # the time the item was low during the period + self._low = 0 + # the time the output was high during the period + self._high = 0 + # setting initial value to 100 + self.syncTick = 100 + + + #keep track of the periods + self.syncWidth = 0 + self.status = 0 + self.data1 = 0 + self.data2 = 0 + self.data3 = 0 + self.data4 = 0 + self.data5 = 0 + self.data6 = 0 + self.crc = 0 + #initize the sent frame . Need to use hex for data + #self.frame = [0,0,0,'0x0','0x0','0x0','0x0','0x0','0x0',0] + self.frame = [0,0,0,0,0,0,0,0,0,0] + self.syncFound = False + self.frameComplete = False + self.nibble = 0 + self.numberFrames = 0 + self.SampleStopped = False + + self.pi.set_mode(gpio, pigpio.INPUT) + + #self._cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cbf) + #sleep enougth to start reading SENT + #time.sleep(0.05) + + #start thread to sample the SENT property + # this is needed for piGPIO sample of 1us and sensing the 3us + self.OutputSampleThread = threading.Thread(target = self.SampleCallBack) + self.OutputSampleThread.daemon = True + self.OutputSampleThread.start() + + #give time for thread to start capturing data + time.sleep(.05) + + + def SampleCallBack(self): + + # this will run in a loop and sample the SENT path + # this sampling is required when 1us sample rate for SENT 3us tick time + while True: + + self.SampleStopped = False + self._cb = self.pi.callback(self.gpio, pigpio.EITHER_EDGE, self._cbf) + # wait until sample stopped + while self.SampleStopped == False: + #do nothing + time.sleep(.001) + + # gives the callback time to cancel so we can start again. + time.sleep(0.20) + + def _cbf(self, gpio, level, tick): + # depending on the system state set the tick times. + # first look for sync pulse. this is found when duty ratio >90 + #print(pgio) + #print("inside _cpf") + #print(tick) + if self.syncFound == False: + if level == 1: + self._high_tick = tick + self._low = pigpio.tickDiff(self._low_tick,tick) + elif level == 0: + # this may be a syncpulse if the duty is 51/56 + self._period = pigpio.tickDiff(self._low_tick,tick) + # not reset the self._low_tick + self._low_tick = tick + self._high = pigpio.tickDiff(self._high_tick,tick) + # sync pulse is detected by finding duty ratio. 51/56 + # but also filter if period is > 90us*56 = 5040 + if (100*self._high/self._period) > 87 and (self._period<5100): + self.syncFound = True + self.syncWidth = self._high + self.syncPeriod = self._period + #self.syncTick = round(self.syncPeriod/56.0,2) + self.syncTick = self.syncPeriod + # reset the nibble to zero + self.nibble = 0 + self.SampleStopped = False + else: + # now look for the nibble information for each nibble (8 Nibbles) + if level == 1: + self._high_tick = tick + self._low = pigpio.tickDiff(self._low_tick,tick) + elif level == 0: + # This will be a data nibble + self._period = pigpio.tickDiff(self._low_tick,tick) + # not reset the self._low_tick + self._low_tick = tick + self._high = pigpio.tickDiff(self._high_tick,tick) + self.nibble = self.nibble + 1 + if self.nibble == 1: + self.status = self._period + elif self.nibble == 2: + #self.data1 = hex(int(round(self._period / self.syncTick)-12)) + self.data1 = self._period + elif self.nibble == 3: + self.data2 = self._period + elif self.nibble == 4: + self.data3 = self._period + elif self.nibble == 5: + self.data4 = self._period + elif self.nibble == 6: + self.data5 = self._period + elif self.nibble == 7: + self.data6 = self._period + elif self.nibble == 8: + self.crc = self._period + # now send all to the SENT Frame + self.frame = [self.syncPeriod,self.syncTick,self.status,self.data1,self.data2,self.data3,self.data4,self.data5,self.data6,self.crc] + self.syncFound = False + self.nibble = 0 + self.numberFrames += 1 + if self.numberFrames > 2: + self.cancel() + self.SampleStopped = True + self.numberFrames = 0 + + def ConvertData(self,tickdata,tickTime): + if tickdata == 0: + t = '0x0' + else: + t = hex(int(round(tickdata / tickTime)-12)) + if t[0] =='-': + t='0x0' + return t + + def SENTData(self): + # check that data1 = Data2 if they are not equal return fault = True + # will check the CRC code for faults. if fault, return = true + # returns status, data1, data2, crc, fault + #self._cb = self.pi.callback(self.gpio, pigpio.EITHER_EDGE, self._cbf) + #time.sleep(0.1) + fault = False + SentFrame = self.frame[:] + SENTTick = round(SentFrame[1]/56.0,2) + + # the greatest SYNC sync is 90us. So trip a fault if this occurs + if SENTTick > 90: + fault = True + + #print(SentFrame) + # convert SentFrame to HEX Format including the status and Crc bits + for x in range (2,10): + SentFrame[x] = self.ConvertData(SentFrame[x],SENTTick) + SENTCrc = SentFrame[9] + SENTStatus = SentFrame[2] + SENTPeriod = SentFrame[0] + #print(SentFrame) + # combine the datafield nibbles + datanibble = '0x' + datanibble2 = '0x' + for x in range (3,6): + datanibble = datanibble + str((SentFrame[x]))[2:] + for x in range (6,9): + datanibble2 = datanibble2 + str((SentFrame[x]))[2:] + # if using SENT mode 0, then data nibbles should be equal + #if self.SENTMode == 0 : + # if datanibble != datanibble2: + # fault = True + # if datanibble or datanibble2 == 0 then fault = true + if (int(datanibble,16) == 0) or (int(datanibble2,16) ==0): + fault = True + # if datanibble or datanibble2 > FFF (4096) then fault = True + if ( (int(datanibble,16) > 0xFFF) or (int(datanibble2,16) > 0xFFF)): + fault = True + #print(datanibble) + # CRC checking + # converting the datanibble values to a binary bit string. + # remove the first two characters. Not needed for crcCheck + InputBitString = bin(int((datanibble + datanibble2[2:]),16))[2:] + # converting Crcvalue to bin but remove the first two characters 0b + # format is set to remove the leading 0b, 4 charactors long + crcBitValue = format(int(str(SENTCrc),16),'04b') + #checking the crcValue + # polybitstring is 1*X^4+1*X^3+1*x^2+0*X+1 = '11101' + if self.crcCheck(InputBitString,'11101',crcBitValue) == False: + fault = True + + # converter to decimnal + returnData = int(datanibble,16) + returnData2 = int(datanibble2,16) + #returns both Data values and if there is a FAULT + return (SENTStatus, returnData, returnData2,SENTTick, SENTCrc, fault, SENTPeriod) + + def tick(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return ticktime + + def crcNibble(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return crc + + def dataField1(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return data1 + + def dataField2(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return data2 + + def statusNibble(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return status + + def syncPulse(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return syncPulse + + def errorFrame(self): + status, data1, data2, ticktime, crc, errors, syncPulse = self.SENTData() + return errors + + def cancel(self): + self._cb.cancel() + + def stop(self): + self.OutputSampleThread.stop() + + def crcCheck(self, InputBitString, PolyBitString, crcValue ): + # the input string will be a binary string all 6 nibbles of the SENT data + # the seed value ( = '0101) is appended to the input string. Do not use zeros for SENT protocal + # this uses the SENT CRC recommended implementation. + checkOK = False + + LenPolyBitString = len(PolyBitString) + PolyBitString = PolyBitString.lstrip('0') + LenInput = len(InputBitString) + InputPaddedArray = list(InputBitString + '0101') + while '1' in InputPaddedArray[:LenInput]: + cur_shift = InputPaddedArray.index('1') + for i in range(len(PolyBitString)): + InputPaddedArray[cur_shift + i] = str(int(PolyBitString[i] != InputPaddedArray[cur_shift + i])) + + if (InputPaddedArray[LenInput:] == list(crcValue)): + checkOK = True + + return checkOK + +if __name__ == "__main__": + + import time + import pigpio + import read_SENT + + SENT_GPIO = 18 + RUN_TIME = 6000000000.0 + SAMPLE_TIME = 0.1 + + pi = pigpio.pi() + + p = read_SENT.SENTReader(pi, SENT_GPIO) + + start = time.time() + + while (time.time() - start) < RUN_TIME: + + time.sleep(SAMPLE_TIME) + + status, data1, data2, ticktime, crc, errors, syncPulse = p.SENTData() + print("Sent Status= %s - 12-bit DATA 1= %4.0f - DATA 2= %4.0f - tickTime(uS)= %4.2f - CRC= %s - Errors= %s - PERIOD = %s" % (status,data1,data2,ticktime,crc,errors,syncPulse)) + print("Sent Stat2s= %s - 12-bit DATA 1= %4.0f - DATA 2= %4.0f - tickTime(uS)= %4.2f - CRC= %s - Errors= %s - PERIOD = %s" % (p.statusNibble(),p.dataField1(),p.dataField2(),p.tick(),p.crcNibble(),p.errorFrame(),p.syncPulse())) + + # stop the thread in SENTReader + p.stop() + # clear the pi object instance + pi.stop() diff --git a/README.md b/README.md index 8727e74..e326fca 100644 --- a/README.md +++ b/README.md @@ -3,12 +3,6 @@ pigpio is a C library for the Raspberry which allows control of the General Purpose Input Outputs (GPIO). -**At the moment pigpio on the Pi4B is experimental. I am not sure if the DMA channels - being used are safe. The Pi4B defaults are primary channel 7, secondary channel 6. - If these channels do not work you will have to experiment. You can set the channels - used by the pigpio daemon by invoking it with the -d and -e options, e.g. - sudo pigpiod -d 5 -e 8 to specify primary 5, secondary 8.** - ## Features * Sampling and time-stamping of GPIO 0-31 between 100,000 and 1,000,000 times per second diff --git a/cmake/FindRT.cmake b/cmake/FindRT.cmake new file mode 100644 index 0000000..db7c4de --- /dev/null +++ b/cmake/FindRT.cmake @@ -0,0 +1,39 @@ +# FindRT.cmake - Try to find the RT library +# Once done this will define +# +# RT_FOUND - System has rt +# RT_INCLUDE_DIR - The rt include directory +# RT_LIBRARIES - The libraries needed to use rt +# RT_DEFINITIONS - Compiler switches required for using rt +# +# Also creates an import target called RT::RT + +find_path (RT_INCLUDE_DIR NAMES time.h + PATHS + /usr + /usr/local + /opt + PATH_SUFFIXES +) + +find_library(RT_LIBRARIES NAMES rt + PATHS + /usr + /usr/local + /opt +) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(rt DEFAULT_MSG RT_LIBRARIES RT_INCLUDE_DIR) + +mark_as_advanced(RT_INCLUDE_DIR RT_LIBRARIES) + +if (NOT TARGET RT::RT) + add_library(RT::RT INTERFACE IMPORTED) + + set_target_properties(RT::RT PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES ${RT_INCLUDE_DIR} + INTERFACE_LINK_LIBRARIES ${RT_LIBRARIES} + ) +endif() \ No newline at end of file diff --git a/cmake/pigpioConfig.cmake b/cmake/pigpioConfig.cmake new file mode 100644 index 0000000..7912526 --- /dev/null +++ b/cmake/pigpioConfig.cmake @@ -0,0 +1 @@ +include (${CMAKE_CURRENT_LIST_DIR}/pigpioTargets.cmake) \ No newline at end of file diff --git a/cmake/setup.py.in b/cmake/setup.py.in new file mode 100644 index 0000000..a5913a2 --- /dev/null +++ b/cmake/setup.py.in @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +from distutils.core import setup + +setup(name='pigpio', + version='1.44', + author='joan', + author_email='joan@abyz.me.uk', + maintainer='joan', + maintainer_email='joan@abyz.me.uk', + url='http://abyz.me.uk/rpi/pigpio/python.html', + description='Raspberry Pi GPIO module', + long_description='Raspberry Pi Python module to access the pigpio daemon', + download_url='http://abyz.me.uk/rpi/pigpio/pigpio.zip', + license='unlicense.org', + py_modules=['pigpio'], + keywords=['raspberrypi', 'gpio',], + classifiers=[ + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 3", + ], + package_dir={ '': '${CMAKE_CURRENT_SOURCE_DIR}'} + ) + diff --git a/command.c b/command.c index 4a1da4d..ffc3463 100644 --- a/command.c +++ b/command.c @@ -201,7 +201,8 @@ cmdInfo_t cmdInfo[]= {PI_CMD_WVBSY, "WVBSY", 101, 2, 1}, // gpioWaveTxBusy {PI_CMD_WVCHA, "WVCHA", 197, 0, 0}, // gpioWaveChain {PI_CMD_WVCLR, "WVCLR", 101, 0, 1}, // gpioWaveClear - {PI_CMD_WVCRE, "WVCRE", 101, 2, 1}, // gpioWaveCreate + {PI_CMD_WVCRE, "WVCRE", 101, 2, 1}, // gpioWaveCreate + {PI_CMD_WVCAP, "WVCAP", 112, 2, 1}, // gpioWaveCreatePad {PI_CMD_WVDEL, "WVDEL", 112, 0, 1}, // gpioWaveDelete {PI_CMD_WVGO, "WVGO" , 101, 2, 0}, // gpioWaveTxStart {PI_CMD_WVGOR, "WVGOR", 101, 2, 0}, // gpioWaveTxStart @@ -693,7 +694,7 @@ int cmdParse( case 112: /* BI2CC FC GDC GPW I2CC I2CRB MG MICS MILS MODEG NC NP PADG PFG PRG PROCD PROCP PROCS PRRG R READ SLRC SPIC - WVDEL WVSC WVSM WVSP WVTX WVTXR BSPIC + WVCAP WVDEL WVSC WVSM WVSP WVTX WVTXR BSPIC One positive parameter. */ diff --git a/pigpio.3 b/pigpio.3 index e218ed1..783bc92 100644 --- a/pigpio.3 +++ b/pigpio.3 @@ -189,6 +189,28 @@ error PI_INITIALISED. .br +.br +If you intend to rely on signals sent to your application, you should +turn off the internal signal handling as shown in this example: + +.br + +.br + +.EX +int cfg = gpioCfgGetInternals(); +.br +cfg |= PI_CFG_NOSIGHANDLER; // (1<<10) +.br +gpioCfgSetInternals(cfg); +.br +int status = gpioInitialise(); +.br + +.EE + +.br + .br .SH OVERVIEW @@ -584,6 +606,8 @@ gpioWaveAddSerial Adds serial data to the waveform .br gpioWaveCreate Creates a waveform from added data .br +gpioWaveCreatePad Creates a waveform of fixed size from added data +.br gpioWaveDelete Deletes a waveform .br @@ -687,8 +711,6 @@ gpioCfgMemAlloc Configure DMA memory allocation mode gpioCfgNetAddr Configure allowed network addresses .br -.br -gpioCfgInternals Configure misc. internals (DEPRECATED) .br gpioCfgGetInternals Get internal configuration settings .br @@ -1682,6 +1704,15 @@ will be a latency. .br +.br +If you want to track the level of more than one GPIO do so by +maintaining the state in the callback. Do not use \fBgpioRead\fP. +Remember the event that triggered the callback may have +happened several milliseconds before and the GPIO may have +changed level many times since then. + +.br + .br The tick value is the time stamp of the sample in microseconds, see \fBgpioTick\fP for more details. @@ -2653,6 +2684,89 @@ specified delay between the pulse and the next. Returns the new waveform id if OK, otherwise PI_EMPTY_WAVEFORM, PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL. +.IP "\fBint gpioWaveCreatePad(int pctCB, int pctBOOL, int pctTOOL)\fP" +.IP "" 4 +Similar to \fBgpioWaveCreate\fP, this function creates a waveform but pads the consumed +resources. Padded waves of equal dimension can be re-cycled efficiently allowing +newly created waves to re-use the resources of deleted waves of the same dimension. + +.br + +.br + +.EX +pctCB: 0-100, the percent of all DMA control blocks to consume. +.br +pctBOOL: 0-100, percent On-Off-Level (OOL) buffer to consume for wave output. +.br +pctTOOL: 0-100, the percent of OOL buffer to consume for wave input (flags). +.br + +.EE + +.br + +.br +Upon success a wave id greater than or equal to 0 is returned, otherwise +PI_EMPTY_WAVEFORM, PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID. + +.br + +.br +Waveform data provided by \fBgpioWaveAdd*\fP and \fBrawWaveAdd*\fP functions are +consumed by this function. + +.br + +.br +A usage would be the creation of two waves where one is filled while the other +is being transmitted. Each wave is assigned 50% of the resources. +This buffer structure allows the transmission of infinite wave sequences. + +.br + +.br +\fBExample\fP +.br + +.EX + // get firstWaveChunk, somehow +.br + gpioWaveAddGeneric(firstWaveChunk); +.br + wid = gpioWaveCreatePad(50, 50, 0); +.br + gpioWaveTxSend(wid, PI_WAVE_MODE_ONE_SHOT); +.br + // get nextWaveChunk +.br + +.br + while (nextWaveChunk) { +.br + gpioWaveAddGeneric(nextWaveChunk); +.br + nextWid = gpioWaveCreatePad(50, 50, 0); +.br + gpioWaveTxSend(nextWid, PI_WAVE_MODE_ONE_SHOT_SYNC); +.br + while(gpioWaveTxAt() == wid) time_sleep(0.1); +.br + gpioWaveDelete(wid); +.br + wid = nextWid; +.br + // get nextWaveChunk +.br + } +.br + +.EE + +.br + +.br + .IP "\fBint gpioWaveDelete(unsigned wave_id)\fP" .IP "" 4 This function deletes the waveform with id wave_id. @@ -2932,7 +3046,7 @@ int main(int argc, char *argv[]) .IP "\fBint gpioWaveTxAt(void)\fP" .IP "" 4 This function returns the id of the waveform currently being -transmitted. +transmitted using \fBgpioWaveTxSend\fP. Chained waves are not supported. .br @@ -4181,18 +4295,6 @@ queue and the master removes it. .br -.br -This function is not available on the BCM2711 (e.g. as -used in the Pi4B). - -.br - -.br -I can't get SPI to work properly. I tried with a -control word of 0x303 and swapped MISO and MOSI. - -.br - .br The function sets the BSC mode, writes any data in the transmit buffer to the BSC transmit FIFO, and @@ -4249,14 +4351,37 @@ that mode until a different control word is sent. .br .br -The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL) in I2C mode -and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO), and 21 (CE) in SPI mode. You -need to swap MISO/MOSI between master and slave. +GPIO used for models other than those based on the BCM2711. .br .br -When a zero control word is received GPIO 18-21 will be reset + SDA SCL MOSI SCLK MISO CE +.br +I2C 18 19 - - - - +.br +SPI - - 20 19 18 21 +.br + +.br + +.br +GPIO used for models based on the BCM2711 (e.g. the Pi4B). + +.br + +.br + SDA SCL MOSI SCLK MISO CE +.br +I2C 10 11 - - - - +.br +SPI - - 9 11 10 8 +.br + +.br + +.br +When a zero control word is received the used GPIO will be reset to INPUT mode. .br @@ -4364,7 +4489,7 @@ details. .br SSSSS number of bytes successfully copied to transmit FIFO .br -RRRRR number of bytes in receieve FIFO +RRRRR number of bytes in receive FIFO .br TTTTT number of bytes in transmit FIFO .br @@ -4423,6 +4548,23 @@ if (status >= 0) .EE +.br + +.br +The BSC slave in SPI mode deserializes data from the MOSI pin into its +receiver/FIFO when the LSB of the first byte is a 0. No data is output on +the MISO pin. When the LSB of the first byte on MOSI is a 1, the +transmitter/FIFO data is serialized onto the MISO pin while all other data +on the MOSI pin is ignored. + +.br + +.br +The BK bit of the BSC control register is non-functional when in the SPI +mode. The transmitter along with its FIFO can be dequeued by successively +disabling and re-enabling the TE bit on the BSC control register while in +SPI mode. + .IP "\fBint bbSPIOpen(unsigned CS, unsigned MISO, unsigned MOSI, unsigned SCLK, unsigned baud, unsigned spiFlags)\fP" .IP "" 4 This function selects a set of GPIO for bit banging SPI with @@ -5777,36 +5919,6 @@ PI_TOO_MANY_PARAM. param is an array of up to 10 parameters which may be referenced in the script as p0 to p9. -.IP "\fBint gpioRunScript(unsigned script_id, unsigned numPar, uint32_t *param)\fP" -.IP "" 4 -This function runs a stored script. - -.br - -.br - -.EX -script_id: >=0, as returned by \fBgpioStoreScript\fP -.br - numPar: 0-10, the number of parameters -.br - param: an array of parameters -.br - -.EE - -.br - -.br -The function returns 0 if OK, otherwise PI_BAD_SCRIPT_ID, or -PI_TOO_MANY_PARAM. - -.br - -.br -param is an array of up to 10 parameters which may be referenced in -the script as p0 to p9. - .IP "\fBint gpioUpdateScript(unsigned script_id, unsigned numPar, uint32_t *param)\fP" .IP "" 4 This function sets the parameters of a script. The script may or @@ -7785,22 +7897,6 @@ numSockAddr: 0-256 (0 means all addresses allowed) .EE -.IP "\fBint gpioCfgInternals(unsigned cfgWhat, unsigned cfgVal)\fP" -.IP "" 4 -Used to tune internal settings. - -.br - -.br - -.EX -cfgWhat: see source code -.br - cfgVal: see source code -.br - -.EE - .IP "\fBuint32_t gpioCfgGetInternals(void)\fP" .IP "" 4 This function returns the current library internal configuration @@ -7821,6 +7917,10 @@ cfgVal: see source code .EE +.br + +.br + .IP "\fBint gpioCustom1(unsigned arg1, unsigned arg2, char *argx, unsigned argc)\fP" .IP "" 4 This function is available for user customisation. @@ -9458,6 +9558,27 @@ An array of script parameters. .br +.IP "\fBpctBOOL\fP: 0-100" 0 +percent On-Off-Level (OOL) buffer to consume for wave output. + +.br + +.br + +.IP "\fBpctCB\fP: 0-100" 0 +the percent of all DMA control blocks to consume. + +.br + +.br + +.IP "\fBpctTOOL\fP: 0-100" 0 +the percent of OOL buffer to consume for wave input (flags). + +.br + +.br + .IP "\fBpi_i2c_msg_t\fP" 0 .EX @@ -10610,6 +10731,8 @@ A 16-bit word value. .br #define PI_CMD_PROCU 117 .br +#define PI_CMD_WVCAP 118 +.br .br diff --git a/pigpio.c b/pigpio.c index e30bc93..86a8507 100644 --- a/pigpio.c +++ b/pigpio.c @@ -25,7 +25,7 @@ OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to */ -/* pigpio version 74 */ +/* pigpio version 79 */ /* include ------------------------------------------------------- */ @@ -396,6 +396,7 @@ bit 0 READ_LAST_NOT_SET_ERROR #define DMA_DEST_WIDTH (1<< 5) #define DMA_DEST_INC (1<< 4) #define DMA_WAIT_RESP (1<< 3) +#define DMA_TDMODE (1<< 1) #define DMA_DEBUG_READ_ERR (1<<2) #define DMA_DEBUG_FIFO_ERR (1<<1) @@ -664,6 +665,7 @@ bit 0 READ_LAST_NOT_SET_ERROR /* --------------------------------------------------------------- */ #define NORMAL_DMA (DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP) +#define TWO_BEAT_DMA (DMA_TDMODE | DMA_BURST_LENGTH(1)) #define TIMED_DMA(x) (DMA_DEST_DREQ | DMA_PERIPHERAL_MAPPING(x)) @@ -948,6 +950,7 @@ typedef struct uint32_t nfRBitV; uint32_t gfSteadyUs; + uint8_t gfInitialised; uint32_t gfTick; uint32_t gfLBitV; uint32_t gfRBitV; @@ -1569,6 +1572,9 @@ int myPathBad(char *name) in_part = 0; last_char_dot = 0; + if (strstr(name, "..")) return 1; + if (strstr(name, "\\.")) return 1; + len = strlen(name); for (i=0; iinfo = TWO_BEAT_DMA; + p->src = waveOOLPOadr(botOOL); + waveSetOOL(botOOL++, waves[i].gpioOn); + s_stride = waveOOLPOadr(botOOL) - p->src; + waveSetOOL(botOOL++, waves[i].gpioOff); + p->dst = ((GPIO_BASE + (GPSET0*4)) & 0x00ffffff) | PI_PERI_BUS; + p->length = (2<<16) + 4; // 2 transfers of 4 bytes each + p->stride = (12<<16) + s_stride; // d_stride = (GPCLR0-GPSET0)*4 = 12 + p->next = waveCbPOadr(botCB); + } + if (waves[i].gpioOn && !waves[i].gpioOff) { waveSetOOL(botOOL, waves[i].gpioOn); @@ -3052,8 +3096,7 @@ static int wave2Cbs(unsigned wave_mode, int *CB, int *BOOL, int *TOOL) p->length = 4; p->next = waveCbPOadr(botCB); } - - if (waves[i].gpioOff) + if (waves[i].gpioOff && !waves[i].gpioOn) { waveSetOOL(botOOL, waves[i].gpioOff); @@ -3065,7 +3108,6 @@ static int wave2Cbs(unsigned wave_mode, int *CB, int *BOOL, int *TOOL) p->length = 4; p->next = waveCbPOadr(botCB); } - if (waves[i].flags & WAVE_FLAG_READ) { p = rawWaveCBAdr(botCB++); @@ -3130,6 +3172,28 @@ static int wave2Cbs(unsigned wave_mode, int *CB, int *BOOL, int *TOOL) } } + if (numCB) + { + /* Pad the wave */ + + botCB = *CB + numCB - 1; + botOOL = *BOOL + numBOOL - 1; + topOOL = *TOOL - numTOOL; + + /* Link the last CB to end of wave */ + + p->next = waveCbPOadr(botCB); + + /* Insert sentinel CB at end of DMA */ + + p = rawWaveCBAdr(botCB++); + p->info = NORMAL_DMA | DMA_DEST_IGNORE; + p->src = waveOOLPOadr(botOOL++); + p->dst = ((GPIO_BASE + (GPSET0*4)) & 0x00ffffff) | PI_PERI_BUS; + p->length = 4; + p->next = 0; + } + if (p != NULL) { if (wave_mode == PI_WAVE_MODE_ONE_SHOT) @@ -3324,9 +3388,7 @@ int rawWaveAddGeneric(unsigned numIn1, rawWave_t *in1) cbs += waveDelayCBs(tDelay); - if (out[outPos].gpioOn) cbs++; /* one cb if gpio on */ - - if (out[outPos].gpioOff) cbs++; /* one cb if gpio off */ + if (out[outPos].gpioOn || out[outPos].gpioOff) cbs++; if (out[outPos].flags & WAVE_FLAG_READ) { @@ -4054,7 +4116,7 @@ int i2cOpen(unsigned i2cBus, unsigned i2cAddr, unsigned i2cFlags) i2cInfo[slot].addr = i2cAddr; i2cInfo[slot].flags = i2cFlags; i2cInfo[slot].funcs = funcs; - i2cInfo[i].state = PI_I2C_OPENED; + i2cInfo[slot].state = PI_I2C_OPENED; return slot; } @@ -4768,7 +4830,7 @@ int spiClose(unsigned handle) if (spiInfo[handle].state != PI_SPI_OPENED) SOFT_ERROR(PI_BAD_HANDLE, "bad handle (%d)", handle); - spiInfo[handle].state = PI_I2C_CLOSED; + spiInfo[handle].state = PI_SPI_CLOSED; if (!spiAnyOpen(spiInfo[handle].flags)) spiTerm(spiInfo[handle].flags); /* terminate on last close */ @@ -5627,7 +5689,7 @@ unsigned alert_delays[]= static void alertGlitchFilter(gpioSample_t *sample, int numSamples) { int i, j, diff; - uint32_t steadyUs, changedTick, RBitV, LBitV; + uint32_t steadyUs, changedTick, RBitV, LBitV, initialised; uint32_t bit, bitV; for (i=0; i<=PI_MAX_USER_GPIO; i++) @@ -5636,6 +5698,17 @@ static void alertGlitchFilter(gpioSample_t *sample, int numSamples) if (monitorBits & bit & gFilterBits) { + initialised = gpioAlert[i].gfInitialised; + if (!initialised && numSamples > 0) + { + /* Initialise filter with first sample */ + bitV = sample[0].level & bit; + gpioAlert[i].gfRBitV = bitV; + gpioAlert[i].gfLBitV = bitV; + gpioAlert[i].gfTick = sample[0].tick; + gpioAlert[i].gfInitialised = 1; + } + steadyUs = gpioAlert[i].gfSteadyUs; RBitV = gpioAlert[i].gfRBitV; LBitV = gpioAlert[i].gfLBitV; @@ -7262,7 +7335,7 @@ static int initGrabLockFile(void) static uint32_t * initMapMem(int fd, uint32_t addr, uint32_t len) { return (uint32_t *) mmap(0, len, - PROT_READ|PROT_WRITE|PROT_EXEC, + PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, fd, addr); } @@ -9566,7 +9639,7 @@ int gpioWaveCreate(void) /* What resources are needed? */ - waveCBsOOLs(&numCB, &numBOOL, &numTOOL); + waveCBsOOLs(&numCB, &numBOOL, &numTOOL); wid = -1; @@ -9589,10 +9662,10 @@ int gpioWaveCreate(void) { /* Are there enough spare resources? */ - if ((numCB+waveOutBotCB) >= NUM_WAVE_CBS) + if ((numCB+waveOutBotCB) > NUM_WAVE_CBS) return PI_TOO_MANY_CBS; - if ((numBOOL+waveOutBotOOL) >= (waveOutTopOOL-numTOOL)) + if ((numBOOL+waveOutBotOOL) > (waveOutTopOOL-numTOOL)) return PI_TOO_MANY_OOL; if (wid >= PI_MAX_WAVES) @@ -9619,7 +9692,7 @@ int gpioWaveCreate(void) BOOL = waveInfo[wid].botOOL; TOOL = waveInfo[wid].topOOL; - wave2Cbs(PI_WAVE_MODE_ONE_SHOT, &CB, &BOOL, &TOOL); + wave2Cbs(PI_WAVE_MODE_ONE_SHOT, &CB, &BOOL, &TOOL, 0, 0, 0); /* Sanity check. */ @@ -9633,6 +9706,9 @@ int gpioWaveCreate(void) numTOOL, waveInfo[wid].topOOL-TOOL); } + DBG(DBG_USER, "Wave Stats: wid=%d CBs %d BOOL %d TOOL %d", wid, + numCB, numBOOL, numTOOL); + waveInfo[wid].deleted = 0; /* Consume waves. */ @@ -9646,6 +9722,124 @@ int gpioWaveCreate(void) return wid; } +int gpioWaveCreatePad(int pctCB, int pctBOOL, int pctTOOL) +{ + int i, wid; + int numCB, numBOOL, numTOOL; + int CB, BOOL, TOOL; + + DBG(DBG_USER, "%d, %d, %d", pctCB, pctBOOL, pctTOOL); + + CHECK_INITED; + + if (pctCB < 0 || pctCB > 100) + SOFT_ERROR(PI_BAD_PARAM, "bad wave param, pctCB=(%d)", pctCB); + if (pctBOOL < 0 || pctBOOL > 100) + SOFT_ERROR(PI_BAD_PARAM, "bad wave param, pctBOOL=(%d)", pctBOOL); + if (pctTOOL < 0 || pctTOOL > 100) + SOFT_ERROR(PI_BAD_PARAM, "bad wave param, pctTOOL=(%d)", pctTOOL); + + if (wfc[wfcur] == 0) return PI_EMPTY_WAVEFORM; + + /* What resources are needed? */ + waveCBsOOLs(&numCB, &numBOOL, &numTOOL); + + /* Amount of pad required */ + CB = (NUM_WAVE_CBS - PI_WAVE_COUNT_PAGES*CBS_PER_OPAGE) * pctCB / 100; + BOOL = (NUM_WAVE_OOL - PI_WAVE_COUNT_PAGES*OOL_PER_OPAGE) * pctBOOL /100; + TOOL = (NUM_WAVE_OOL - PI_WAVE_COUNT_PAGES*OOL_PER_OPAGE) * pctTOOL /100; + + /* Reject if wave is too big */ + if (numCB > CB) return PI_TOO_MANY_CBS; + if (numBOOL > BOOL) return PI_TOO_MANY_OOL; + if (numTOOL > TOOL) return PI_TOO_MANY_OOL; + + /* Set the padding */ + numCB = CB; + numBOOL = BOOL; + numTOOL = TOOL; + + + wid = -1; + + /* Is there an exact fit with a deleted wave. */ + + for (i=0; i NUM_WAVE_CBS) + return PI_TOO_MANY_CBS; + + if ((numBOOL+waveOutBotOOL) > (waveOutTopOOL-numTOOL)) + return PI_TOO_MANY_OOL; + + if (wid >= PI_MAX_WAVES) + return PI_NO_WAVEFORM_ID; + + wid = waveOutCount++; + + waveInfo[wid].botCB = waveOutBotCB; + waveInfo[wid].topCB = waveOutBotCB + numCB -1; + waveInfo[wid].botOOL = waveOutBotOOL; + waveInfo[wid].topOOL = waveOutTopOOL; + waveInfo[wid].numCB = numCB; + waveInfo[wid].numBOOL = numBOOL; + waveInfo[wid].numTOOL = numTOOL; + + waveOutBotCB += numCB; + waveOutBotOOL += numBOOL; + waveOutTopOOL -= numTOOL; + } + + /* Must be room if got this far. */ + + CB = waveInfo[wid].botCB; + BOOL = waveInfo[wid].botOOL; + TOOL = waveInfo[wid].topOOL; + + wave2Cbs(PI_WAVE_MODE_ONE_SHOT, &CB, &BOOL, &TOOL, numCB, numBOOL, numTOOL); + + /* Sanity check. */ + + if ( (numCB != (CB-waveInfo[wid].botCB)) || + (numBOOL != (BOOL-waveInfo[wid].botOOL)) || + (numTOOL != (waveInfo[wid].topOOL-TOOL)) ) + { + DBG(DBG_ALWAYS, "ERROR wid=%d CBs %d=%d BOOL %d=%d TOOL %d=%d", wid, + numCB, CB-waveInfo[wid].botCB, + numBOOL, BOOL-waveInfo[wid].botOOL, + numTOOL, waveInfo[wid].topOOL-TOOL); + } + + DBG(DBG_USER, "Wave padding: wid=%d CBs %d BOOL %d TOOL %d", wid, + numCB, numBOOL, numTOOL); + + waveInfo[wid].deleted = 0; + + /* Consume waves. */ + + wfc[0] = 0; + wfc[1] = 0; + wfc[2] = 0; + + wfcur = 0; + + return wid; +} /* ----------------------------------------------------------------------- */ int gpioWaveDelete(unsigned wave_id) @@ -10785,35 +10979,84 @@ int bbI2CZip( void bscInit(int mode) { + int sda, scl, mosi, miso, ce; + bscsReg[BSC_CR]=0; /* clear device */ bscsReg[BSC_RSR]=0; /* clear underrun and overrun errors */ bscsReg[BSC_SLV]=0; /* clear I2C slave address */ bscsReg[BSC_IMSC]=0xf; /* mask off all interrupts */ bscsReg[BSC_ICR]=0x0f; /* clear all interrupts */ - gpioSetMode(BSC_SDA_MOSI, PI_ALT3); - gpioSetMode(BSC_SCL_SCLK, PI_ALT3); + if (pi_is_2711) + { + sda = BSC_SDA_2711; + scl = BSC_SCL_SCLK_2711; + mosi = BSC_MOSI_2711; + miso = BSC_MISO_2711; + ce = BSC_CE_N_2711; + } + else + { + sda = BSC_SDA; + scl = BSC_SCL_SCLK; + mosi = BSC_MOSI; + miso = BSC_MISO; + ce = BSC_CE_N; + } + if (mode > 1) /* SPI uses all GPIO */ { - gpioSetMode(BSC_MISO, PI_ALT3); - gpioSetMode(BSC_CE_N, PI_ALT3); + gpioSetMode(scl, PI_ALT3); + gpioSetMode(mosi, PI_ALT3); + gpioSetMode(miso, PI_ALT3); + gpioSetMode(ce, PI_ALT3); + } + else + { + gpioSetMode(scl, PI_ALT3); + gpioSetMode(sda, PI_ALT3); } } void bscTerm(int mode) { + int sda, scl, mosi, miso, ce; + bscsReg[BSC_CR] = 0; /* clear device */ bscsReg[BSC_RSR]=0; /* clear underrun and overrun errors */ bscsReg[BSC_SLV]=0; /* clear I2C slave address */ - gpioSetMode(BSC_SDA_MOSI, PI_INPUT); - gpioSetMode(BSC_SCL_SCLK, PI_INPUT); + if (pi_is_2711) + { + sda = BSC_SDA_2711; + scl = BSC_SCL_SCLK_2711; + mosi = BSC_MOSI_2711; + miso = BSC_MISO_2711; + ce = BSC_CE_N_2711; + } + else + { + sda = BSC_SDA; + scl = BSC_SCL_SCLK; + mosi = BSC_MOSI; + miso = BSC_MISO; + ce = BSC_CE_N; + } + if (mode > 1) { - gpioSetMode(BSC_MISO, PI_INPUT); - gpioSetMode(BSC_CE_N, PI_INPUT); + gpioSetMode(scl, PI_INPUT); + gpioSetMode(mosi, PI_INPUT); + gpioSetMode(miso, PI_INPUT); + gpioSetMode(ce, PI_INPUT); + } + else + { + gpioSetMode(sda, PI_INPUT); + gpioSetMode(scl, PI_INPUT); + } } @@ -10833,9 +11076,6 @@ int bscXfer(bsc_xfer_t *xfer) CHECK_INITED; - if (pi_is_2711) - SOFT_ERROR(PI_NOT_ON_BCM2711, "SPI/BSC slave not available on BCM2711"); - eventAlert[PI_EVENT_BSC].ignore = 1; if (xfer->control) @@ -10849,7 +11089,7 @@ int bscXfer(bsc_xfer_t *xfer) if (mode > bscMode) { - bscInit(bscMode); + bscInit(mode); bscMode = mode; } } @@ -12180,18 +12420,8 @@ int gpioGlitchFilter(unsigned gpio, unsigned steady) if (steady) { - gpioAlert[gpio].gfTick = systReg[SYST_CLO]; - - if (gpioRead_Bits_0_31() & (1< PI_MAX_TIMER) SOFT_ERROR(PI_BAD_TIMER, "bad timer id (%d)", id); - if ((millis < PI_MIN_MS) || (millis > PI_MAX_MS)) - SOFT_ERROR(PI_BAD_MS, "timer %d, bad millis (%d)", id, millis); + if (f) + { + if ((millis < PI_MIN_MS) || (millis > PI_MAX_MS)) + SOFT_ERROR(PI_BAD_MS, "timer %d, bad millis (%d)", id, millis); + } intGpioSetTimerFunc(id, millis, f, 0, NULL); @@ -13064,6 +13297,8 @@ int fileApprove(char *filename) buffer[0] = 0; match[0] = 0; + if (myPathBad(filename)) return PI_FILE_NONE; + f = fopen("/opt/pigpio/access", "r"); if (!f) return PI_FILE_NONE; @@ -13120,7 +13355,7 @@ int fileOpen(char *file, unsigned mode) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int fd=-1; - int i, slot, oflag, omode; + int i, slot, oflag, omode, pmode, rmode; struct stat statbuf; DBG(DBG_USER, "file=%s mode=%d", file, mode); @@ -13132,9 +13367,15 @@ int fileOpen(char *file, unsigned mode) ((mode & PI_FILE_RW) == 0) ) SOFT_ERROR(PI_BAD_FILE_MODE, "bad mode (%d)", mode); - if ((fileApprove(file) & mode) == PI_FILE_NONE) + pmode = fileApprove(file); // 0=NONE, 1=READ, 2=WRITE, 3=RW + rmode = mode & PI_FILE_RW; // 0=NONE, 1=READ, 2=WRITE, 3=RW + + if (((pmode & rmode) != rmode) || (rmode == PI_FILE_NONE)) SOFT_ERROR(PI_NO_FILE_ACCESS, "no permission to access file (%s)", file); + if ((mode > 3) && ((mode & PI_FILE_WRITE) == 0)) + SOFT_ERROR(PI_NO_FILE_ACCESS, "no permission to write file (%s)", file); + slot = -1; pthread_mutex_lock(&mutex); @@ -13158,7 +13399,6 @@ int fileOpen(char *file, unsigned mode) if (mode & PI_FILE_APPEND) { - mode |= PI_FILE_WRITE; oflag |= O_APPEND; } @@ -13170,7 +13410,6 @@ int fileOpen(char *file, unsigned mode) if (mode & PI_FILE_TRUNC) { - mode |= PI_FILE_WRITE; oflag |= O_TRUNC; } @@ -13355,7 +13594,7 @@ int fileList(char *fpat, char *buf, unsigned count) CHECK_INITED; - if (fileApprove(fpat) == PI_FILE_NONE) + if ((fileApprove(fpat) & PI_FILE_READ) != PI_FILE_READ) SOFT_ERROR(PI_NO_FILE_ACCESS, "no permission to access file (%s)", fpat); bufpos = 0; @@ -13576,8 +13815,8 @@ unsigned gpioHardwareRevision(void) rev = ntohl(tmp); rev &= 0xFFFFFF; /* mask out warranty bit */ } + fclose(filp); } - fclose(filp); } piCores = 0; @@ -13588,7 +13827,7 @@ unsigned gpioHardwareRevision(void) if ((rev & 0x800000) == 0) /* old rev code */ { - if (rev < 0x0016) /* all BCM2835 */ + if ((rev > 0) && (rev < 0x0016)) /* all BCM2835 */ { pi_ispi = 1; piCores = 1; @@ -13845,44 +14084,6 @@ int gpioCfgSetInternals(uint32_t cfgVal) return 0; } -int gpioCfgInternals(unsigned cfgWhat, unsigned cfgVal) -{ - int retVal = PI_BAD_CFG_INTERNAL; - - DBG(DBG_USER, "cfgWhat=%u, cfgVal=%d", cfgWhat, cfgVal); - - switch(cfgWhat) - { - case 562484977: - - if (cfgVal) gpioCfg.internals |= PI_CFG_STATS; - else gpioCfg.internals &= (~PI_CFG_STATS); - - DBG(DBG_ALWAYS, "show stats is %u", cfgVal); - - retVal = 0; - - break; - - case 984762879: - - if ((cfgVal >= DBG_ALWAYS) && (cfgVal <= DBG_MAX_LEVEL)) - { - - gpioCfg.dbgLevel = cfgVal; - gpioCfg.internals = (gpioCfg.internals & (~0xF)) | cfgVal; - - DBG(DBG_ALWAYS, "Debug level is %u", cfgVal); - - retVal = 0; - } - - break; - } - - return retVal; -} - /* include any user customisations */ diff --git a/pigpio.h b/pigpio.h index eed7f63..cee6ef8 100644 --- a/pigpio.h +++ b/pigpio.h @@ -27,10 +27,11 @@ For more information, please refer to #ifndef PIGPIO_H #define PIGPIO_H +#include #include #include -#define PIGPIO_VERSION 74 +#define PIGPIO_VERSION 79 /*TEXT @@ -106,6 +107,16 @@ return error PI_NOT_INITIALISED. If the library is initialised the [*gpioCfg**] functions will return error PI_INITIALISED. +If you intend to rely on signals sent to your application, you should +turn off the internal signal handling as shown in this example: + +. . +int cfg = gpioCfgGetInternals(); +cfg |= PI_CFG_NOSIGHANDLER; // (1<<10) +gpioCfgSetInternals(cfg); +int status = gpioInitialise(); +. . + TEXT*/ /*OVERVIEW @@ -322,6 +333,7 @@ gpioWaveAddGeneric Adds a series of pulses to the waveform gpioWaveAddSerial Adds serial data to the waveform gpioWaveCreate Creates a waveform from added data +gpioWaveCreatePad Creates a waveform of fixed size from added data gpioWaveDelete Deletes a waveform gpioWaveTxSend Transmits a waveform @@ -376,7 +388,6 @@ gpioCfgSocketPort Configure socket port gpioCfgMemAlloc Configure DMA memory allocation mode gpioCfgNetAddr Configure allowed network addresses -gpioCfgInternals Configure misc. internals (DEPRECATED) gpioCfgGetInternals Get internal configuration settings gpioCfgSetInternals Set internal configuration settings @@ -792,11 +803,18 @@ typedef void *(gpioThreadFunc_t) (void *); /* BSC GPIO */ -#define BSC_SDA_MOSI 18 +#define BSC_SDA 18 +#define BSC_MOSI 20 #define BSC_SCL_SCLK 19 -#define BSC_MISO 20 +#define BSC_MISO 18 #define BSC_CE_N 21 +#define BSC_SDA_2711 10 +#define BSC_MOSI_2711 9 +#define BSC_SCL_SCLK_2711 11 +#define BSC_MISO_2711 10 +#define BSC_CE_N_2711 8 + /* Longest busy delay */ #define PI_MAX_BUSY_DELAY 100 @@ -1439,6 +1457,12 @@ once per level change since the last time the thread was activated. i.e. The active alert functions will get all level changes but there will be a latency. +If you want to track the level of more than one GPIO do so by +maintaining the state in the callback. Do not use [*gpioRead*]. +Remember the event that triggered the callback may have +happened several milliseconds before and the GPIO may have +changed level many times since then. + The tick value is the time stamp of the sample in microseconds, see [*gpioTick*] for more details. @@ -1976,6 +2000,49 @@ PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL. D*/ +/*F*/ +int gpioWaveCreatePad(int pctCB, int pctBOOL, int pctTOOL); +/*D +Similar to [*gpioWaveCreate*], this function creates a waveform but pads the consumed +resources. Padded waves of equal dimension can be re-cycled efficiently allowing +newly created waves to re-use the resources of deleted waves of the same dimension. + +. . +pctCB: 0-100, the percent of all DMA control blocks to consume. +pctBOOL: 0-100, percent On-Off-Level (OOL) buffer to consume for wave output. +pctTOOL: 0-100, the percent of OOL buffer to consume for wave input (flags). +. . + +Upon success a wave id greater than or equal to 0 is returned, otherwise +PI_EMPTY_WAVEFORM, PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID. + +Waveform data provided by [*gpioWaveAdd**] and [*rawWaveAdd**] functions are +consumed by this function. + +A usage would be the creation of two waves where one is filled while the other +is being transmitted. Each wave is assigned 50% of the resources. +This buffer structure allows the transmission of infinite wave sequences. + +... + // get firstWaveChunk, somehow + gpioWaveAddGeneric(firstWaveChunk); + wid = gpioWaveCreatePad(50, 50, 0); + gpioWaveTxSend(wid, PI_WAVE_MODE_ONE_SHOT); + // get nextWaveChunk + + while (nextWaveChunk) { + gpioWaveAddGeneric(nextWaveChunk); + nextWid = gpioWaveCreatePad(50, 50, 0); + gpioWaveTxSend(nextWid, PI_WAVE_MODE_ONE_SHOT_SYNC); + while(gpioWaveTxAt() == wid) time_sleep(0.1); + gpioWaveDelete(wid); + wid = nextWid; + // get nextWaveChunk + } +... + +D*/ + /*F*/ int gpioWaveDelete(unsigned wave_id); /*D @@ -2135,7 +2202,7 @@ D*/ int gpioWaveTxAt(void); /*D This function returns the id of the waveform currently being -transmitted. +transmitted using [*gpioWaveTxSend*]. Chained waves are not supported. Returns the waveform id or one of the following special values: @@ -2922,12 +2989,6 @@ The output process is simple. You simply append data to the FIFO buffer on the chip. This works like a queue, you add data to the queue and the master removes it. -This function is not available on the BCM2711 (e.g. as -used in the Pi4B). - -I can't get SPI to work properly. I tried with a -control word of 0x303 and swapped MISO and MOSI. - The function sets the BSC mode, writes any data in the transmit buffer to the BSC transmit FIFO, and copies any data in the BSC receive FIFO to the @@ -2956,11 +3017,19 @@ in rxBuf. Note that the control word sets the BSC mode. The BSC will stay in that mode until a different control word is sent. -The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL) in I2C mode -and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO), and 21 (CE) in SPI mode. You -need to swap MISO/MOSI between master and slave. +GPIO used for models other than those based on the BCM2711. -When a zero control word is received GPIO 18-21 will be reset + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE +I2C @ 18 @ 19 @ - @ - @ - @ - +SPI @ - @ - @ 20 @ 19 @ 18 @ 21 + +GPIO used for models based on the BCM2711 (e.g. the Pi4B). + + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE +I2C @ 10 @ 11 @ - @ - @ - @ - +SPI @ - @ - @ 9 @ 11 @ 10 @ 8 + +When a zero control word is received the used GPIO will be reset to INPUT mode. The returned function value is the status of the transfer (see below). @@ -3011,7 +3080,7 @@ pages 165-166 of the Broadcom peripherals document for full details. SSSSS @ number of bytes successfully copied to transmit FIFO -RRRRR @ number of bytes in receieve FIFO +RRRRR @ number of bytes in receive FIFO TTTTT @ number of bytes in transmit FIFO RB @ receive busy TE @ transmit FIFO empty @@ -3038,6 +3107,17 @@ if (status >= 0) // process transfer } ... + +The BSC slave in SPI mode deserializes data from the MOSI pin into its +receiver/FIFO when the LSB of the first byte is a 0. No data is output on +the MISO pin. When the LSB of the first byte on MOSI is a 1, the +transmitter/FIFO data is serialized onto the MISO pin while all other data +on the MOSI pin is ignored. + +The BK bit of the BSC control register is non-functional when in the SPI +mode. The transmitter along with its FIFO can be dequeued by successively +disabling and re-enabling the TE bit on the BSC control register while in +SPI mode. D*/ /*F*/ @@ -3802,24 +3882,6 @@ param is an array of up to 10 parameters which may be referenced in the script as p0 to p9. D*/ -/*F*/ -int gpioRunScript(unsigned script_id, unsigned numPar, uint32_t *param); -/*D -This function runs a stored script. - -. . -script_id: >=0, as returned by [*gpioStoreScript*] - numPar: 0-10, the number of parameters - param: an array of parameters -. . - -The function returns 0 if OK, otherwise PI_BAD_SCRIPT_ID, or -PI_TOO_MANY_PARAM. - -param is an array of up to 10 parameters which may be referenced in -the script as p0 to p9. -D*/ - /*F*/ @@ -4924,18 +4986,6 @@ numSockAddr: 0-256 (0 means all addresses allowed) D*/ -/*F*/ -int gpioCfgInternals(unsigned cfgWhat, unsigned cfgVal); -/*D -Used to tune internal settings. - -. . -cfgWhat: see source code - cfgVal: see source code -. . -D*/ - - /*F*/ uint32_t gpioCfgGetInternals(void); /*D @@ -4952,6 +5002,7 @@ settings. . . cfgVal: see source code . . + D*/ @@ -5753,6 +5804,15 @@ high and low levels. *param:: An array of script parameters. +pctBOOL:: 0-100 +percent On-Off-Level (OOL) buffer to consume for wave output. + +pctCB:: 0-100 +the percent of all DMA control blocks to consume. + +pctTOOL:: 0-100 +the percent of OOL buffer to consume for wave input (flags). + pi_i2c_msg_t:: . . typedef struct @@ -6264,6 +6324,7 @@ PARAMS*/ #define PI_CMD_EVT 116 #define PI_CMD_PROCU 117 +#define PI_CMD_WVCAP 118 /*DEF_E*/ diff --git a/pigpio.py b/pigpio.py index 0e2a0a1..20d48e6 100644 --- a/pigpio.py +++ b/pigpio.py @@ -288,6 +288,7 @@ wave_add_generic Adds a series of pulses to the waveform wave_add_serial Adds serial data to the waveform wave_create Creates a waveform from added data +wave_create_and_pad Creates a waveform of fixed size from added data wave_delete Deletes a waveform wave_send_once Transmits a waveform once @@ -330,7 +331,7 @@ import threading import os import atexit -VERSION = "1.45" +VERSION = "1.78" # sync minor number to pigpio library version exceptions = True @@ -571,6 +572,7 @@ _PI_CMD_EVM =115 _PI_CMD_EVT =116 _PI_CMD_PROCU=117 +_PI_CMD_WVCAP=118 # pigpio error numbers @@ -2304,6 +2306,51 @@ class pi(): """ return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCRE, 0, 0)) + def wave_create_and_pad(self, percent): + """ + This function creates a waveform like [*wave_create*] but pads the consumed + resources. Where percent gives the percentage of the resources to use + (in terms of the theoretical maximum, not the current amount free). + This allows the reuse of deleted waves while a transmission is active. + + Upon success a wave id greater than or equal to 0 is returned, otherwise + PI_EMPTY_WAVEFORM, PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID. + + . . + percent: 0-100, size of waveform as percentage of maximum available. + . . + + The data provided by the [*wave_add_**] functions are consumed by this + function. + + As many waveforms may be created as there is space available. The + wave id is passed to [*wave_send_**] to specify the waveform to transmit. + + A usage would be the creation of two waves where one is filled while the + other is being transmitted. Each wave is assigned 50% of the resources. + This buffer structure allows the transmission of infinite wave sequences. + + Normal usage: + + Step 1. [*wave_clear*] to clear all waveforms and added data. + + Step 2. [*wave_add_**] calls to supply the waveform data. + + Step 3. [*wave_create_and_pad*] to create a waveform of uniform size. + + Step 4. [*wave_send_**] with the id of the waveform to transmit. + + Repeat steps 2-4 as needed. + + Step 5. Any wave id can now be deleted and another wave of the same size + can be created in its place. + + ... + wid = pi.wave_create_and_pad(50) + ... + """ + return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCAP, percent, 0)) + def wave_delete(self, wave_id): """ This function deletes the waveform with id wave_id. @@ -2419,7 +2466,7 @@ class pi(): def wave_tx_at(self): """ Returns the id of the waveform currently being - transmitted. + transmitted using [*wave_send**]. Chained waves are not supported. Returns the waveform id or one of the following special values: @@ -3557,13 +3604,6 @@ class pi(): buffer on the chip. This works like a queue, you add data to the queue and the master removes it. - This function is not available on the BCM2711 (e.g. as - used in the Pi4B). - - I can't get SPI to work properly. I tried with a - control word of 0x303 and swapped MISO and MOSI. - - The function sets the BSC mode, writes any data in the transmit buffer to the BSC transmit FIFO, and copies any data in the BSC receive FIFO to the @@ -3580,12 +3620,19 @@ class pi(): Note that the control word sets the BSC mode. The BSC will stay in that mode until a different control word is sent. - The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL) - in I2C mode and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO), - and 21 (CE) in SPI mode. You need to swap MISO/MOSI - between master and slave. + GPIO used for models other than those based on the BCM2711. - When a zero control word is received GPIO 18-21 will be reset + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE + I2C @ 18 @ 19 @ - @ - @ - @ - + SPI @ - @ - @ 20 @ 19 @ 18 @ 21 + + GPIO used for models based on the BCM2711 (e.g. the Pi4B). + + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE + I2C @ 10 @ 11 @ - @ - @ - @ - + SPI @ - @ - @ 9 @ 11 @ 10 @ 8 + + When a zero control word is received the used GPIO will be reset to INPUT mode. bsc_control consists of the following bits: @@ -3627,7 +3674,7 @@ class pi(): details. SSSSS @ number of bytes successfully copied to transmit FIFO - RRRRR @ number of bytes in receieve FIFO + RRRRR @ number of bytes in receive FIFO TTTTT @ number of bytes in transmit FIFO RB @ receive busy TE @ transmit FIFO empty @@ -3639,6 +3686,50 @@ class pi(): ... (status, count, data) = pi.bsc_xfer(0x330305, "Hello!") ... + + The BSC slave in SPI mode deserializes data from the MOSI pin into its + receiver/FIFO when the LSB of the first byte is a 0. No data is output on + the MISO pin. When the LSB of the first byte on MOSI is a 1, the + transmitter/FIFO data is serialized onto the MISO pin while all other data + on the MOSI pin is ignored. + + The BK bit of the BSC control register is non-functional when in the SPI + mode. The transmitter along with its FIFO can be dequeued by successively + disabling and re-enabling the TE bit on the BSC control register while in + SPI mode. + + This example demonstrates a SPI master talking to the BSC as SPI slave: + Requires SPI master SCLK / MOSI / MISO / CE GPIO are connected to + BSC peripheral GPIO 11 / 9 / 10 / 8 respectively, on a Pi4B (BCM2711). + + ... + #!/usr/bin/env python + + import pigpio + + # Choose some random GPIO for the bit-bang SPI master + CE=15 + MISO=26 + MOSI=13 + SCLK=14 + + pi = pigpio.pi() + if not pi.connected: + exit() + + pi.bb_spi_open(CE, MISO, MOSI, SCLK, 10000, 0) # open SPI master + pi.bsc_xfer(0x303, []) # start BSC as SPI slave + pi.bb_spi_xfer(CE, '\0' + 'hello') # write 'hello' to BSC + status, count, bsc_data = pi.bsc_xfer(0x303, 'world') + print bsc_data # hello + count, spi_data = pi.bb_spi_xfer(CE, [1,0,0,0,0,0]) + print spi_data # world + + pi.bsc_xfer(0, []) + pi.bb_spi_close(CE) + + pi.stop() + ... """ # I p1 control # I p2 0 @@ -3666,9 +3757,6 @@ class pi(): """ This function allows the Pi to act as a slave I2C device. - This function is not available on the BCM2711 (e.g. as - used in the Pi4B). - The data bytes (if any) are written to the BSC transmit FIFO and the bytes in the BSC receive FIFO are returned. @@ -3684,10 +3772,10 @@ class pi(): (and will contain the error code). Note that an i2c_address of 0 may be used to close - the BSC device and reassign the used GPIO (18/19) - as inputs. + the BSC device and reassign the used GPIO as inputs. - This example assumes GPIO 2/3 are connected to GPIO 18/19. + This example assumes GPIO 2/3 are connected to GPIO 18/19 + (GPIO 10/11 on the BCM2711). ... #!/usr/bin/env python @@ -4939,6 +5027,37 @@ class pi(): A GPIO may have multiple callbacks (although I can't think of a reason to do so). + The GPIO are sampled at a rate set when the pigpio daemon + is started (default 5 us). + + The number of samples per second is given in the following table. + + . . + samples + per sec + + 1 1,000,000 + 2 500,000 + sample 4 250,000 + rate 5 200,000 + (us) 8 125,000 + 10 100,000 + . . + + GPIO level changes shorter than the sample rate may be missed. + + The daemon software which generates the callbacks is triggered + 1000 times per second. The callbacks will be called once per + level change since the last time they were called. + i.e. The callbacks will get all level changes but there will + be a latency. + + If you want to track the level of more than one GPIO do so by + maintaining the state in the callback. Do not use [*read*]. + Remember the event that triggered the callback may have + happened several milliseconds before and the GPIO may have + changed level many times since then. + ... def cbf(gpio, level, tick): print(gpio, level, tick) @@ -4974,7 +5093,7 @@ class pi(): by calling the tally function. The count may be reset to zero by calling the reset_tally function. - The callback may be cancelled by calling the event_cancel function. + The callback may be canceled by calling the cancel function. An event may have multiple callbacks (although I can't think of a reason to do so). @@ -4991,7 +5110,7 @@ class pi(): cb2.reset_tally() - cb1.event_cancel() # To cancel callback cb1. + cb1.cancel() # To cancel callback cb1. ... """ @@ -5548,6 +5667,9 @@ def xref(): When scripts are started they can receive up to 10 parameters to define their operation. + percent:: 0-100 + The size of waveform as percentage of maximum available. + port: The port used by the pigpio daemon, defaults to 8888. diff --git a/pigpiod_if.c b/pigpiod_if.c index 7802e57..c62b3e8 100644 --- a/pigpiod_if.c +++ b/pigpiod_if.c @@ -1064,7 +1064,7 @@ int i2c_process_call(unsigned handle, unsigned reg, uint32_t val) ext[0].ptr = &val; return pigpio_command_ext - (gPigCommand, PI_CMD_I2CPK, handle, reg, 4, 1, ext, 1); + (gPigCommand, PI_CMD_I2CPC, handle, reg, 4, 1, ext, 1); } int i2c_write_block_data( diff --git a/pigpiod_if2.3 b/pigpiod_if2.3 index 1c9291c..1f55ee5 100644 --- a/pigpiod_if2.3 +++ b/pigpiod_if2.3 @@ -546,6 +546,8 @@ wave_add_serial Adds serial data to the waveform .br wave_create Creates a waveform from added data .br +wave_create_and_pad Creates a waveform of fixed size from added data +.br wave_delete Deletes one or more waveforms .br @@ -714,7 +716,7 @@ No value is returned. .br The thread to be stopped should have been started with \fBstart_thread\fP. -.IP "\fBint pigpio_start(char *addrStr, char *portStr)\fP" +.IP "\fBint pigpio_start(const char *addrStr, const char *portStr)\fP" .IP "" 4 Connect to the pigpio daemon. Reserving command and notification streams. @@ -947,7 +949,8 @@ user_gpio: 0-31. .br .br -Returns 0 if OK, otherwise PI_BAD_USER_GPIO or PI_NOT_PWM_GPIO. +Returns current PWM dutycycle if OK, +otherwise PI_BAD_USER_GPIO or PI_NOT_PWM_GPIO. .br @@ -2391,6 +2394,87 @@ specified delay between the pulse and the next. Returns the new waveform id if OK, otherwise PI_EMPTY_WAVEFORM, PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL. +.IP "\fBint wave_create_and_pad(int pi, int percent)\fP" +.IP "" 4 +This function creates a waveform like \fBwave_create\fP but pads the consumed +resources. Where percent gives the percentage of the resources to use (in terms +of the theoretical maximum, not the current amount free). This allows the reuse +.br +of deleted waves while a transmission is active. + +.br + +.br + +.EX +pi: >=0 (as returned by \fBpigpio_start\fP). +.br +percent: 0-100, size of waveform as percentage of maximum available. +.br + +.EE + +.br + +.br +The data provided by the \fBwave_add_*\fP functions are consumed by this +function. + +.br + +.br +As many waveforms may be created as there is space available. The +wave id is passed to \fBwave_send_*\fP to specify the waveform to transmit. + +.br + +.br +A usage would be the creation of two waves where one is filled while the other +is being transmitted. Each wave is assigned 50% of the resources. +This buffer structure allows the transmission of infinite wave sequences. + +.br + +.br +Normal usage: + +.br + +.br +Step 1. \fBwave_clear\fP to clear all waveforms and added data. + +.br + +.br +Step 2. \fBwave_add_*\fP calls to supply the waveform data. + +.br + +.br +Step 3. \fBwave_create_and_pad\fP to create a waveform of uniform size. + +.br + +.br +Step 4. \fBwave_send_*\fP with the id of the waveform to transmit. + +.br + +.br +Repeat steps 2-4 as needed. + +.br + +.br +Step 5. Any wave id can now be deleted and another wave of the same size + can be created in its place. + +.br + +.br +Returns the new waveform id if OK, otherwise PI_EMPTY_WAVEFORM, +PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL. + .IP "\fBint wave_delete(int pi, unsigned wave_id)\fP" .IP "" 4 This function deletes the waveform with id wave_id. @@ -2746,7 +2830,7 @@ int main(int argc, char *argv[]) .IP "\fBint wave_tx_at(int pi)\fP" .IP "" 4 This function returns the id of the waveform currently being -transmitted. +transmitted by \fBwave_send*\fP. Chained waves are not supported. .br @@ -5920,6 +6004,66 @@ tick 32 bit The number of microseconds since boot .EE +.br + +.br +The GPIO are sampled at a rate set when the pigpio daemon +is started (default 5 us). + +.br + +.br +The number of samples per second is given in the following table. + +.br + +.br + +.EX + samples +.br + per sec +.br + +.br + 1 1,000,000 +.br + 2 500,000 +.br +sample 4 250,000 +.br +rate 5 200,000 +.br +(us) 8 125,000 +.br + 10 100,000 +.br + +.EE + +.br + +.br +GPIO level changes shorter than the sample rate may be missed. + +.br + +.br +The daemon software which generates the callbacks is triggered +1000 times per second. The callbacks will be called once per +level change since the last time they were called. +i.e. The callbacks will get all level changes but there will +be a latency. + +.br + +.br +If you want to track the level of more than one GPIO do so by +maintaining the state in the callback. Do not use \fBgpio_read\fP. +Remember the event that triggered the callback may have +happened several milliseconds before and the GPIO may have +changed level many times since then. + .IP "\fBint callback_ex(int pi, unsigned user_gpio, unsigned edge, CBFuncEx_t f, void *userdata)\fP" .IP "" 4 This function initialises a new callback. @@ -6072,18 +6216,6 @@ queue and the master removes it. .br -.br -This function is not available on the BCM2711 (e.g. as -used in the Pi4B). - -.br - -.br -I can't get SPI to work properly. I tried with a -control word of 0x303 and swapped MISO and MOSI. - -.br - .br The function sets the BSC mode, writes any data in the transmit buffer to the BSC transmit FIFO, and @@ -6160,14 +6292,37 @@ that mode until a different control word is sent. .br .br -The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL) in I2C mode -and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO), and 21 (CE) in SPI mode. You -need to swap MISO/MOSI between master and slave. +GPIO used for models other than those based on the BCM2711. .br .br -When a zero control word is received GPIO 18-21 will be reset + SDA SCL MOSI SCLK MISO CE +.br +I2C 18 19 - - - - +.br +SPI - - 20 19 18 21 +.br + +.br + +.br +GPIO used for models based on the BCM2711 (e.g. the Pi4B). + +.br + +.br + SDA SCL MOSI SCLK MISO CE +.br +I2C 10 11 - - - - +.br +SPI - - 9 11 10 8 +.br + +.br + +.br +When a zero control word is received the used GPIO will be reset to INPUT mode. .br @@ -6257,7 +6412,7 @@ details. .br SSSSS number of bytes successfully copied to transmit FIFO .br -RRRRR number of bytes in receieve FIFO +RRRRR number of bytes in receive FIFO .br TTTTT number of bytes in transmit FIFO .br @@ -6316,6 +6471,23 @@ if (status >= 0) .EE +.br + +.br +The BSC slave in SPI mode deserializes data from the MOSI pin into its +receiver/FIFO when the LSB of the first byte is a 0. No data is output on +the MISO pin. When the LSB of the first byte on MOSI is a 1, the +transmitter/FIFO data is serialized onto the MISO pin while all other data +on the MOSI pin is ignored. + +.br + +.br +The BK bit of the BSC control register is non-functional when in the SPI +mode. The transmitter along with its FIFO can be dequeued by successively +disabling and re-enabling the TE bit on the BSC control register while in +SPI mode. + .IP "\fBint bsc_i2c(int pi, int i2c_addr, bsc_xfer_t *bscxfer)\fP" .IP "" 4 This function allows the Pi to act as a slave I2C device. @@ -6390,8 +6562,7 @@ If there was an error the status will be less than zero .br Note that an i2c_address of 0 may be used to close -the BSC device and reassign the used GPIO (18/19) -as inputs. +the BSC device and reassign the used GPIO as inputs. .IP "\fBint event_callback(int pi, unsigned event, evtCBFunc_t f)\fP" .IP "" 4 @@ -7340,6 +7511,13 @@ An array of script parameters. .br +.IP "\fBpercent\fP: 0-100" 0 +The size of waveform as percentage of maximum available. + +.br + +.br + .IP "\fBpi\fP" 0 An integer defining a connected Pi. The value is returned by \fBpigpio_start\fP upon success. diff --git a/pigpiod_if2.c b/pigpiod_if2.c index 36f01aa..f8dc9c7 100644 --- a/pigpiod_if2.c +++ b/pigpiod_if2.c @@ -25,7 +25,7 @@ OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to */ -/* PIGPIOD_IF2_VERSION 16 */ +/* PIGPIOD_IF2_VERSION 17 */ #include #include @@ -234,7 +234,7 @@ static int pigpio_command_ext return cmd.res; } -static int pigpioOpenSocket(char *addrStr, char *portStr) +static int pigpioOpenSocket(const char *addrStr, const char *portStr) { int sock, err, opt; struct addrinfo hints, *res, *rp; @@ -685,7 +685,7 @@ void stop_thread(pthread_t *pth) } } -int pigpio_start(char *addrStr, char *portStr) +int pigpio_start(const char *addrStr, const char *portStr) { int pi; int *userdata; @@ -953,6 +953,9 @@ int wave_add_serial( int wave_create(int pi) {return pigpio_command(pi, PI_CMD_WVCRE, 0, 0, 1);} +int wave_create_and_pad(int pi, int percent) + {return pigpio_command(pi, PI_CMD_WVCAP, percent, 0, 1);} + int wave_delete(int pi, unsigned wave_id) {return pigpio_command(pi, PI_CMD_WVDEL, wave_id, 0, 1);} @@ -1285,7 +1288,7 @@ int i2c_process_call(int pi, unsigned handle, unsigned reg, uint32_t val) ext[0].ptr = &val; return pigpio_command_ext - (pi, PI_CMD_I2CPK, handle, reg, 4, 1, ext, 1); + (pi, PI_CMD_I2CPC, handle, reg, 4, 1, ext, 1); } int i2c_write_block_data( @@ -2119,5 +2122,5 @@ int wait_for_event(int pi, unsigned event, double timeout) } int event_trigger(int pi, unsigned event) - {return pigpio_command(pi, PI_CMD_EVM, event, 0, 1);} + {return pigpio_command(pi, PI_CMD_EVT, event, 0, 1);} diff --git a/pigpiod_if2.h b/pigpiod_if2.h index fb214df..b6aa648 100644 --- a/pigpiod_if2.h +++ b/pigpiod_if2.h @@ -30,7 +30,7 @@ For more information, please refer to #include "pigpio.h" -#define PIGPIOD_IF2_VERSION 16 +#define PIGPIOD_IF2_VERSION 17 /*TEXT @@ -302,6 +302,7 @@ wave_add_generic Adds a series of pulses to the waveform wave_add_serial Adds serial data to the waveform wave_create Creates a waveform from added data +wave_create_and_pad Creates a waveform of fixed size from added data wave_delete Deletes one or more waveforms wave_send_once Transmits a waveform once @@ -428,7 +429,7 @@ The thread to be stopped should have been started with [*start_thread*]. D*/ /*F*/ -int pigpio_start(char *addrStr, char *portStr); +int pigpio_start(const char *addrStr, const char *portStr); /*D Connect to the pigpio daemon. Reserving command and notification streams. @@ -567,7 +568,8 @@ Return the PWM dutycycle in use on a GPIO. user_gpio: 0-31. . . -Returns 0 if OK, otherwise PI_BAD_USER_GPIO or PI_NOT_PWM_GPIO. +Returns current PWM dutycycle if OK, +otherwise PI_BAD_USER_GPIO or PI_NOT_PWM_GPIO. For normal PWM the dutycycle will be out of the defined range for the GPIO (see [*get_PWM_range*]). @@ -1372,6 +1374,49 @@ PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL. D*/ +/*F*/ +int wave_create_and_pad(int pi, int percent); +/*D +This function creates a waveform like [*wave_create*] but pads the consumed +resources. Where percent gives the percentage of the resources to use (in terms +of the theoretical maximum, not the current amount free). This allows the reuse +of deleted waves while a transmission is active. + +. . +pi: >=0 (as returned by [*pigpio_start*]). +percent: 0-100, size of waveform as percentage of maximum available. +. . + +The data provided by the [*wave_add_**] functions are consumed by this +function. + +As many waveforms may be created as there is space available. The +wave id is passed to [*wave_send_**] to specify the waveform to transmit. + +A usage would be the creation of two waves where one is filled while the other +is being transmitted. Each wave is assigned 50% of the resources. +This buffer structure allows the transmission of infinite wave sequences. + +Normal usage: + +Step 1. [*wave_clear*] to clear all waveforms and added data. + +Step 2. [*wave_add_**] calls to supply the waveform data. + +Step 3. [*wave_create_and_pad*] to create a waveform of uniform size. + +Step 4. [*wave_send_**] with the id of the waveform to transmit. + +Repeat steps 2-4 as needed. + +Step 5. Any wave id can now be deleted and another wave of the same size + can be created in its place. + +Returns the new waveform id if OK, otherwise PI_EMPTY_WAVEFORM, +PI_NO_WAVEFORM_ID, PI_TOO_MANY_CBS, or PI_TOO_MANY_OOL. +D*/ + + /*F*/ int wave_delete(int pi, unsigned wave_id); /*D @@ -1565,7 +1610,7 @@ D*/ int wave_tx_at(int pi); /*D This function returns the id of the waveform currently being -transmitted. +transmitted by [*wave_send**]. Chained waves are not supported. . . pi: >=0 (as returned by [*pigpio_start*]). @@ -3352,6 +3397,37 @@ tick 32 bit The number of microseconds since boot WARNING: this wraps around from 4294967295 to 0 roughly every 72 minutes . . + +The GPIO are sampled at a rate set when the pigpio daemon +is started (default 5 us). + +The number of samples per second is given in the following table. + +. . + samples + per sec + + 1 1,000,000 + 2 500,000 +sample 4 250,000 +rate 5 200,000 +(us) 8 125,000 + 10 100,000 +. . + +GPIO level changes shorter than the sample rate may be missed. + +The daemon software which generates the callbacks is triggered +1000 times per second. The callbacks will be called once per +level change since the last time they were called. +i.e. The callbacks will get all level changes but there will +be a latency. + +If you want to track the level of more than one GPIO do so by +maintaining the state in the callback. Do not use [*gpio_read*]. +Remember the event that triggered the callback may have +happened several milliseconds before and the GPIO may have +changed level many times since then. D*/ /*F*/ @@ -3442,12 +3518,6 @@ The output process is simple. You simply append data to the FIFO buffer on the chip. This works like a queue, you add data to the queue and the master removes it. -This function is not available on the BCM2711 (e.g. as -used in the Pi4B). - -I can't get SPI to work properly. I tried with a -control word of 0x303 and swapped MISO and MOSI. - The function sets the BSC mode, writes any data in the transmit buffer to the BSC transmit FIFO, and copies any data in the BSC receive FIFO to the @@ -3486,11 +3556,19 @@ less than requested if the FIFO already contained untransmitted data). Note that the control word sets the BSC mode. The BSC will stay in that mode until a different control word is sent. -The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL) in I2C mode -and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO), and 21 (CE) in SPI mode. You -need to swap MISO/MOSI between master and slave. +GPIO used for models other than those based on the BCM2711. -When a zero control word is received GPIO 18-21 will be reset + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE +I2C @ 18 @ 19 @ - @ - @ - @ - +SPI @ - @ - @ 20 @ 19 @ 18 @ 21 + +GPIO used for models based on the BCM2711 (e.g. the Pi4B). + + @ SDA @ SCL @ MOSI @ SCLK @ MISO @ CE +I2C @ 10 @ 11 @ - @ - @ - @ - +SPI @ - @ - @ 9 @ 11 @ 10 @ 8 + +When a zero control word is received the used GPIO will be reset to INPUT mode. control consists of the following bits. @@ -3532,7 +3610,7 @@ pages 165-166 of the Broadcom peripherals document for full details. SSSSS @ number of bytes successfully copied to transmit FIFO -RRRRR @ number of bytes in receieve FIFO +RRRRR @ number of bytes in receive FIFO TTTTT @ number of bytes in transmit FIFO RB @ receive busy TE @ transmit FIFO empty @@ -3559,6 +3637,17 @@ if (status >= 0) // process transfer } ... + +The BSC slave in SPI mode deserializes data from the MOSI pin into its +receiver/FIFO when the LSB of the first byte is a 0. No data is output on +the MISO pin. When the LSB of the first byte on MOSI is a 1, the +transmitter/FIFO data is serialized onto the MISO pin while all other data +on the MOSI pin is ignored. + +The BK bit of the BSC control register is non-functional when in the SPI +mode. The transmitter along with its FIFO can be dequeued by successively +disabling and re-enabling the TE bit on the BSC control register while in +SPI mode. D*/ /*F*/ @@ -3598,8 +3687,7 @@ If there was an error the status will be less than zero (and will contain the error code). Note that an i2c_address of 0 may be used to close -the BSC device and reassign the used GPIO (18/19) -as inputs. +the BSC device and reassign the used GPIO as inputs. D*/ /*F*/ @@ -4048,6 +4136,9 @@ high and low levels. *param:: An array of script parameters. +percent:: 0-100 +The size of waveform as percentage of maximum available. + pi:: An integer defining a connected Pi. The value is returned by [*pigpio_start*] upon success. diff --git a/pigs.1 b/pigs.1 index 3b5d30b..1d9bf6f 100644 --- a/pigs.1 +++ b/pigs.1 @@ -548,6 +548,9 @@ Add serial data to waveform .B WVCRE Create a waveform .P +.B WVCAP percent +Create a waveform of fixed size +.P .B WVDEL wid Delete selected waveform .P @@ -925,14 +928,6 @@ The output process is simple. You simply append data to the FIFO buffer on the chip. This works like a queue, you add data to the queue and the master removes it. -.br -This function is not available on the BCM2711 (e.g. as -used in the Pi4B). - -.br -I can't get SPI to work properly. I tried with a -control word of 0x303 and swapped MISO and MOSI. - .br The command sets the BSC mode and writes any data \fBbvs\fP to the BSC transmit FIFO. It returns the data count (at least 1 @@ -950,12 +945,31 @@ For I2C use a control word of (I2C address << 16) + 0x305. E.g. to talk as I2C slave with address 0x13 use 0x130305. .br -The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL) in I2C mode -and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO), and 21 (CE) in SPI mode. You -need to swap MISO/MOSI between master and slave. +GPIO used for models other than those based on the BCM2711. .br -When a zero control word is received GPIO 18-21 will be reset + +.EX + SDA SCL MOSI SCLK MISO CE +I2C 18 19 - - - - +SPI - - 20 19 18 21 + +.EE + +.br +GPIO used for models based on the BCM2711 (e.g. the Pi4B). + +.br + +.EX + SDA SCL MOSI SCLK MISO CE +I2C 10 11 - - - - +SPI - - 9 11 10 8 + +.EE + +.br +When a zero control word is received the used GPIO will be reset to INPUT mode. .br @@ -1031,7 +1045,8 @@ TB transmit busy .EE .br -This example assumes that GPIO 2/3 are connected to GPIO 18/19. +This example assumes that GPIO 2/3 are connected to GPIO 18/19 +(GPIO 10/11 on the BCM2711). .br @@ -1120,6 +1135,57 @@ $ pigs i2crd 0 5 .EE +.br +The BSC slave in SPI mode deserializes data from the MOSI pin into its receiver/ +FIFO when the LSB of the first byte is a 0. No data is output on the MISO pin. +When the LSB of the first byte on MOSI is a 1, the transmitter/FIFO data is +serialized onto the MISO pin while all other data on the MOSI pin is ignored. + +.br +The BK bit of the BSC control register is non-functional when in the SPI mode. +The transmitter along with its FIFO can be dequeued by successively disabling +and re-enabling the TE bit on the BSC control register while in SPI mode. + +.br +This example demonstrates a SPI master talking to the BSC as SPI slave: +Requires SPI master SCLK / MOSI / MISO / CE GPIO are connected to +BSC peripheral GPIO 11 / 9 / 10 / 8 respectively, on a Pi4B (BCM2711). + +.br + +\fBExample\fP +.br + +.EX +$ pigs bspio 15 26 13 14 10000 0 # open bit-bang spi master on random gpio +.br + +.br +$ pigs bscx 0x303 # start BSC as SPI slave, both rx and tx enabled +.br +1 18 +.br + +.br +$ pigs bspix 15 0 0xd 0xe 0xa 0xd # write 0xdead to BSC +.br +5 0 0 0 0 0 +.br + +.br +$ pigs bscx 0x303 0xb 0xe 0xe 0xf # place 0xbeef in BSC tx FIFO, read rx FIFO +.br +5 262338 13 14 10 13 +.br + +.br +$ pigs bspix 15 1 0 0 0 0 # read four bytes from BSC +.br +5 0 11 14 14 15 +.br + +.EE + .br .IP "\fBBSPIC cs\fP - Close bit bang SPI" @@ -4804,7 +4870,7 @@ $ pigs wvas 7 38400 8 2 0 0x41 0x42 .br This command returns the id of the waveform currently -being transmitted. +being transmitted. Chained waves are not supported. .br Returns the waveform id or one of the following special @@ -5123,6 +5189,72 @@ ERROR: attempt to create an empty waveform .br +.IP "\fBWVCAP percent\fP - Create a waveform of fixed size" +.IP "" 4 + +.br +Create a waveform of fixed size. Similar to \fBWVCRE\fP, this command creates a waveform but pads the consumed resources to a fixed size, specified as a \fBpercent\fP of the total resources. Padded waves of equal size can be re-cycled efficiently allowing newly created waves to re-use the resources of deleted waves of the same dimension. + +.br +Upon success a wave id (>=0) is returned. On error a negative status code will be returned. + +.br +The data provided by the \fBWVAG\fP and \fBWVAS\fP commands are consumed by this command. + +.br +As many waveforms may be created as there is space available. The wave id is passed to \fBWVTX\fP or \fBWVTXR\fP to specify the waveform to transmit. + +.br +Normal usage would be + +.br +Step 1. \fBWVCLR\fP to clear all waveforms and added data. + +.br +Step 2. \fBWVAG\fP/\fBWVAS\fP calls to supply the waveform data. + +.br +Step 3. \fBWVCAP\fP to create a waveform of a uniform size. + +.br +Step 4. \fBWVTX\fP or \fBWVTXR\fP with the id of the waveform to transmit. + +.br +Repeat steps 2 - 4 as needed. + +.br +Step 5. Any wave id can now be deleted and another wave of the same size can be created in its place. + +.br +Example + +.br + +\fBExample\fP +.br + +.EX +# Create a wave that consumes 50% of the total resource: +.br + +.br +$ pigs wvag 16 0 5000000 0 16 5000000 +.br +2 +.br +$ pigs wvcap 50 +.br +0 +.br +$ pigs wvtx 0 +.br +11918 +.br + +.EE + +.br + .IP "\fBWVDEL wid\fP - Delete selected waveform" .IP "" 4 @@ -5791,6 +5923,13 @@ The command expects a dutycycle. .br +.IP "\fBpercent\fP - percent (1-100)" 0 +The percent of wave resources to allocate to a wave. It can be useful +to create waves of fixed sizes to prevent wave fragmentation (where +there are plenty of resources but not a large enough contiguous space). + +.br + .IP "\fBpf\fP - hardware PWM frequency (1-125M, 1-187.5M for the BCM2711)" 0 The command expects a frequency. diff --git a/setup.py b/setup.py index 00f70a0..4dbb8a9 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from distutils.core import setup setup(name='pigpio', - version='1.45', + version='1.78', author='joan', author_email='joan@abyz.me.uk', maintainer='joan', diff --git a/util/pigpiod b/util/pigpiod deleted file mode 100755 index 59ba142..0000000 --- a/util/pigpiod +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -### BEGIN INIT INFO -# Provides: pigpiod -# Required-Start: -# Required-Stop: -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: pigpio daemon -# Description: pigpio daemon required to control GPIO pins via pigpio $ -### END INIT INFO - -# Actions -case "$1" in - start) - pigpiod - ;; - stop) - pkill pigpiod - ;; - restart) - pkill pigpiod - pigpiod - ;; - *) - echo "Usage: $0 start" >&2 - exit 3 - ;; -esac - -exit 0 - diff --git a/util/pigpiod.service b/util/pigpiod.service index a0bb916..f040d38 100644 --- a/util/pigpiod.service +++ b/util/pigpiod.service @@ -3,6 +3,7 @@ Description=Pigpio daemon [Service] Type=forking +PIDFile=pigpio.pid ExecStart=/usr/bin/pigpiod [Install] diff --git a/x_pigpio.c b/x_pigpio.c index cd15389..8119d73 100644 --- a/x_pigpio.c +++ b/x_pigpio.c @@ -459,6 +459,51 @@ To the lascivious pleasing of a lute.\n\ c = gpioWaveGetMaxCbs(); CHECK(5, 21, c, 25016, 0, "wave get max cbs"); + + /* waveCreatePad tests */ + gpioWaveTxStop(); + gpioWaveClear(); + gpioSetAlertFunc(GPIO, t5cbf); + + e = gpioWaveAddGeneric(2, (gpioPulse_t[]) + { {1<