1
0
mirror of https://github.com/xtacocorex/CHIP_IO synced 2025-07-20 12:53:22 +00:00

52 Commits

Author SHA1 Message Date
84df4376f8 added logging to inform user of 1s retry if set_direction fails on the first try, updating to v0.7.1 2017-11-12 08:06:35 -06:00
906beb0257 Merge pull request #80 from MEitelwein/master
add 1s delay in set_direction to allow udev to set permissions
2017-11-12 07:31:02 -06:00
00cd5c09ad add 1s delay in set_direction to allow udev to set permissions 2017-11-11 19:08:02 +00:00
c87b0ca72a Merge pull request #79 from futuristicblanket/master
Fixed a small spelling error of the word 'note' in the readme
2017-10-22 11:44:53 -05:00
ff7bf2fa1c Fixed a small spelling error of the word 'note' 2017-10-14 10:44:27 +10:00
af9555fcdf updating the GPIO docs to reference ability to control pins via sysfs numbers 2017-09-13 11:45:20 -05:00
e7db735a2f GPIO able to be controlled by pin sysfs number like RPi.GPIO, close #65 2017-09-13 10:35:32 -05:00
e3a077bf82 implementation and close #75 - enabling a timeout for the wait_for_edge function 2017-09-03 21:43:59 -05:00
a0b2ac12a6 Adding the ability to generate wheel packages for uploading to pypi, thanks to help from pztrick. This will close #77 2017-09-02 21:04:24 -05:00
6af974c113 fixing implementation of #76 since i didn't actually test it 2017-08-09 23:18:16 -05:00
4670e44758 API documentation complete, closing #74 and closing #73 2017-08-09 22:54:20 -05:00
2247e9d234 fixing table formatting on the docs index page 2017-08-07 22:25:42 -05:00
ff91bcd0d1 cleanup of the readme and adding pin name table to doc index 2017-08-07 22:13:58 -05:00
35619e5baf adding code to close #76 2017-08-07 22:06:15 -05:00
1e3935c8ea finalizing servo, softpwm, and pwm api docs, cleanup of code comments for #73 2017-08-07 22:02:16 -05:00
e038fc9c89 actually finishing servo api docs 2017-08-07 21:24:15 -05:00
5b016887fe finishing servo api docs 2017-08-07 21:23:11 -05:00
aa76edb7b3 finished lradc api docs 2017-08-07 21:04:21 -05:00
d84c3c03d7 fixing a utilities function definition 2017-07-04 19:35:30 -05:00
c47fb197f5 utilities api documentaiton complete 2017-07-04 19:34:30 -05:00
a6111d8245 finished overlaymanager api docs 2017-07-04 17:03:44 -05:00
71923f5739 added overlaymanager.md 2017-07-04 15:10:35 -05:00
c9b0ae4229 moving the docs to separate files as it will be easier to maintain 2017-07-04 12:05:03 -05:00
5aef829dd1 another test commit of documentation formatting 2017-07-04 11:56:22 -05:00
3c3ec494dd test commit of documentation formatting 2017-07-04 11:52:56 -05:00
bb5f0083e8 start of api docs 2017-07-04 11:28:21 -05:00
408bf60ffa Set theme jekyll-theme-minimal 2017-07-04 11:18:06 -05:00
310c4a9ae4 adding docs folder 2017-07-04 11:16:38 -05:00
014dcb8a36 Updated README to close #71 2017-06-28 20:11:05 -05:00
6e93fad1de README updates following the merge of PR#70 into master 2017-06-08 20:06:52 -05:00
41d4b84c56 Merge pull request #70 from mzealey/master
Extern integer definitions in the header file
2017-06-08 19:19:17 -05:00
024e5d5797 Extern integer definitions in the header file
Integers are defined in both the .c and the common.h file leading to linking
issues with the library when used externally and potentially causing issues
within the code as well.
2017-06-08 15:23:32 +00:00
6ddd0e0b14 Closing out Issue #68 by adding 3 CHIP Pro pins able to be used as interrupts 2017-05-02 22:46:10 -05:00
d4b1d8a41c adding i2s pins as gpio capable for the chip pro, code to handle per pwm/softpwm cleanup to close #64 2017-05-01 22:50:17 -05:00
2b48571ee3 Updating setup to allow for repeated calls on a pin. Not totally sold on this, but it work and is what RPi.GPIO does. This will close #63 2017-03-20 23:06:09 -05:00
38a34e7edf Updating the README to clean up how to do callbacks for more clarification on #62 2017-03-07 07:22:09 -06:00
f32733bb07 Updating the Readme to add a note regarding one callback per pin 2017-03-06 17:53:34 -06:00
4da0812acd Fixing issue where using alt name for the XIO would cause a segfault when speficying the pin as an input. This will close #62 2017-03-06 17:08:05 -06:00
dcd8ea6f40 Re-enabled polarity set on the CHIP PWM, fixed issues that caused me to disable that feature to begin with. This could have been a 1 letter change, but I re-eabled tests in the unit test to validate. This will close #61 2017-03-05 00:49:16 -06:00
29377cf24d updates to the pytest tests to fix the issues with pwm, added 2 new tests that bring in 5 total unit tests. python3 unit tests are passing, this will close #42 and close #47 2017-02-26 21:04:40 -06:00
f7bec3f891 forgot to update the chip pro detection in Utilties, removed overlay stuff from makefile, cleaned up readme 2017-02-26 14:07:11 -06:00
48d9343dba forgot to update the manifest to remove the overlay stuff 2017-02-25 19:43:29 -06:00
bab94f7600 forgot the actual version bump for #32. gonna close #32 since it's initially done 2017-02-25 19:17:25 -06:00
dab60b334d version updates prior to merge 2017-02-25 19:09:47 -06:00
c3ead5d395 fixing issues with the code to determine if the computer is a chip/chip pro for #32 2017-02-26 00:50:54 +00:00
121ad398e4 new method for determining if the computer is a chip/chip pro, this fixes the runtimeerror's i was getting. for #32 2017-02-25 17:06:38 -06:00
c21c431b7b pwm1 works on the chip pro, commit to allow me to reset all the changes that broke stuff on the normal chip 2017-02-25 12:48:36 -06:00
f66740b797 pwm1 and pwm0 working on chip pro. thanks ntc for the awesome led's on the devkit, they're super helpful 2017-02-21 05:26:56 +00:00
ca7d221b33 More work on #32, Checks for gpio being invalid on specific hardware, pwm invalid checks done. Need to do proper export of PWM1 on CHIP Pro 2017-02-20 05:03:04 +00:00
e179e52b5e Merge branch 'master' into feature/chippro 2017-02-19 17:57:59 +00:00
fa3108544b First stab as getting a capability to dump out .deb files for both Python2 and Python3. 2017-02-19 10:06:22 -06:00
c5dbede3c4 Formal initial start at CHIP Pro support. Removed the custom DT Overlays, OverlayManager now pulls dtbo from chip-dt-overlays package from NTC. First commit to CHIP_IO from a CPro DevKit 2017-02-13 05:18:33 +00:00
48 changed files with 3095 additions and 467 deletions

View File

@ -1,3 +1,76 @@
0.7.1
---
* Merged in PR #79
* Merged in PR #80
* Added message notifying user of the gpio set direction retry
0.7.0
---
* Added ability to specify GPIO only as a number, this doesn't work for PWM/SPWM/LRADC/SERVO
0.6.2
---
* Implementation for #77 - ability to push up binary pypi
* Implementation for #75 - wait_for_edge timeout
0.6.1
---
* Fixing implementation for #76
0.6
---
* Random comment cleanup
* Implement fix for #76
* API documentation added
* Closing #74
0.5.9
---
* Merged PR#70 to enable the underlying C code to be used properly in C based code
* Updated README to add missing pins on the CHIP Pro that are available as GPIO
* Updated README to denote pins that are available for Edge Detection
0.5.8
---
* Added 3 pins for the CHIP Pro as allowable for setting callbacks and edge detection to close out Issue #68
0.5.7
---
* Added the I2S pins on the CHIP Pro as GPIO capable
* Added per PWM/SoftPWM cleanup per Issue #64
0.5.6
---
* Fix for Issue #63 where re-setting up a pin wasn't lining up with RPi.GPIO standards. Calling setup after the first time will now update direction.
* README updates to point out the direction() function since that was missing
0.5.5
---
* Fix for Issue #62 where using alternate name of an XIO would cause a segfault due to trying to set pull up/down resistor setting
0.5.4
---
* Re-enabled the polarity setting for PWM based upon Issue #61
* Fixed a 1 letter bug was trying to write inverted to polarity when it wants inversed (such facepalm)
* Cleaned up the polarity setting code to work when PWM is not enabled
* Fixed the unit test for pwm to verify we can set polarity
0.5.3
---
* Fixes to the PWM pytest
* Added pytest for LRADC and Utilities
* Makefile updates for all the things
0.5.2
---
* Updating Utilties to determine CHIP Pro better
* Updating the README to fix things
0.5.0
---
* CHIP Pro Support
* README Updates
0.4.0 0.4.0
--- ---
* Software Servo code added * Software Servo code added

View File

@ -46,8 +46,10 @@ def toggle_debug():
global DEBUG global DEBUG
if DEBUG: if DEBUG:
DEBUG = False DEBUG = False
print("debug disabled")
else: else:
DEBUG = True DEBUG = True
print("debug enabled")
def setup(rate=250): def setup(rate=250):
# First we determine if the device exists # First we determine if the device exists

View File

@ -20,11 +20,12 @@
import os import os
import shutil import shutil
import time import time
import sys
from .Utilities import is_chip_pro
DEBUG = False DEBUG = False
OVERLAYINSTALLPATH = "/lib/firmware/chip_io" OVERLAYINSTALLPATH = "/lib/firmware/nextthingco/chip"
SPIINSTALLPATH = "/lib/firmware/nextthingco/chip"
OVERLAYCONFIGPATH = "/sys/kernel/config/device-tree/overlays" OVERLAYCONFIGPATH = "/sys/kernel/config/device-tree/overlays"
CUSTOMOVERLAYFILEPATH = "" CUSTOMOVERLAYFILEPATH = ""
@ -43,7 +44,7 @@ _LOADED = {
_OVERLAYS = { _OVERLAYS = {
"SPI2" : "sample-spi.dtbo", "SPI2" : "sample-spi.dtbo",
"PWM0" : "chip-pwm0.dtbo", "PWM0" : "sample-pwm.dtbo",
"CUST" : "" "CUST" : ""
} }
@ -57,8 +58,10 @@ def toggle_debug():
global DEBUG global DEBUG
if DEBUG: if DEBUG:
DEBUG = False DEBUG = False
print("debug disabled")
else: else:
DEBUG = True DEBUG = True
print("debug enabled")
def get_spi_loaded(): def get_spi_loaded():
""" """
@ -159,12 +162,14 @@ def load(overlay, path=""):
print("Custom Overlay path does not exist") print("Custom Overlay path does not exist")
return 1 return 1
# DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO LOAD PWM0
if is_chip_pro() and overlay.upper() == "PWM0":
print("CHIP Pro supports PWM0 in base DTB, exiting")
return 1
# SET UP THE OVERLAY PATH FOR OUR USE # SET UP THE OVERLAY PATH FOR OUR USE
if overlay.upper() != "CUST": if overlay.upper() != "CUST":
opath = OVERLAYINSTALLPATH opath = OVERLAYINSTALLPATH
# IF THE OVERLAY IS SPI, USE THE NTC PATH
if overlay.upper() == "SPI2":
opath = SPIINSTALLPATH
opath += "/" + _OVERLAYS[overlay.upper()] opath += "/" + _OVERLAYS[overlay.upper()]
else: else:
opath = path opath = path
@ -194,6 +199,12 @@ def unload(overlay):
global _LOADED global _LOADED
if DEBUG: if DEBUG:
print("UNLOAD OVERLAY: {0}".format(overlay)) print("UNLOAD OVERLAY: {0}".format(overlay))
# DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO UNLOAD PWM0
if is_chip_pro() and overlay.upper() == "PWM0":
print("CHIP Pro supports PWM0 in base DTB, exiting")
return
# SEE IF OUR OVERLAY NAME IS IN THE KEYS # SEE IF OUR OVERLAY NAME IS IN THE KEYS
if overlay.upper() in _OVERLAYS.keys(): if overlay.upper() in _OVERLAYS.keys():
# BRUTE FORCE REMOVE AS THE DIRECTORY CONTAINS FILES # BRUTE FORCE REMOVE AS THE DIRECTORY CONTAINS FILES

View File

@ -35,12 +35,15 @@ def toggle_debug():
global DEBUG global DEBUG
if DEBUG: if DEBUG:
DEBUG = False DEBUG = False
print("debug disabled")
else: else:
DEBUG = True DEBUG = True
print("debug enabled")
# Set the 1.8V-pin on the CHIP U13-header to given voltage # Set the 1.8V-pin on the CHIP U13-header to given voltage
# Return False on error # Return False on error
def set_1v8_pin_voltage(voltage): def set_1v8_pin_voltage(voltage):
if not is_chip_pro():
if not isinstance(voltage, int) and not isinstance(voltage, float): if not isinstance(voltage, int) and not isinstance(voltage, float):
return False return False
if voltage < 1.8 or voltage > 3.3: if voltage < 1.8 or voltage > 3.3:
@ -57,10 +60,13 @@ def set_1v8_pin_voltage(voltage):
print("Pin set voltage command failed") print("Pin set voltage command failed")
return False return False
return True return True
else:
print("Set 1.8V Pin Voltage not supported on the CHIP Pro")
# Get the voltage the 1.8V-pin on the CHIP U13-header has been configured as # Get the voltage the 1.8V-pin on the CHIP U13-header has been configured as
# Return False on error # Return False on error
def get_1v8_pin_voltage(): def get_1v8_pin_voltage():
if not is_chip_pro():
p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x90"], stdout=subprocess.PIPE) p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x90"], stdout=subprocess.PIPE)
output=p.communicate()[0].decode("utf-8").strip() output=p.communicate()[0].decode("utf-8").strip()
#Not configured as an output #Not configured as an output
@ -74,13 +80,20 @@ def get_1v8_pin_voltage():
if DEBUG: if DEBUG:
print("Current 1.8V Pin voltage: {0}".format(voltage)) print("Current 1.8V Pin voltage: {0}".format(voltage))
return voltage return voltage
else:
print("Get 1.8V Pin Voltage not supported on the CHIP Pro")
# Enable 1.8V Pin on CHIP U13 Header # Enable 1.8V Pin on CHIP U13 Header
def enable_1v8_pin(): def enable_1v8_pin():
if not is_chip_pro():
set_1v8_pin_voltage(1.8) set_1v8_pin_voltage(1.8)
else:
print("Enable 1.8V Pin not supported on the CHIP Pro")
# Disable 1.8V Pin on CHIP U13 Header # Disable 1.8V Pin on CHIP U13 Header
def disable_1v8_pin(): def disable_1v8_pin():
if not is_chip_pro():
if DEBUG: if DEBUG:
print("Disabling the 1.8V Pin") print("Disabling the 1.8V Pin")
# CANNOT USE I2C LIB AS WE NEED TO FORCE THE COMMAND DUE TO THE KERNEL OWNING THE DEVICE # CANNOT USE I2C LIB AS WE NEED TO FORCE THE COMMAND DUE TO THE KERNEL OWNING THE DEVICE
@ -88,6 +101,8 @@ def disable_1v8_pin():
subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x91 0x05', shell=True) subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x91 0x05', shell=True)
# Then we have to write 0x07 to AXP-209 Register 0x90 # Then we have to write 0x07 to AXP-209 Register 0x90
subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x90 0x07', shell=True) subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x90 0x07', shell=True)
else:
print("Disable 1.8V Pin not supported on the CHIP Pro")
# Unexport All # Unexport All
def unexport_all(): def unexport_all():
@ -101,3 +116,29 @@ def unexport_all():
cmd = "echo " + num + " > /sys/class/gpio/unexport" cmd = "echo " + num + " > /sys/class/gpio/unexport"
subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE) subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
# Determine Processor
def is_chip_pro():
isgr8 = False
if DEBUG:
print("Determining if computer is CHIP or CHIP Pro")
# GET FIRST LINE FROM /proc/meminfo
f = open("/proc/meminfo","r")
fline = f.readline()
f.close()
# FIGURE OUT OUR TOTAL MEMORY SIZE
parts = fline.split()
mem = float(parts[1]) / 1024
if mem > 380:
isgr8 = False
if DEBUG:
print("found CHIP!")
else:
isgr8 = True
if DEBUG:
print("found CHIP Pro!")
# Return isgr8
return isgr8

View File

@ -2,4 +2,3 @@ include distribute_setup.py
include README.rst include README.rst
include CHANGELOG.rst include CHANGELOG.rst
recursive-include source *.h recursive-include source *.h
recursive-include overlays *.dts *.py

View File

@ -1,19 +1,67 @@
# PyPi Packaging
package: clean package: clean
python setup.py sdist @echo " ** PACKAGING FOR PYPI **"
python setup.py sdist bdist_wheel
python3 setup.py bdist_wheel
publish: package # PyPi Packaging
package3: package
@echo " ** PACKAGING FOR PYPI **"
python3 setup.py bdist_wheel
# PyPi Publishing
publish: package package3
@echo " ** UPLOADING TO PYPI **"
twine upload dist/* twine upload dist/*
# Clean all the things
clean: clean:
@echo " ** CLEANING CHIP_IO **"
rm -rf CHIP_IO.* build dist rm -rf CHIP_IO.* build dist
rm -f *.pyo *.pyc rm -f *.pyo *.pyc
rm -f *.egg rm -f *.egg
rm -f overlays/*.pyo overlays/*.pyc rm -rf __pycache__
tests: rm -rf test/__pycache__/
py.test rm -rf debian/python-chip-io*
rm -rf debian/python3-chip-io*
# Run all the tests
tests: pytest2 pytest3
# Run the tests with Python 2
pytest2:
@echo " ** RUNING CHIP_IO TESTS UNDER PYTHON 2 **"
pushd test; python -m pytest; popd
# Run the tests with Python 3
pytest3:
@echo " ** RUNING CHIP_IO TESTS UNDER PYTHON 3 **"
pushd test; python3 -m pytest; popd
# Build all the things
build: build:
@echo " ** BUILDING CHIP_IO: PYTHON 2 **"
python setup.py build --force python setup.py build --force
# Install all the things
install: build install: build
@echo " ** INSTALLING CHIP_IO: PYTHON 2 **"
python setup.py install --force python setup.py install --force
# Build for Python 3
build3:
@echo " ** BUILDING CHIP_IO: PYTHON 3 **"
python3 setup.py build --force
# Install for Python 3
install3: build3
@echo " ** INSTALLING CHIP_IO: PYTHON 3 **"
python3 setup.py install --force
# Install for both Python 2 and 3
all: install install3
# Create a deb file
debfile:
@echo " ** BUILDING DEBIAN PACKAGES **"
dpkg-buildpackage -rfakeroot -uc -b

View File

@ -2,19 +2,25 @@ CHIP_IO
============================ ============================
A CHIP GPIO library A CHIP GPIO library
NOTE: Now requires the custom DTC to install the library Debian File Installation:
Manual:: There are now pre-compiled binary deb files for the CHIP that do not require any build tools on a CHIP/CHIP Pro.
Go to this page: https://github.com/xtacocorex/CHIP_IO/releases/latest
Or
Go to this page: https://xtacocorex.github.io/chip_io_releases/index.html
Download the .deb file for the version of Python you are running.
Then install with dpkg, like the following example:
sudo dpkg -i python-chip-io_0.5.9-1_armhf.deb
Manual Installation::
For Python2.7:: For Python2.7::
sudo apt-get update sudo apt-get update
sudo apt-get install git build-essential python-dev python-pip flex bison chip-dt-overlays -y sudo apt-get install git build-essential python-dev python-pip flex bison chip-dt-overlays -y
git clone https://github.com/atenart/dtc.git
cd dtc
make
sudo make install PREFIX=/usr
cd ..
git clone git://github.com/xtacocorex/CHIP_IO.git git clone git://github.com/xtacocorex/CHIP_IO.git
cd CHIP_IO cd CHIP_IO
sudo python setup.py install sudo python setup.py install
@ -24,16 +30,25 @@ For Python3::
sudo apt-get update sudo apt-get update
sudo apt-get install git build-essential python3-dev python3-pip flex bison chip-dt-overlays -y sudo apt-get install git build-essential python3-dev python3-pip flex bison chip-dt-overlays -y
git clone https://github.com/atenart/dtc.git
cd dtc
make
sudo make install PREFIX=/usr
cd ..
git clone git://github.com/xtacocorex/CHIP_IO.git git clone git://github.com/xtacocorex/CHIP_IO.git
cd CHIP_IO cd CHIP_IO
sudo python3 setup.py install sudo python3 setup.py install
cd .. cd ..
PyPi Installation::
For Python2.7::
sudo apt-get update
sudo apt-get install git build-essential python-dev python-pip flex bison chip-dt-overlays -y
sudo pip install CHIP-IO
For Python3::
sudo apt-get update
sudo apt-get install git build-essential python3-dev python3-pip flex bison chip-dt-overlays -y
sudo pip3 install CHIP-IO
**Usage** **Usage**
Using the library is very similar to the excellent RPi.GPIO library used on the Raspberry Pi. Below are some examples. Using the library is very similar to the excellent RPi.GPIO library used on the Raspberry Pi. Below are some examples.
@ -44,113 +59,125 @@ All scripts that require GPIO, PWM (HW and/or SW), and Overlay Manager need to b
The following "table" is the allowable pin names that are able to be used by the library. The Name column is the normal name used on the CHIP Headers, the Alt Name column is the value used by the PocketCHIP header (if it's broken out), and the Key is the Header and Pin Number the the Pin is physically located. Either of these 3 means is able to specify a pin in CHIP_IO. The following "table" is the allowable pin names that are able to be used by the library. The Name column is the normal name used on the CHIP Headers, the Alt Name column is the value used by the PocketCHIP header (if it's broken out), and the Key is the Header and Pin Number the the Pin is physically located. Either of these 3 means is able to specify a pin in CHIP_IO.
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CHIP (Name) | PocketCHIP (Alt Name) | Key | | CHIP (Main Name) | PocketCHIP/CHIP Pro Name | Key (Alt Name) | HW Support | Edge Detect |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| TWI1-SDA | KPD-I2C-SDA | U13_9 | | TWI1-SDA | KPD-I2C-SDA | U13_9 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| TWI1-SCK | KPD-I2C-SCL | U13_11 | | TWI1-SCK | KPD-I2C-SCL | U13_11 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D2 | LCD-D2 | U13_17 | | LCD-D2 | UART2-TX | U13_17 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| PWM0 | PWM0 | U13_18 | | PWM0 | PWM0 | U13_18 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D4 | LCD-D4 | U13_19 | | PWM1 | PWM1 | EINT13 | CHIP PRO | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D3 | LCD-D3 | U13_20 | | LCD-D4 | UART2-CTS | U13_19 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D6 | LCD-D6 | U13_21 | | LCD-D3 | UART2-RX | U13_20 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D5 | LCD-D5 | U13_22 | | LCD-D6 | LCD-D6 | U13_21 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D10 | LCD-D10 | U13_23 | | LCD-D5 | UART2-RTS | U13_22 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D7 | LCD-D7 | U13_24 | | LCD-D10 | LCD-D10 | U13_23 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D12 | LCD-D12 | U13_25 | | LCD-D7 | LCD-D7 | U13_24 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D11 | LCD-D11 | U13_26 | | LCD-D12 | LCD-D12 | U13_25 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D14 | LCD-D14 | U13_27 | | LCD-D11 | LCD-D11 | U13_26 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D13 | LCD-D13 | U13_28 | | LCD-D14 | LCD-D14 | U13_27 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D18 | LCD-D18 | U13_29 | | LCD-D13 | LCD-D13 | U13_28 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D15 | LCD-D15 | U13_30 | | LCD-D18 | LCD-D18 | U13_29 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D20 | LCD-D20 | U13_31 | | LCD-D15 | LCD-D15 | U13_30 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D19 | LCD-D19 | U13_32 | | LCD-D20 | LCD-D20 | U13_31 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D22 | LCD-D22 | U13_33 | | LCD-D19 | LCD-D19 | U13_32 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D21 | LCD-D21 | U13_34 | | LCD-D22 | LCD-D22 | U13_33 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-CLK | LCD-CLK | U13_35 | | LCD-D21 | LCD-D21 | U13_34 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-D23 | LCD-D23 | U13_36 | | LCD-CLK | LCD-CLK | U13_35 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-VSYNC | LCD-VSYNC | U13_37 | | LCD-D23 | LCD-D23 | U13_36 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-HSYNC | LCD-HSYNC | U13_38 | | LCD-VSYNC | LCD-VSYNC | U13_37 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LCD-DE | LCD-DE | U13_40 | | LCD-HSYNC | LCD-HSYNC | U13_38 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| UART1-TX | UART-TX | U14_3 | | LCD-DE | LCD-DE | U13_40 | CHIP | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| UART1-RX | UART-RX | U14_5 | | UART1-TX | UART-TX | U14_3 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| LRADC | ADC | U14_11 | | UART1-RX | UART-RX | U14_5 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P0 | XIO-P0 | U14_13 | | LRADC | ADC | U14_11 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P1 | XIO-P1 | U14_14 | | XIO-P0 | XIO-P0 | U14_13 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P2 | GPIO1 | U14_15 | | XIO-P1 | XIO-P1 | U14_14 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P3 | GPIO2 | U14_16 | | XIO-P2 | GPIO1 | U14_15 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P4 | GPIO3 | U14_17 | | XIO-P3 | GPIO2 | U14_16 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P5 | GPIO4 | U14_18 | | XIO-P4 | GPIO3 | U14_17 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P6 | GPIO5 | U14_19 | | XIO-P5 | GPIO4 | U14_18 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| XIO-P7 | GPIO6 | U14_20 | | XIO-P6 | GPIO5 | U14_19 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| AP-EINT1 | KPD-INT | U14_23 | | XIO-P7 | GPIO6 | U14_20 | CHIP | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| AP-EINT3 | AP-INT3 | U14_24 | | AP-EINT1 | KPD-INT | U14_23 | CHIP/CHIP PRO | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| TWI2-SDA | I2C-SDA | U14_25 | | AP-EINT3 | AP-INT3 | U14_24 | CHIP/CHIP PRO | YES |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| TWI2-SCK | I2C-SCL | U14_26 | | TWI2-SDA | I2C-SDA | U14_25 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSIPCK | SPI-SEL | U14_27 | | TWI2-SCK | I2C-SCL | U14_26 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSICK | SPI-CLK | U14_28 | | CSIPCK | SPI-SEL | U14_27 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSIHSYNC | SPI-MOSI | U14_29 | | CSICK | SPI-CLK | U14_28 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSIVSYNC | SPI-MISO | U14_30 | | CSIHSYNC | SPI-MOSI | U14_29 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID0 | CSID0 | U14_31 | | CSIVSYNC | SPI-MISO | U14_30 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID1 | CSID1 | U14_32 | | CSID0 | D0 | U14_31 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID2 | CSID2 | U14_33 | | CSID1 | D1 | U14_32 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID3 | CSID3 | U14_34 | | CSID2 | D2 | U14_33 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID4 | CSID4 | U14_35 | | CSID3 | D3 | U14_34 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID5 | CSID5 | U14_36 | | CSID4 | D4 | U14_35 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID6 | CSID6 | U14_37 | | CSID5 | D5 | U14_36 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID7 | CSID7 | U14_38 | | CSID6 | D6 | U14_37 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+--------+ +------------------+--------------------------+----------------+-----------------+-----------------+
| CSID7 | D7 | U14_38 | CHIP/CHIP PRO | NO |
+------------------+--------------------------+----------------+-----------------+-----------------+
| I2S-MCLK | EINT19 | 21 | CHIP PRO | YES |
+------------------+--------------------------+----------------+-----------------+-----------------+
| I2S-BCLK | I2S-BCLK | 22 | CHIP PRO | NO |
+------------------+--------------------------+----------------+-----------------+-----------------+
| I2S-LCLK | I2S-LCLK | 23 | CHIP PRO | NO |
+------------------+--------------------------+----------------+-----------------+-----------------+
| I2S-DO | EINT19 | 24 | CHIP PRO | NO |
+------------------+--------------------------+----------------+-----------------+-----------------+
| I2S-DI | EINT24 | 25 | CHIP PRO | YES |
+------------------+--------------------------+----------------+-----------------+-----------------+
**GPIO Setup** **GPIO Setup**
@ -167,13 +194,20 @@ You can also refer to the bin based upon its alternate name::
GPIO.setup("GPIO1", GPIO.IN) GPIO.setup("GPIO1", GPIO.IN)
**GPIO Debug** **GPIO Miscellaneous**
Debug can be enabled/disabled by the following command:: Debug can be enabled/disabled by the following command::
# Enable Debug # Enable Debug
GPIO.toggle_debug() GPIO.toggle_debug()
You can determine if the hardware is a CHIP/CHIP Pro using the following::
# Determine hardware
# 0 For CHIP
# 1 For CHIP Pro
GPIO.is_chip_pro()
**GPIO Output** **GPIO Output**
Setup the pin for output, and write GPIO.HIGH or GPIO.LOW. Or you can use 1 or 0.:: Setup the pin for output, and write GPIO.HIGH or GPIO.LOW. Or you can use 1 or 0.::
@ -193,6 +227,7 @@ Other options when setting up pins::
# Specify pull up/pull down settings on a pin # Specify pull up/pull down settings on a pin
GPIO.setup("CSID0", GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup("CSID0", GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Specify initial value for an output # Specify initial value for an output
GPIO.setup("CSID0", GPIO.OUT, initial=1) GPIO.setup("CSID0", GPIO.OUT, initial=1)
@ -209,11 +244,22 @@ Read lots of data::
# Get 8 bits of data in one shot # Get 8 bits of data in one shot
mybyte = GPIO.read_byte("LCD-D3") mybyte = GPIO.read_byte("LCD-D3")
# Get 16 bits of data in one shot # Get 16 bits of data in one shot
myword = GPIO.read_word("XIO-P4") myword = GPIO.read_word("XIO-P4")
This code was initially added by brettcvz and I cleaned it up and expanded it. This code was initially added by brettcvz and I cleaned it up and expanded it.
You can quickly change a pins direction::
GPIO.direction("XIO-P3", GPIO.OUT)
GPIO.direction("XIO-P3", GPIO.IN)
You can also re-setup a pin in order to change direction, note that this is a slower operation::
GPIO.setup("XIO-P3", GPIO.OUT)
GPIO.setup("XIO-P3", GPIO.IN)
The edge detection code below only works for the AP-EINT1, AP-EINT3, and XPO Pins on the CHIP. The edge detection code below only works for the AP-EINT1, AP-EINT3, and XPO Pins on the CHIP.
Waiting for an edge (GPIO.RISING, GPIO.FALLING, or GPIO.BOTH:: Waiting for an edge (GPIO.RISING, GPIO.FALLING, or GPIO.BOTH::
@ -225,25 +271,35 @@ Detecting events::
GPIO.setup("XIO-P0", GPIO.IN) GPIO.setup("XIO-P0", GPIO.IN)
GPIO.add_event_detect("XIO-P0", GPIO.FALLING) GPIO.add_event_detect("XIO-P0", GPIO.FALLING)
#your amazing code here #your amazing code here
#detect wherever: #detect wherever:
if GPIO.event_detected("XIO-P0"): if GPIO.event_detected("XIO-P0"):
print "event detected!" print "event detected!"
CHIP_IO can also handle adding callback functions on any pin that supports edge detection.:: CHIP_IO can also handle adding callback functions on any pin that supports edge detection. Note that only one callback function can be specified per Pin, if you try to set more, an exception will be thrown.::
def mycallback(channel): def mycallback(channel):
print("we hit the edge we want") print("we hit the edge we want")
GPIO.setup("GPIO3", GPIO.IN) GPIO.setup("GPIO3", GPIO.IN)
# Add Callback: Falling Edge
GPIO.add_event_callback("GPIO3", GPIO.FALLING, mycallback) # Add Event Detect and Callback Separately for Falling Edge
# Add Callback: Rising Edge GPIO.add_event_detect("GPIO3", GPIO.FALLING)
GPIO.add_event_callback("GPIO3", GPIO.RISING, mycallback) GPIO.add_event_callback("GPIO3", mycallback)
# Add Callback: Both Edges
GPIO.add_event_callback("GPIO3", GPIO.BOTH, mycallback) # Add Event Detect and Callback Separately for Rising Edge
# Remove callback GPIO.add_event_detect("GPIO3", GPIO.RISING)
GPIO.add_event_callback("GPIO3", mycallback)
# Add Callback for Both Edges using the add_event_detect() method
GPIO.add_event_detect("GPIO3", GPIO.BOTH, mycallback)
# Remove callback with the following
GPIO.remove_event_detect("GPIO3") GPIO.remove_event_detect("GPIO3")
# bouncetime is also able to be set for both GPIO.add_event_detect() and GPIO.add_event_callback()
GPIO.add_event_detect("GPIO3", GPIO.FALLING, bouncetime=300)
GPIO.add_event_callback("GPIO3", GPIO.RISING, mycallback, bouncetime=300)
**GPIO Cleanup** **GPIO Cleanup**
@ -251,6 +307,7 @@ To clean up the GPIO when done, do the following::
# Clean up every exported GPIO Pin # Clean up every exported GPIO Pin
GPIO.cleanup() GPIO.cleanup()
# Clean up a single pin (keeping everything else intact) # Clean up a single pin (keeping everything else intact)
GPIO.cleanup("XIO-P0") GPIO.cleanup("XIO-P0")
@ -259,34 +316,51 @@ To clean up the GPIO when done, do the following::
Hardware PWM requires a DTB Overlay loaded on the CHIP to allow the kernel to know there is a PWM device available to use. Hardware PWM requires a DTB Overlay loaded on the CHIP to allow the kernel to know there is a PWM device available to use.
:: ::
import CHIP_IO.PWM as PWM import CHIP_IO.PWM as PWM
# Determine hardware
# 0 For CHIP
# 1 For CHIP Pro
PWM.is_chip_pro()
# Enable/Disable Debug # Enable/Disable Debug
PWM.toggle_debug() PWM.toggle_debug()
#PWM.start(channel, duty, freq=2000, polarity=0) #PWM.start(channel, duty, freq=2000, polarity=0)
#duty values are valid 0 (off) to 100 (on) #duty values are valid 0 (off) to 100 (on)
PWM.start("PWM0", 50) PWM.start("PWM0", 50)
PWM.set_duty_cycle("PWM0", 25.5) PWM.set_duty_cycle("PWM0", 25.5)
PWM.set_frequency("PWM0", 10) PWM.set_frequency("PWM0", 10)
# To stop PWM # To stop PWM
PWM.stop("PWM0") PWM.stop("PWM0")
PWM.cleanup() PWM.cleanup()
#For specific polarity: this example sets polarity to 1 on start: #For specific polarity: this example sets polarity to 1 on start:
PWM.start("PWM0", 50, 2000, 1) PWM.start("PWM0", 50, 2000, 1)
**SOFTPWM**:: **SOFTPWM**::
import CHIP_IO.SOFTPWM as SPWM import CHIP_IO.SOFTPWM as SPWM
# Determine hardware
# 0 For CHIP
# 1 For CHIP Pro
SPWM.is_chip_pro()
# Enable/Disable Debug # Enable/Disable Debug
SPWM.toggle_debug() SPWM.toggle_debug()
#SPWM.start(channel, duty, freq=2000, polarity=0) #SPWM.start(channel, duty, freq=2000, polarity=0)
#duty values are valid 0 (off) to 100 (on) #duty values are valid 0 (off) to 100 (on)
#you can choose any pin #you can choose any pin
SPWM.start("XIO-P7", 50) SPWM.start("XIO-P7", 50)
SPWM.set_duty_cycle("XIO-P7", 25.5) SPWM.set_duty_cycle("XIO-P7", 25.5)
SPWM.set_frequency("XIO-P7", 10) SPWM.set_frequency("XIO-P7", 10)
# To Stop SPWM # To Stop SPWM
SPWM.stop("XIO-P7") SPWM.stop("XIO-P7")
# Cleanup # Cleanup
SPWM.cleanup() SPWM.cleanup()
#For specific polarity: this example sets polarity to 1 on start: #For specific polarity: this example sets polarity to 1 on start:
SPWM.start("XIO-P7", 50, 2000, 1) SPWM.start("XIO-P7", 50, 2000, 1)
@ -297,16 +371,24 @@ If using SOFTPWM and PWM at the same time, import CHIP_IO.SOFTPWM as SPWM or som
**SERVO**:: **SERVO**::
import CHIP_IO.SERVO as SERVO import CHIP_IO.SERVO as SERVO
# Determine hardware
# 0 For CHIP
# 1 For CHIP Pro
SERVO.is_chip_pro()
# Enable/Disable Debug # Enable/Disable Debug
SERVO.toggle_debug() SERVO.toggle_debug()
#SPWM.start(channel, angle=0, range=180) #SPWM.start(channel, angle=0, range=180)
#angle values are between +/- range/2) #angle values are between +/- range/2)
#you can choose any pin except the XIO's #you can choose any pin except the XIO's
SERVO.start("CSID4", 50) SERVO.start("CSID4", 50)
SERVO.set_angle("CSID4", 25.5) SERVO.set_angle("CSID4", 25.5)
SERVO.set_range("CSID4", 90) SERVO.set_range("CSID4", 90)
# To Stop Servo # To Stop Servo
SERVO.stop("CSID4") SERVO.stop("CSID4")
# Cleanup # Cleanup
SERVO.cleanup() SERVO.cleanup()
@ -320,23 +402,31 @@ Sample code below details how to talk to the LRADC.::
import CHIP_IO.LRADC as ADC import CHIP_IO.LRADC as ADC
# Enable/Disable Debug # Enable/Disable Debug
ADC.toggle_debug() ADC.toggle_debug()
# Check to see if the LRADC Device exists # Check to see if the LRADC Device exists
# Returns True/False # Returns True/False
ADC.get_device_exists() ADC.get_device_exists()
# Setup the LRADC # Setup the LRADC
# Specify a sampling rate if needed # Specify a sampling rate if needed
ADC.setup(rate) ADC.setup(rate)
# Get the Scale Factor # Get the Scale Factor
factor = ADC.get_scale_factor() factor = ADC.get_scale_factor()
# Get the allowable Sampling Rates # Get the allowable Sampling Rates
sampleratestuple = ADC.get_allowable_sample_rates() sampleratestuple = ADC.get_allowable_sample_rates()
# Set the sampling rate # Set the sampling rate
ADC.set_sample_rate(rate) ADC.set_sample_rate(rate)
# Get the current sampling rate # Get the current sampling rate
currentrate = ADC.get_sample_rate() currentrate = ADC.get_sample_rate()
# Get the Raw Channel 0 or 1 data # Get the Raw Channel 0 or 1 data
raw = ADC.get_chan0_raw() raw = ADC.get_chan0_raw()
raw = ADC.get_chan1_raw() raw = ADC.get_chan1_raw()
# Get the factored ADC Channel data # Get the factored ADC Channel data
fulldata = ADC.get_chan0() fulldata = ADC.get_chan0()
fulldata = ADC.get_chan1() fulldata = ADC.get_chan1()
@ -348,18 +438,21 @@ SPI requires a DTB Overlay to access. CHIP_IO does not contain any SPI specific
**Overlay Manager**:: **Overlay Manager**::
The Overlay Manager enables you to quickly load simple Device Tree Overlays. The options for loading are: The Overlay Manager enables you to quickly load simple Device Tree Overlays. The options for loading are:
PWM0, SPI2, I2C1, CUST PWM0, SPI2, CUST. The Overlay Manager is smart enough to determine if you are trying to load PWM on a CHIP Pro and will fail due to the base DTB for the CHIP Pro supporting PWM0/1 out of the box.
Only one of each type of overlay can be loaded at a time, but all three options can be loaded simultaneously. So you can have SPI2 and I2C1 without PWM0, but you cannot have SPI2 loaded twice. Only one of each type of overlay can be loaded at a time, but all three options can be loaded simultaneously. So you can have SPI2 without PWM0, but you cannot have SPI2 loaded twice.
:: ::
import CHIP_IO.OverlayManager as OM import CHIP_IO.OverlayManager as OM
# The toggle_debug() function turns on/off debug printing # The toggle_debug() function turns on/off debug printing
#OM.toggle_debug() OM.toggle_debug()
# To load an overlay, feed in the name to load() # To load an overlay, feed in the name to load()
OM.load("PWM0") OM.load("PWM0")
# To verify the overlay was properly loaded, the get_ functions return booleans # To verify the overlay was properly loaded, the get_ functions return booleans
OM.get_pwm_loaded() OM.get_pwm_loaded()
OM.get_spi_loaded() OM.get_spi_loaded()
# To unload an overlay, feed in the name to unload() # To unload an overlay, feed in the name to unload()
OM.unload("PWM0") OM.unload("PWM0")
@ -369,8 +462,10 @@ There is no verification that the Custom Overlay is setup properly, it's fire an
import CHIP_IO.OverlayManager as OM import CHIP_IO.OverlayManager as OM
# The full path to the dtbo file needs to be specified # The full path to the dtbo file needs to be specified
OM.load("CUST","/home/chip/projects/myfunproject/overlays/mycustomoverlay.dtbo") OM.load("CUST","/home/chip/projects/myfunproject/overlays/mycustomoverlay.dtbo")
# You can check for loading like above, but it's really just there for sameness # You can check for loading like above, but it's really just there for sameness
OM.get_custom_loaded() OM.get_custom_loaded()
# To unload, just call unload() # To unload, just call unload()
OM.unload("CUST") OM.unload("CUST")
@ -385,21 +480,32 @@ To use the utilities, here is sample code::
import CHIP_IO.Utilities as UT import CHIP_IO.Utilities as UT
# Enable/Disable Debug # Enable/Disable Debug
UT.toggle_debug() UT.toggle_debug()
# Enable 1.8V Output # Enable 1.8V Output
UT.enable_1v8_pin() UT.enable_1v8_pin()
# Set 2.0V Output # Set 2.0V Output
UT.set_1v8_pin_voltage(2.0) UT.set_1v8_pin_voltage(2.0)
# Set 2.6V Output # Set 2.6V Output
UT.set_1v8_pin_voltage(2.6) UT.set_1v8_pin_voltage(2.6)
# Set 3.3V Output # Set 3.3V Output
UT.set_1v8_pin_voltage(3.3) UT.set_1v8_pin_voltage(3.3)
# Disable 1.8V Output # Disable 1.8V Output
UT.disable_1v8_pin() UT.disable_1v8_pin()
# Get currently-configured voltage (returns False if the pin is not enabled as output) # Get currently-configured voltage (returns False if the pin is not enabled as output)
UT.get_1v8_pin_voltage() UT.get_1v8_pin_voltage()
# Unexport Everything # Unexport Everything
UT.unexport_all() UT.unexport_all()
# Determine if you are running a CHIP/CHIP Pro
# This returns True if the computer is a CHIP Pro and False if it is a CHIP
UT.is_chip_pro()
**Running tests** **Running tests**
Install py.test to run the tests. You'll also need the python compiler package for py.test.:: Install py.test to run the tests. You'll also need the python compiler package for py.test.::
@ -412,11 +518,12 @@ Install py.test to run the tests. You'll also need the python compiler package f
To run the tests, do the following.:: To run the tests, do the following.::
# If only one version of Python is installed # If only one version of Python is installed
sudo py.test # Python 2
# If more than one version of Python sudo make pytest2
cd test # Python 3
sudo python2 -m pytest sudo make pytest3
sudo python3 -m pytest # If more than one version of Python, run through both
sudo make test
**Credits** **Credits**

108
debian/changelog vendored Normal file
View File

@ -0,0 +1,108 @@
chip-io (0.7.1-1) unstable; urgency=low
* Merged PR#79 and#80
* Added logging to tell user of the 1 second sleep before retry on setting gpio direction
-- Robert Wolterman <robert.wolterman@gmail.com> Sun, 12 Nov 2017 07:40:00 -0600
chip-io (0.7.0-1) unstable; urgency=low
* Added ability to specify GPIO only as a number, this doesn't work for PWM/SPWM/LRADC/SERVO
-- Robert Wolterman <robert.wolterman@gmail.com> Wed, 13 Sep 2017 09:51:00 -0600
chip-io (0.6.2-1) unstable; urgency=low
* Implementation for number 77 ability to push up binary pypi
* Implementation for number 75 wait for edge timeout
-- Robert Wolterman <robert.wolterman@gmail.com> Sun, 03 Sep 2017 21:34:00 -0600
chip-io (0.6.1-1) unstable; urgency=low
* Fixing implementation for #76
-- Robert Wolterman <robert.wolterman@gmail.com> Wed, 09 Aug 2017 23:09:00 -0600
chip-io (0.6.0-1) unstable; urgency=low
* Random comment cleanup
* Implement fix for #76
* API documentation added
* Closing #74
-- Robert Wolterman <robert.wolterman@gmail.com> Wed, 09 Aug 2017 22:50:00 -0600
chip-io (0.5.9-1) unstable; urgency=low
* Merged PR#70 to enable the underlying C code to be used properly in C based code
* Updated README to add missing pins on the CHIP Pro that are available as GPIO
* Updated README to denote pins that are available for Edge Detection
-- Robert Wolterman <robert.wolterman@gmail.com> Tue, 08 Jun 2017 20:03:00 -0600
chip-io (0.5.8-1) unstable; urgency=low
* Added 3 pins for the CHIP Pro as allowable for setting callbacks and edge
detection to close out Issue #68
-- Robert Wolterman <robert.wolterman@gmail.com> Tue, 02 May 2017 22:43:00 -0600
chip-io (0.5.7-1) unstable; urgency=low
* Added the I2S pins on the CHIP Pro as GPIO capable
* Added per PWM/SoftPWM cleanup per Issue #64
-- Robert Wolterman <robert.wolterman@gmail.com> Mon, 01 May 2017 22:47:00 -0600
chip-io (0.5.6-1) unstable; urgency=low
* Fix for Issue #63 where re-setting up a pin wasn't lining up with RPi.GPIO standards. Calling setup after the first time will now update direction.
* README updates to point out the direction() function since that was missing
-- Robert Wolterman <robert.wolterman@gmail.com> Mon, 20 Mar 2017 23:04:00 -0600
chip-io (0.5.5-1) unstable; urgency=low
* Fix for Issue #62 where using alternate name of an XIO would cause a segfault due to trying to set pull up/down resistor setting
-- Robert Wolterman <robert.wolterman@gmail.com> Mon, 6 Mar 2017 17:02:00 -0600
chip-io (0.5.4-1) unstable; urgency=low
* Re-enabled the polarity setting for PWM based upon Issue #61
* Fixed a 1 letter bug was trying to write inverted to polarity when it wants inversed (such facepalm)
* Cleaned up the polarity setting code to work when PWM is not enabled
* Fixed the unit test for pwm to verify we can set polarity
-- Robert Wolterman <robert.wolterman@gmail.com> Sat, 4 Mar 2017 20:46:00 -0600
chip-io (0.5.3-1) unstable; urgency=low
* Fixes to the PWM pytest
* Added pytest for LRADC and Utilities
* Makefile updates for all the things
-- Robert Wolterman <robert.wolterman@gmail.com> Sun, 26 Feb 2017 20:46:00 -0600
chip-io (0.5.2-1) unstable; urgency=low
* Updating Utilities to determine CHIP Pro better
* Updating Utilities to only run CHIP appropriate code on the CHIP and not CHIP Pro
* Updated README
-- Robert Wolterman <robert.wolterman@gmail.com> Sun, 26 Feb 2017 13:56:00 -0600
chip-io (0.5.0-1) unstable; urgency=low
* CHIP Pro support for PWM1, reduced GPIO capability
* New is_chip_pro() in each of the PWM, GPIO, SoftPWM, and Servo modules
* Updated README
-- Robert Wolterman <robert.wolterman@gmail.com> Sat, 25 Feb 2017 19:00:00 -0600
chip-io (0.4.0-1) unstable; urgency=low
* source package automatically created by stdeb 0.8.2
-- Robert Wolterman <robert.wolterman@gmail.com> Sat, 18 Feb 2017 23:58:48 +0000

1
debian/compat vendored Normal file
View File

@ -0,0 +1 @@
9

23
debian/control vendored Normal file
View File

@ -0,0 +1,23 @@
Source: chip-io
Maintainer: Robert Wolterman <robert.wolterman@gmail.com>
Section: python
Priority: optional
Build-Depends: python-setuptools (>= 0.6b3), python-all-dev (>= 2.6.6-3), debhelper (>= 9), dh-python,
python3-all (>=3.2), python3-setuptools
Standards-Version: 3.9.1
Package: python-chip-io
Architecture: any
Depends: ${misc:Depends}, ${python:Depends}, ${shlibs:Depends}
Description: A module to control CHIP IO channels
CHIP_IO
============================
A CHIP GPIO library
Package: python3-chip-io
Architecture: any
Depends: ${misc:Depends}, ${python3:Depends}, ${shlibs:Depends}
Description: A module to control CHIP IO channels
CHIP_IO
============================
A CHIP GPIO library

2
debian/files vendored Normal file
View File

@ -0,0 +1,2 @@
python-chip-io_0.7.1-1_armhf.deb python optional
python3-chip-io_0.7.1-1_armhf.deb python optional

9
debian/rules vendored Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/make -f
# This file was automatically generated by stdeb 0.8.2 at
# Sat, 18 Feb 2017 23:58:48 +0000
export PYBUILD_NAME=chip-io
%:
dh $@ --with python2,python3 --buildsystem=pybuild

1
debian/source/format vendored Normal file
View File

@ -0,0 +1 @@
3.0 (quilt)

1
docs/_config.yml Normal file
View File

@ -0,0 +1 @@
theme: jekyll-theme-minimal

354
docs/gpio.md Normal file
View File

@ -0,0 +1,354 @@
## CHIP_IO.GPIO
Import the GPIO module as follows
```python
import CHIP_IO.GPIO as GPIO
```
Note: As of version 0.7.0, all GPIO functions can use the SYSFS pin number for a GPIO for control, a la RPi.GPIO.
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Examples
```python
GPIO.toggle_debug()
```
### is_chip_pro()
Function to report to the calling script if the SBC is a CHIP or a CHIP Pro
* Parameters
None
* Returns
int - 1 for CHIP Pro, 0 for CHIP
* Examples
```python
is_chip_pro = GPIO.is_chip_pro()
```
### setmode(mode)
Dummy function to maintain backwards compatibility with Raspberry Pi scripts.
### setup(channel, direction, pull_up_down=PUD_OFF, initial=None)
Setup a GPIO pin. If pin is already configure, it will reconfigure.
* Parameters
channel - GPIO pin
direction - INPUT or OUTPUT
pull_up_down - PUD_OFF, PUD_UP, PUD_DOWN (optional)
initial - Initial value for an OUTPUT pin (optional)
* Returns
None
* Examples
```python
GPIO.setup("CSID0", GPIO.IN)
GPIO.setup(132, GPIO.IN)
GPIO.setup("CSID3", GPIO.OUT, initial=1)
GPIO.setup("CSID2", GPIO.IN, GPIO.PUD_UP)
```
### cleanup(channel)
Cleanup GPIO. If not channel input, all GPIO will be cleaned up
* Parameters
channel - GPIO pin (optional)
* Returns
None
* Examples
```python
GPIO.cleanup()
GPIO.cleanup("CSID3")
GPIO.cleanup(132)
```
### output(channel, value)
Write a value to a GPIO pin.
* Parameters
channel - GPIO Pin
value - HIGH, LOW, 0, 1
* Returns
None
* Examples
```python
GPIO.output("XIO-P7", GPIO.HIGH)
GPIO.output("XIO-P7", GPIO.LOW)
GPIO.output("CSID0", 1)
GPIO.output("CSID0", 0)
GPIO.output(132, 1)
```
### input(channel)
Read a GPIO pin once.
* Parameters
channel - GPIO Pin
* Returns
value - current value of the GPIO pin
* Examples
```python
value = GPIO.input("XIO-P7")
value = GPIO.input(1013)
```
### read_byte(channel)
Read a GPIO pin multiple times to fill up 8 bits.
* Parameters
channel - GPIO Pin
* Returns
int - 8 bit value of the GPIO pin
* Examples
```python
bits = GPIO.read_byte("XIO-P7")
bits = GPIO.read_byte(135)
```
### read_word(channel)
Read a GPIO pin multiple times to fill up 16 bits.
* Parameters
channel - GPIO Pin
* Returns
word - 16 bit value of the GPIO pin
* Examples
```python
bits = GPIO.read_word("XIO-P7")
bits = GPIO.read_word(134)
```
### add_event_detect(channel, edge, callback=None, bouncetime=0)
Add event detection to a pin. Refer to main table for which pins are able to use edge detection.
* Parameters
channel - GPIO Pin
edge - edge: RISING_EDGE, FALLING_EDGE, BOTH_EDGE
callback - callback function to be run when edge is detected (optional)
bouncetime - level debounce time period in ms (optional)
* Returns
None
* Examples
```python
GPIO.add_event_detect("XIO-P7", GPIO.RISING_EDGE)
GPIO.add_event_detect("AP-EINT3", GPIO.RISING_EDGE, mycallback)
GPIO.add_event_detect("XIO-P7", GPIO.FALLING_EDGE, bouncetime=30)
GPIO.add_event_detect("XIO-P7", GPIO.RISING_EDGE, mycallback, 45)
GPIO.add_event_detect(1013, GPIO.BOTH_EDGE)
```
### remove_event_detect(channel)
Remove a pins event detection. Refer to main table for which pins are able to use edge detection.
* Parameters
channel - GPIO Pin
* Returns
None
* Examples
```python
GPIO.remove_event_detect("XIO-P7")
GPIO.remove_event_detect(1013)
```
### event_detected(channel)
Function to determine if an event was detected on a pin. Pin must have an event detect added via add_event_detect() prior to calling this function. Refer to main table for which pins are able to use edge detection.
* Parameters
channel - GPIO Pin
* Returns
boolean - True if event was detected
* Examples
```python
have_event = GPIO.event_detected("XIO-P5")
have_event = GPIO.event_detected(1014)
```
### add_event_callback(channel, callback, bouncetime=0)
Add callback function to a pin that has been setup for edge detection. Refer to main table for which pins are able to use edge detection.
* Parameters
channel - GPIO Pin
callback - callback function to be run when edge is detected
bouncetime - level debounce time period in ms (optional)
* Returns
None
* Examples
```python
GPIO.add_event_callback("AP-EINT3", mycallback)
GPIO.add_event_callback("XIO-P7", mycallback, 45)
GPIO.add_event_callback(1013, mycallback)
```
### wait_for_edge(channel, edge, timeout=-1)
Wait for an edge to be detected. This is a blocking function. Refer to main table for which pins are able to use edge detection.
* Parameters
channel - GPIO Pin
edge - edge: RISING_EDGE, FALLING_EDGE, BOTH_EDGE
timeout - timeout in milliseconds to wait before exiting function (optional)
* Returns
None
* Examples
```python
GPIO.wait_for_edge("XIO-P3", GPIO.RISING_EDGE)
GPIO.wait_for_edge("AP-EINT3", GPIO.BOTH_EDGE)
GPIO.wait_for_edge("I2S-DI", GPIO.FALLING_EDGE)
GPIO.wait_for_edge("XIO-P3", GPIO.RISING_EDGE, 40)
GPIO.wait_for_edge(1013, GPIO.BOTH_EDGE, 35)
```
### gpio_function(channel)
Function to report get a GPIO Pins directioj
* Parameters
channel - GPIO Pin
* Returns
int - GPIO Pin direction
* Examples
```python
funct = GPIO.gpio_function("CSID0")
funct = GPIO.gpio_function(132)
```
### setwarnings(state)
Function to enable/disable warning print outs. This may or may not work properly. toggle_debug() is a better bet.
* Parameters
state - 1 for enable, 0 for disable
* Returns
None
* Examples
```python
GPIO.set_warnings(1)
```
### get_gpio_base()
Function to get the SYSFS base value for the XIO pins on a CHIP
* Parameters
None
* Returns
int - sysfs base of the XIO, returns -1 on a CHIP Pro
* Examples
```python
base = GPIO.get_gpio_base()
```
### selftest(value)
Function to perform a selftest on the GPIO module
* Parameters
value - a value
* Returns
int - the input value
* Examples
```python
rtn = GPIO.selftest(0)
```
### direction(channel, direction)
Function to set the direction of an exported GPIO pin
* Parameters
channel - GPIO Pin
direction - Direction Pin is to take
* Returns
None
* Examples
```python
GPIO.set_direction("XIO-P0", GPIO.OUT)
GPIO.set_direction("XIO-P1", GPIO.IN)
GPIO.set_direction(1013, GPIO.OUT)
```
[home](./index.md)

75
docs/index.md Normal file
View File

@ -0,0 +1,75 @@
## CHIP_IO API Documentation
* [CHIP_IO.GPIO](./gpio.md)
* [CHIP_IO.PWM](./pwm.md)
* [CHIP_IO.SOFTPWM](./softpwm.md)
* [CHIP_IO.SERVO](./servo.md)
* [CHIP_IO.LRADC](./lradc.md)
* [CHIP_IO.Utilities](./utilities.md)
* [CHIP_IO.OverlayManager](./overlaymanager.md)
### Allowable Pin Names and Edge Detection Capability
The following "table" is the allowable pin names that are able to be used by the library. The Name column is the normal name used on the CHIP Headers, the Alt Name column is the value used by the PocketCHIP header (if it's broken out), and the Key is the Header and Pin Number the the Pin is physically located. Either of these 3 means is able to specify a pin in CHIP_IO.
| CHIP (Main Name) | PocketCHIP/CHIP Pro Name | Key (Alt Name) | HW Support | Edge Detect |
|:----------------:|:------------------------:|:--------------:|:---------------:|:---------------:|
| TWI1-SDA | KPD-I2C-SDA | U13_9 | CHIP/CHIP PRO | NO |
| TWI1-SCK | KPD-I2C-SCL | U13_11 | CHIP/CHIP PRO | NO |
| LCD-D2 | UART2-TX | U13_17 | CHIP/CHIP PRO | NO |
| PWM0 | PWM0 | U13_18 | CHIP/CHIP PRO | NO |
| PWM1 | PWM1 | EINT13 | CHIP PRO | YES |
| LCD-D4 | UART2-CTS | U13_19 | CHIP/CHIP PRO | NO |
| LCD-D3 | UART2-RX | U13_20 | CHIP/CHIP PRO | NO |
| LCD-D6 | LCD-D6 | U13_21 | CHIP | NO |
| LCD-D5 | UART2-RTS | U13_22 | CHIP/CHIP PRO | NO |
| LCD-D10 | LCD-D10 | U13_23 | CHIP | NO |
| LCD-D7 | LCD-D7 | U13_24 | CHIP | NO |
| LCD-D12 | LCD-D12 | U13_25 | CHIP | NO |
| LCD-D11 | LCD-D11 | U13_26 | CHIP | NO |
| LCD-D14 | LCD-D14 | U13_27 | CHIP | NO |
| LCD-D13 | LCD-D13 | U13_28 | CHIP | NO |
| LCD-D18 | LCD-D18 | U13_29 | CHIP | NO |
| LCD-D15 | LCD-D15 | U13_30 | CHIP | NO |
| LCD-D20 | LCD-D20 | U13_31 | CHIP | NO |
| LCD-D19 | LCD-D19 | U13_32 | CHIP | NO |
| LCD-D22 | LCD-D22 | U13_33 | CHIP | NO |
| LCD-D21 | LCD-D21 | U13_34 | CHIP | NO |
| LCD-CLK | LCD-CLK | U13_35 | CHIP | NO |
| LCD-D23 | LCD-D23 | U13_36 | CHIP | NO |
| LCD-VSYNC | LCD-VSYNC | U13_37 | CHIP | NO |
| LCD-HSYNC | LCD-HSYNC | U13_38 | CHIP | NO |
| LCD-DE | LCD-DE | U13_40 | CHIP | NO |
| UART1-TX | UART-TX | U14_3 | CHIP/CHIP PRO | NO |
| UART1-RX | UART-RX | U14_5 | CHIP/CHIP PRO | NO |
| LRADC | ADC | U14_11 | CHIP/CHIP PRO | NO |
| XIO-P0 | XIO-P0 | U14_13 | CHIP | YES |
| XIO-P1 | XIO-P1 | U14_14 | CHIP | YES |
| XIO-P2 | GPIO1 | U14_15 | CHIP | YES |
| XIO-P3 | GPIO2 | U14_16 | CHIP | YES |
| XIO-P4 | GPIO3 | U14_17 | CHIP | YES |
| XIO-P5 | GPIO4 | U14_18 | CHIP | YES |
| XIO-P6 | GPIO5 | U14_19 | CHIP | YES |
| XIO-P7 | GPIO6 | U14_20 | CHIP | YES |
| AP-EINT1 | KPD-INT | U14_23 | CHIP/CHIP PRO | YES |
| AP-EINT3 | AP-INT3 | U14_24 | CHIP/CHIP PRO | YES |
| TWI2-SDA | I2C-SDA | U14_25 | CHIP/CHIP PRO | NO |
| TWI2-SCK | I2C-SCL | U14_26 | CHIP/CHIP PRO | NO |
| CSIPCK | SPI-SEL | U14_27 | CHIP/CHIP PRO | NO |
| CSICK | SPI-CLK | U14_28 | CHIP/CHIP PRO | NO |
| CSIHSYNC | SPI-MOSI | U14_29 | CHIP/CHIP PRO | NO |
| CSIVSYNC | SPI-MISO | U14_30 | CHIP/CHIP PRO | NO |
| CSID0 | D0 | U14_31 | CHIP/CHIP PRO | NO |
| CSID1 | D1 | U14_32 | CHIP/CHIP PRO | NO |
| CSID2 | D2 | U14_33 | CHIP/CHIP PRO | NO |
| CSID3 | D3 | U14_34 | CHIP/CHIP PRO | NO |
| CSID4 | D4 | U14_35 | CHIP/CHIP PRO | NO |
| CSID5 | D5 | U14_36 | CHIP/CHIP PRO | NO |
| CSID6 | D6 | U14_37 | CHIP/CHIP PRO | NO |
| CSID7 | D7 | U14_38 | CHIP/CHIP PRO | NO |
| I2S-MCLK | EINT19 | 21 | CHIP PRO | YES |
| I2S-BCLK | I2S-BCLK | 22 | CHIP PRO | NO |
| I2S-LCLK | I2S-LCLK | 23 | CHIP PRO | NO |
| I2S-DO | EINT19 | 24 | CHIP PRO | NO |
| I2S-DI | EINT24 | 25 | CHIP PRO | YES |

200
docs/lradc.md Normal file
View File

@ -0,0 +1,200 @@
## CHIP_IO.LRADC
The LRADC module handles interfacing with the onboard 6-Bit, 2V tolerant ADC in the R8/GR8.
Import the LRADC module as follows
```python
import CHIP_IO.LRADC as LRADC
```
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Returns
None
* Examples
```python
LRADC.toggle_debug()
```
### get_device_exist()
Check to see if the LRADC device exists
* Parameters
None
* Returns
boolean - True if LRADC is enabled, False is LRADC is disabled
* Examples
```python
LRADC.get_device_exist()
```
### setup(rate=250)
Setup the LRADC, defaults to a sampling rate of 250.
* Parameters
rate (optional) - Sampling rate of the LRADC: 32.25, 62.5, 125, 250
* Returns
boolean - True if LRADC is enabled, False is LRADC is disabled
* Examples
```python
LRADC.setup()
LRADC.setup(32.25)
```
### get_scale_factor()
Get the scaling factor applied to raw values from the LRADC
* Parameters
None
* Returns
float - scale factor applied to the LRADC Raw data
* Examples
```python
factor = LRADC.get_scale_factor()
print(factor)
```
### get_allowable_sample_rates()
Get the allowable sample rates for the LRADC
* Parameters
None
* Returns
tuple - sampling rates of the LRADC
* Examples
```python
rates = LRADC.get_allowable_sample_rates()
print(rates)
```
### set_sample_rate(rate)
Set the current sample rates for the LRADC
* Parameters
rate - Sample rate, only rates allowable by the LRADC
* Returns
float - current sampling rate of the LRADC
* Examples
```python
curr_rate = LRADC.set_sample_rate(125.0)
```
### get_sample_rate()
Get the current sample rates for the LRADC
* Parameters
None
* Returns
float - current sampling rate of the LRADC
* Examples
```python
curr_rate = LRADC.get_sample_rate()
```
### get_chan0_raw()
Get the raw value for LRADC Channel 0
* Parameters
None
* Returns
float - current raw value of LRADC Channel 0
* Examples
```python
dat = LRADC.get_chan0_raw()
```
### get_chan1_raw()
Get the raw value for LRADC Channel 1
* Parameters
None
* Returns
float - current raw value of LRADC Channel 1
* Examples
```python
dat = LRADC.get_chan1_raw()
```
### get_chan0()
Get the value for LRADC Channel 0
* Parameters
None
* Returns
float - current value of LRADC Channel 0
* Examples
```python
dat = LRADC.get_chan0()
```
### get_chan1
Get the value for LRADC Channel 1
* Parameters
None
* Returns
float - current value of LRADC Channel 1
* Examples
```python
dat = LRADC.get_chan1()
```
[home](./index.md)

117
docs/overlaymanager.md Normal file
View File

@ -0,0 +1,117 @@
## CHIP_IO.OverlayManager
Import the OverlayManager module as follows
```python
import CHIP_IO.OverlayManager as OM
```
This module requires NTC's [CHIP-dt-overlays](https://github.com/NextThingCo/CHIP-dt-overlays) to be loaded.
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Returns
None
* Examples
```python
OM.toggle_debug()
```
### load(overlay, path="")
Loads the overlay specified. PWM0 is not available on the CHIP Pro due to the base DTS supporting both PWM0 and PWM1
* Parameters
overlay - Overlay to be loaded: SPI2, PWM0, CUST
path (optional) - Path to the custom compiled overlay
* Returns
integer - 0: Success, 1: Fail, 2: Overlay already loaded
* Examples
```python
resp = OM.load("SPI2")
resp = OM.load("PWM0")
resp = OM.load("CUST","path/to/custom.dtbo")
```
### unload(overlay)
Unloads the overlay specified. PWM0 is not available on the CHIP Pro due to the base DTS supporting both PWM0 and PWM1
* Parameters
overlay - Overlay to be loaded: SPI2, PWM0, CUST
* Returns
None
* Examples
```python
resp = OM.unload("SPI2")
resp = OM.unload("PWM0")
resp = OM.unload("CUST")
```
### get_spi_loaded()
Check to see if the SPI DTBO is loaded
* Parameters
None
* Returns
boolean
* Examples
```python
is_spi_loaded = OM.get_spi_loaded()
```
### get_pwm_loaded()
Check to see if the PWM0 DTBO is loaded
* Parameters
None
* Returns
boolean
* Examples
```python
is_pwm_loaded = OM.get_pwm_loaded()
```
### get_custom_loaded()
Check to see if the Custom DTBO is loaded
* Parameters
None
* Returns
boolean
* Examples
```python
is_custom_loaded = OM.get_custom_loaded()
```
[home](./index.md)

172
docs/pwm.md Normal file
View File

@ -0,0 +1,172 @@
## CHIP_IO.PWM
Import the PWM module as follows
```python
import CHIP_IO.PWM as PWM
```
For the CHIP, this requires the PWM0 DTBO loaded via the OverlayManager or other means.
For the CHIP, PWM1 is unavaiable
For the CHIP Pro, PWM0 and PWM1 are setup in the base DTB by default
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Examples
```python
PWM.toggle_debug()
```
### is_chip_pro()
Function to report to the calling script if the SBC is a CHIP or a CHIP Pro
* Parameters
None
* Returns
int - 1 for CHIP Pro, 0 for CHIP
* Examples
```python
is_chip_pro = PWM.is_chip_pro()
```
### start(channel, duty_cycle=0.0, frequency=2000.0, polarity=0)
Start the Software PWM
* Parameters
channel - pin for software PWM is configured
duty_cycle - initial duty cycle of the PWM (optional)
frequency - frequency of the PWM (optional)
polarity - signal polarity of the PWM (optional)
* Returns
None
* Examples
```python
PWM.start("PWM0")
PWM.start("PWM0", 37.0)
PWM.start("PWM0", 10.0, 500.0)
PWM.start("PWM0", 50.0, 1000.0, 1)
```
### stop(channel)
Stop the PWM
* Parameters
channel - pin PWM is configured
* Returns
None
* Examples
```python
PWM.stop("PWM0")
```
### set_duty_cycle(channel, duty_cycle)
Set the duty cycle of the PWM
* Parameters
channel - pin PWM is configured
duty_cycle - duty cycle of the PWM (0.0 to 100.0)
* Returns
None
* Examples
```python
PWM.set_duty_cycle("PWM0", 25.0)
```
### set_pulse_width_ns(channel, pulse_width_ns)
Set the width of the PWM pulse in nano seconds
* Parameters
channel - pin PWM is configured
pulse_width_ns - pulse width of the PWM in nanoseconds
* Returns
None
* Examples
```python
PWM.set_pulse_width_ns("PWM0", 2500.0)
```
### set_frequency(channel, frequency)
Set the frequency of the PWM in Hertz
* Parameters
channel - pin software PWM is configured
frequency - frequency of the PWM
* Returns
None
* Examples
```python
PWM.set_frequency("PWM0", 450.0)
```
### set_period_ns(channel, pulse_width_ns)
Set the period of the PWM pulse in nano seconds
* Parameters
channel - pin PWM is configured
period_ns - period of the PWM in nanoseconds
* Returns
None
* Examples
```python
PWM.set_period_ns("PWM0", 130.0)
```
### cleanup(channel)
Cleanup PWM. If not channel input, all PWM will be cleaned up
* Parameters
channel - pin PWM is configured (optional)
* Returns
None
* Examples
```python
PWM.cleanup()
PWM.cleanup("PWM0")
```
[home](./index.md)

131
docs/servo.md Normal file
View File

@ -0,0 +1,131 @@
## CHIP_IO.SERVO
Import the SERVO module as follows
```python
import CHIP_IO.SERVO as SERVO
```
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Examples
```python
SERVO.toggle_debug()
```
### is_chip_pro()
Function to report to the calling script if the SBC is a CHIP or a CHIP Pro
* Parameters
None
* Returns
int - 1 for CHIP Pro, 0 for CHIP
* Examples
```python
is_chip_pro = SERVO.is_chip_pro()
```
### start(channel, angle=0.0, range=180.0)
Start the Servo
* Parameters
channel - Pin servo is attached to
angle - initial angle of the servo (optional)
range - total range of the servo in degrees (optional)
* Returns
None
* Examples
```python
SERVO.start("CSID0")
SERVO.start("CSID0", 37.0)
SERVO.start("CSID0", -45.0, 180.0)
```
### stop(channel)
Stop the Servo
* Parameters
channel - Pin servo is attached to
* Returns
None
* Examples
```python
SERVO.stop("CSID0")
```
### set_range(channel, range)
Set the range of the Servo
* Parameters
channel - Pin servo is attached to
range - total range of the servo in degrees
* Returns
None
* Examples
```python
SERVO.set_range("CSID0", 180.0)
SERVO.set_range("CSID0", 360.0)
```
### set_angle(channel, angle)
Set the angle of the Servo
* Parameters
channel - Pin servo is attached to
angle - angle to set the servo between +/- 1/2*Range
* Returns
None
* Examples
```python
SERVO.set_angle("CSID0", -45.0)
SERVO.set_angle("CSID0", 36.0)
```
### cleanup()
Cleanup all setup Servos, this will blast away every sero currently in operation
* Parameters
None
* Returns
None
* Examples
```python
SERVO.cleanup()
```
[home](./index.md)

132
docs/softpwm.md Normal file
View File

@ -0,0 +1,132 @@
## CHIP_IO.SOFTPWM
Import the SOFTPWM module as follows
```python
import CHIP_IO.SOFTPWM as SPWM
```
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Examples
```python
SPWM.toggle_debug()
```
### is_chip_pro()
Function to report to the calling script if the SBC is a CHIP or a CHIP Pro
* Parameters
None
* Returns
int - 1 for CHIP Pro, 0 for CHIP
* Examples
```python
is_chip_pro = SPWM.is_chip_pro()
```
### start(channel, duty_cycle=0.0, frequency=2000.0, polarity=0)
Start the Software PWM
* Parameters
channel - pin for software PWM is configured
duty_cycle - initial duty cycle of the PWM (optional)
frequency - frequency of the PWM (optional)
polarity - signal polarity of the PWM (optional)
* Returns
None
* Examples
```python
SPWM.start("CSID0")
SPWM.start("CSID0", 37.0)
SPWM.start("CSID0", 10.0, 500.0)
SPWM.start("CSID0", 50.0, 1000.0, 1)
```
### stop(channel)
Stop the Software PWM
* Parameters
channel - pin software PWM is configured
* Returns
None
* Examples
```python
SPWM.stop("CSID0")
```
### set_duty_cycle(channel, duty_cycle)
Set the duty cycle of the Software PWM
* Parameters
channel - pin software PWM is configured
duty_cycle - duty cycle of the PWM (0.0 to 100.0)
* Returns
None
* Examples
```python
SPWM.set_duty_cycle("CSID0", 25.0)
```
### set_frequency(channel, frequency)
Set the frequency of the Software PWM in Hertz
* Parameters
channel - pin PWM is configured
frequency - frequency of the PWM
* Returns
None
* Examples
```python
SPWM.set_frequency("CSID0", 450.0)
```
### cleanup(channel)
Cleanup Software PWM. If not channel input, all Software PWM will be cleaned up
* Parameters
channel - pin Software PWM is configured (optional)
* Returns
None
* Examples
```python
SPWM.cleanup()
SPWM.cleanup("CSID0")
```
[home](./index.md)

132
docs/utilities.md Normal file
View File

@ -0,0 +1,132 @@
## CHIP_IO.Utilities
Import the Utilities module as follows
```python
import CHIP_IO.Utilities as UT
```
### toggle_debug()
Enable/Disable the Debug
* Parameters
None
* Returns
None
* Examples
```python
UT.toggle_debug()
```
### unexport_all()
Function to force clean up all exported GPIO on the system
* Parameters
None
* Returns
None
* Examples
```python
UT.unexport_all()
```
### is_chip_pro()
Function to report to the calling script if the SBC is a CHIP or a CHIP Pro
* Parameters
None
* Returns
boolean - True for CHIP Pro, False for CHIP
* Examples
```python
is_chip_pro = UT.is_chip_pro()
```
### enable_1v8_pin()
Enable the 1.8V pin on the CHIP as it is disabled by default. Also sets the output to 1.8V.
This only works on the CHIP.
* Parameters
None
* Returns
None
* Examples
```python
UT.enable_1v8_pin()
```
### set_1v8_pin_voltage(voltage)
Change the voltage of the 1.8V Pin on the CHIP.
This only works on the CHIP.
* Parameters
voltage - 1.8, 2.0, 2.6, 3.3
* Returns
boolean - False on error
* Examples
```python
UT.set_1v8_pin_voltage(2.0)
```
### get_1v8_pin_voltage()
Get the current voltage of the 1.8V Pin on the CHIP.
This only works on the CHIP.
* Parameters
None
* Returns
float - current voltage of the 1.8V Pin
* Examples
```python
volts = UT.get_1v8_pin_voltage()
```
### disable_1v8_pin()
Disables the 1.8V pin on the CHIP.
This only works on the CHIP.
* Parameters
None
* Returns
None
* Examples
```python
UT.disable_1v8_pin()
```
[home](./index.md)

View File

View File

@ -1,22 +0,0 @@
from subprocess import call
import os
import shutil
import glob
import sys
def compile():
print("Compiling DTS Files")
call(["dtc", "-O", "dtb", "-o", "overlays/chip-pwm0.dtbo", "-b", "o", "-@", "overlays/chip-pwm0.dts"])
def copy():
target_dir = os.environ.get('TARGET_DIR', '')
overlay_path = target_dir + "/lib/firmware/chip_io"
print("Checking for DTBO Install Path")
if not os.path.exists(overlay_path):
print("Path not found, creating "+overlay_path)
os.makedirs(overlay_path)
print("Removing old DTBO files (if applicable)")
for fl in glob.glob(overlay_path+"/chip-*-.dtbo"):
os.remove(fl)
print("Moving DTBO files to "+overlay_path)
shutil.move("overlays/chip-pwm0.dtbo", overlay_path+"/chip-pwm0.dtbo")

View File

@ -1,61 +0,0 @@
/*
* Copyright 2016 Free Electrons
* Copyright 2016 NextThing Co
*
* Maxime Ripard <maxime.ripard@free-electrons.com>
*
* This file is dual-licensed: you can use it either under the terms
* of the GPL or the X11 license, at your option. Note that this dual
* licensing only applies to this file, and not this project as a
* whole.
*
* a) This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Or, alternatively,
*
* b) Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/dts-v1/;
/plugin/;
/ {
compatible = "nextthing,chip", "allwinner,sun5i-r8";
/* Enable the PWM */
fragment@0 {
target = <&pwm>;
__overlay__ {
pinctrl-names = "default";
pinctrl-0 = <&pwm0_pins>;
status = "okay";
};
};
};

6
setup.cfg Normal file
View File

@ -0,0 +1,6 @@
[bdist_wheel]
universal = 1
[metadata]
license_file = LICENSE

View File

@ -1,10 +1,3 @@
try:
from overlays import builder
builder.compile()
builder.copy()
except:
pass
import distribute_setup import distribute_setup
distribute_setup.use_setuptools() distribute_setup.use_setuptools()
from setuptools import setup, Extension, find_packages from setuptools import setup, Extension, find_packages
@ -20,13 +13,13 @@ classifiers = ['Development Status :: 3 - Alpha',
'Topic :: System :: Hardware'] 'Topic :: System :: Hardware']
setup(name = 'CHIP_IO', setup(name = 'CHIP_IO',
version = '0.4.0', version = '0.7.1',
author = 'Robert Wolterman', author = 'Robert Wolterman',
author_email = 'robert.wolterman@gmail.com', author_email = 'robert.wolterman@gmail.com',
description = 'A module to control CHIP IO channels', description = 'A module to control CHIP IO channels',
long_description = open('README.rst').read() + open('CHANGELOG.rst').read(), long_description = open('README.rst').read() + open('CHANGELOG.rst').read(),
license = 'MIT', license = 'MIT',
keywords = 'CHIP NextThingCo IO GPIO PWM ADC', keywords = 'CHIP NextThingCo IO GPIO PWM ADC GR8 R8',
url = 'https://github.com/xtacocorex/CHIP_IO/', url = 'https://github.com/xtacocorex/CHIP_IO/',
classifiers = classifiers, classifiers = classifiers,
packages = find_packages(), packages = find_packages(),

View File

@ -47,35 +47,14 @@ SOFTWARE.
#define DISABLE 0 #define DISABLE 0
// Global variables // Global variables
int pwm_initialized = 0;
// pwm devices (future chip pro use)
struct pwm_dev
{
char key[KEYLEN+1]; /* leave room for terminating NUL byte */
int gpio;
int initialized;
struct pwm_dev *next;
};
struct pwm_dev *initialized_pwms = NULL;
struct pwm_dev *lookup_initialized_pwm(const char *key)
{
struct pwm_dev *dev = initialized_pwms;
while (dev != NULL)
{
if (strcmp(dev->key, key) == 0) {
return dev;
}
dev = dev->next;
}
return NULL;
}
// pwm exports // pwm exports
struct pwm_exp struct pwm_exp
{ {
char key[KEYLEN+1]; /* leave room for terminating NUL byte */ char key[KEYLEN+1]; /* leave room for terminating NUL byte */
int iscpro;
int gpio;
int initialized;
int period_fd; int period_fd;
int duty_fd; int duty_fd;
int polarity_fd; int polarity_fd;
@ -101,15 +80,12 @@ struct pwm_exp *lookup_exported_pwm(const char *key)
return NULL; /* standard for pointers */ return NULL; /* standard for pointers */
} }
int initialize_pwm(void) int initialize_pwm(int *initialized, int gpio)
{ {
int e_no; int e_no;
if (!pwm_initialized) { if (!*initialized) {
int fd, len; int fd, len;
char str_gpio[80]; char str_gpio[80];
// Per https://github.com/NextThingCo/CHIP-linux/pull/4
// we need to export 0 here to enable pwm0
int gpio = 0;
if (DEBUG) if (DEBUG)
printf(" ** initialize_pwm **\n"); printf(" ** initialize_pwm **\n");
@ -134,7 +110,7 @@ int initialize_pwm(void)
if (DEBUG) if (DEBUG)
printf(" ** initialize_pwm: export pin: s = %d, len = %d\n", s, len); printf(" ** initialize_pwm: export pin: s = %d, len = %d\n", s, len);
pwm_initialized = 1; *initialized = 1;
return 1; return 1;
} else { } else {
if (DEBUG) if (DEBUG)
@ -169,7 +145,7 @@ int pwm_set_frequency(const char *key, float freq) {
len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer);
ssize_t s = write(pwm->period_fd, buffer, len); e_no = errno; ssize_t s = write(pwm->period_fd, buffer, len); e_no = errno;
if (DEBUG) { if (DEBUG) {
printf(" ** pwm_set_frequency: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_frequency: pwm_initialized = %d\n", pwm->initialized);
printf(" ** pwm_set_frequency: buffer: %s\n", buffer); printf(" ** pwm_set_frequency: buffer: %s\n", buffer);
printf(" ** pwm_set_frequency: s = %d, len = %d\n", s, len); printf(" ** pwm_set_frequency: s = %d, len = %d\n", s, len);
} }
@ -212,7 +188,7 @@ int pwm_set_period_ns(const char *key, unsigned long period_ns) {
len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer);
ssize_t s = write(pwm->period_fd, buffer, len); e_no = errno; ssize_t s = write(pwm->period_fd, buffer, len); e_no = errno;
if (DEBUG) { if (DEBUG) {
printf(" ** pwm_set_period_ns: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_period_ns: pwm_initialized = %d\n", pwm->initialized);
printf(" ** pwm_set_period_ns: buffer: %s\n", buffer); printf(" ** pwm_set_period_ns: buffer: %s\n", buffer);
printf(" ** pwm_set_period_ns: s = %d, len = %d\n", s, len); printf(" ** pwm_set_period_ns: s = %d, len = %d\n", s, len);
} }
@ -270,17 +246,18 @@ int pwm_set_polarity(const char *key, int polarity) {
return rtnval; return rtnval;
} }
if (pwm->enable) { // THIS ONLY WORKS WHEN PWM IS NOT ENABLED
if (pwm->enable == 0) {
if (polarity == 0) { if (polarity == 0) {
len = snprintf(buffer, sizeof(buffer), "%s", "normal"); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%s", "normal"); BUF2SMALL(buffer);
} }
else else
{ {
len = snprintf(buffer, sizeof(buffer), "%s", "inverted"); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%s", "inversed"); BUF2SMALL(buffer);
} }
ssize_t s = write(pwm->polarity_fd, buffer, len); e_no = errno; ssize_t s = write(pwm->polarity_fd, buffer, len); e_no = errno;
if (DEBUG) { if (DEBUG) {
printf(" ** pwm_set_polarity: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_polarity: pwm_initialized = %d\n", pwm->initialized);
printf(" ** pwm_set_polarity: buffer: %s\n", buffer); printf(" ** pwm_set_polarity: buffer: %s\n", buffer);
printf(" ** pwm_set_polarity: s = %d, len = %d\n", s, len); printf(" ** pwm_set_polarity: s = %d, len = %d\n", s, len);
} }
@ -295,6 +272,7 @@ int pwm_set_polarity(const char *key, int polarity) {
} else { } else {
rtnval = 0; rtnval = 0;
} }
return rtnval; return rtnval;
} }
@ -320,7 +298,7 @@ int pwm_set_duty_cycle(const char *key, float duty) {
len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer);
ssize_t s = write(pwm->duty_fd, buffer, len); e_no = errno; ssize_t s = write(pwm->duty_fd, buffer, len); e_no = errno;
if (DEBUG) { if (DEBUG) {
printf(" ** pwm_set_duty_cycle: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_duty_cycle: pwm_initialized = %d\n", pwm->initialized);
printf(" ** pwm_set_duty_cycle: buffer: %s\n", buffer); printf(" ** pwm_set_duty_cycle: buffer: %s\n", buffer);
printf(" ** pwm_set_duty_cycle: s = %d, len = %d\n", s, len); printf(" ** pwm_set_duty_cycle: s = %d, len = %d\n", s, len);
} }
@ -360,7 +338,7 @@ int pwm_set_pulse_width_ns(const char *key, unsigned long pulse_width_ns) {
len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer);
ssize_t s = write(pwm->duty_fd, buffer, len); e_no = errno; ssize_t s = write(pwm->duty_fd, buffer, len); e_no = errno;
if (DEBUG) { if (DEBUG) {
printf(" ** pwm_set_pulse_width_ns: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_pulse_width_ns: pwm_initialized = %d\n", pwm->initialized);
printf(" ** pwm_set_pulse_width_ns: buffer: %s\n", buffer); printf(" ** pwm_set_pulse_width_ns: buffer: %s\n", buffer);
printf(" ** pwm_set_pulse_width_ns: s = %d, len = %d\n", s, len); printf(" ** pwm_set_pulse_width_ns: s = %d, len = %d\n", s, len);
} }
@ -405,7 +383,7 @@ int pwm_set_enable(const char *key, int enable)
len = snprintf(buffer, sizeof(buffer), "%d", enable); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%d", enable); BUF2SMALL(buffer);
ssize_t s = write(pwm->enable_fd, buffer, len); e_no = errno; ssize_t s = write(pwm->enable_fd, buffer, len); e_no = errno;
if (DEBUG) { if (DEBUG) {
printf(" ** pwm_set_enable: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_enable: pwm_initialized = %d\n", pwm->initialized);
printf(" ** pwm_set_enable: buffer: %s\n", buffer); printf(" ** pwm_set_enable: buffer: %s\n", buffer);
printf(" ** pwm_set_enable: s = %d, len = %d\n", s, len); printf(" ** pwm_set_enable: s = %d, len = %d\n", s, len);
} }
@ -435,21 +413,35 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
char polarity_path[80]; char polarity_path[80];
int period_fd, duty_fd, polarity_fd, enable_fd; int period_fd, duty_fd, polarity_fd, enable_fd;
struct pwm_exp *new_pwm, *pwm; struct pwm_exp *new_pwm, *pwm;
int gpio = 0;
int initialized = 0;
int iscpro = 0;
// Figure out if we are a CPro
iscpro = is_this_chippro();
// Figure out which pin we are
if (strcmp(key,"U13_18") == 0) {
gpio = 0;
} else if (strcmp(key,"EINT13") == 0) {
gpio = 1;
}
// Try to get the pwm
pwm = lookup_exported_pwm(key);
if (pwm == NULL) {
initialize_pwm(&initialized, gpio);
if (DEBUG) if (DEBUG)
printf(" ** pwm_start: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_start: pwm(%d) initialized = %d\n", gpio, initialized);
if(!pwm_initialized) {
initialize_pwm();
} else { } else {
if (DEBUG) if (DEBUG)
printf(" ** pwm_start: pwm already initialized, cleaning up **"); printf(" ** pwm_start: pwm(%d) already initialized, cleaning up **", gpio);
pwm_cleanup(); pwm_cleanup();
} }
if (DEBUG)
printf(" ** pwm_start: pwm_initialized = %d\n", pwm_initialized);
//setup the pwm base path, the chip only has one pwm //setup the pwm base path, the chip only has one pwm
snprintf(pwm_base_path, sizeof(pwm_base_path), "/sys/class/pwm/pwmchip0/pwm%d", 0); BUF2SMALL(pwm_base_path); snprintf(pwm_base_path, sizeof(pwm_base_path), "/sys/class/pwm/pwmchip0/pwm%d", gpio); BUF2SMALL(pwm_base_path);
//create the path for the period and duty //create the path for the period and duty
snprintf(enable_path, sizeof(enable_path), "%s/enable", pwm_base_path); BUF2SMALL(enable_path); snprintf(enable_path, sizeof(enable_path), "%s/enable", pwm_base_path); BUF2SMALL(enable_path);
@ -515,6 +507,9 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
printf(" ** pwm_start: sysfs files opened successfully **\n"); printf(" ** pwm_start: sysfs files opened successfully **\n");
strncpy(new_pwm->key, key, KEYLEN); /* can leave string unterminated */ strncpy(new_pwm->key, key, KEYLEN); /* can leave string unterminated */
new_pwm->key[KEYLEN] = '\0'; /* terminate string */ new_pwm->key[KEYLEN] = '\0'; /* terminate string */
new_pwm->gpio = gpio;
new_pwm->iscpro = iscpro;
new_pwm->initialized = initialized;
new_pwm->period_fd = period_fd; new_pwm->period_fd = period_fd;
new_pwm->duty_fd = duty_fd; new_pwm->duty_fd = duty_fd;
new_pwm->polarity_fd = polarity_fd; new_pwm->polarity_fd = polarity_fd;
@ -534,18 +529,21 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
} }
int rtnval = 0; int rtnval = 0;
rtnval = pwm_set_enable(key, ENABLE);
// Fix for issue #53 // Fix for issue #53
// Always set polarity first
rtnval = pwm_set_polarity(key, polarity);
if (rtnval != -1) {
rtnval = 0;
rtnval = pwm_set_enable(key, ENABLE);
if (rtnval != -1) { if (rtnval != -1) {
rtnval = 0; rtnval = 0;
rtnval = pwm_set_frequency(key, freq); rtnval = pwm_set_frequency(key, freq);
if (rtnval != -1) { if (rtnval != -1) {
rtnval = 0; rtnval = 0;
//rtnval = pwm_set_polarity(key, polarity);
//rtnval = 0;
rtnval = pwm_set_duty_cycle(key, duty); rtnval = pwm_set_duty_cycle(key, duty);
} }
} }
}
return rtnval; return rtnval;
} }
@ -555,15 +553,20 @@ int pwm_disable(const char *key)
int fd, len, e_no; int fd, len, e_no;
char str_gpio[80]; char str_gpio[80];
// Per https://github.com/NextThingCo/CHIP-linux/pull/4
// we need to export 0 here to enable pwm0 pwm = lookup_exported_pwm(key);
int gpio = 0;
if (pwm == NULL) {
if (DEBUG)
printf(" ** pwm_disable: pwm struct is null **\n");
return -1;
}
// Disable the PWM // Disable the PWM
pwm_set_frequency(key, 0); pwm_set_frequency(key, 0);
//pwm_set_polarity(key, 0);
pwm_set_duty_cycle(key, 0); pwm_set_duty_cycle(key, 0);
pwm_set_enable(key, DISABLE); pwm_set_enable(key, DISABLE);
pwm_set_polarity(key, 0);
if ((fd = open("/sys/class/pwm/pwmchip0/unexport", O_WRONLY)) < 0) if ((fd = open("/sys/class/pwm/pwmchip0/unexport", O_WRONLY)) < 0)
{ {
@ -572,7 +575,7 @@ int pwm_disable(const char *key)
add_error_msg(err); add_error_msg(err);
return -1; return -1;
} }
len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio); len = snprintf(str_gpio, sizeof(str_gpio), "%d", pwm->gpio); BUF2SMALL(str_gpio);
ssize_t s = write(fd, str_gpio, len); e_no = errno; ssize_t s = write(fd, str_gpio, len); e_no = errno;
close(fd); close(fd);
if (s != len) { if (s != len) {

View File

@ -45,6 +45,7 @@ SOFTWARE.
#include <string.h> #include <string.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/sysinfo.h>
int setup_error = 0; int setup_error = 0;
int module_setup = 0; int module_setup = 0;
@ -52,6 +53,9 @@ int module_setup = 0;
// Library Debug // Library Debug
int DEBUG = 0; int DEBUG = 0;
// Is This a CHIP PRO
int is_chip_pro = 0;
pins_t pins_info[] = { pins_t pins_info[] = {
{ "GND", "GND", "U13_1", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "GND", "GND", "U13_1", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CHG-IN", "CHG-IN", "U13_2", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CHG-IN", "CHG-IN", "U13_2", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
@ -65,39 +69,40 @@ pins_t pins_info[] = {
{ "PWRON", "PWRON", "U13_10", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "PWRON", "PWRON", "U13_10", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "TWI1-SCK", "KPD-I2C-SCL", "U13_11", 47, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "TWI1-SCK", "KPD-I2C-SCL", "U13_11", 47, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "GND", "GND", "U13_12", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "GND", "GND", "U13_12", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "X1", "X1", "U13_13", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "X1", "X1", "U13_13", -1, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "X2", "X2", "U13_14", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "X2", "X2", "U13_14", -1, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "Y1", "Y1", "U13_15", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "Y1", "Y1", "U13_15", -1, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "Y2", "Y2", "U13_16", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "Y2", "Y2", "U13_16", -1, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D2", "LCD-D2", "U13_17", 98, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D2", "UART2-TX", "U13_17", 98, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "PWM0", "PWM0", "U13_18", 34, BASE_METHOD_AS_IS, 0, -1, BOTH}, { "PWM0", "PWM0", "U13_18", 34, BASE_METHOD_AS_IS, 0, -1, BOTH},
{ "LCD-D4", "LCD-D4", "U13_19", 100, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "PWM1", "PWM1", "EINT13", 205, BASE_METHOD_AS_IS, 0, -1, CHIPPRO},
{ "LCD-D3", "LCD-D3", "U13_20", 99, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D4", "UART2-CTS", "U13_19", 100, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "LCD-D6", "LCD-D6", "U13_21", 102, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D3", "UART2-RX", "U13_20", 99, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "LCD-D5", "LCD-D5", "U13_22", 101, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D6", "LCD-D6", "U13_21", 102, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D10", "LCD-D10", "U13_23", 106, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D5", "UART2-RTS", "U13_22", 101, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "LCD-D7", "LCD-D7", "U13_24", 103, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D10", "LCD-D10", "U13_23", 106, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D12", "LCD-D12", "U13_25", 108, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D7", "LCD-D7", "U13_24", 103, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D11", "LCD-D11", "U13_26", 107, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D12", "LCD-D12", "U13_25", 108, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D14", "LCD-D14", "U13_27", 110, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D11", "LCD-D11", "U13_26", 107, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D13", "LCD-D13", "U13_28", 109, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D14", "LCD-D14", "U13_27", 110, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D18", "LCD-D18", "U13_29", 114, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D13", "LCD-D13", "U13_28", 109, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D15", "LCD-D15", "U13_30", 111, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D18", "LCD-D18", "U13_29", 114, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D20", "LCD-D20", "U13_31", 116, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D15", "LCD-D15", "U13_30", 111, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D19", "LCD-D19", "U13_32", 115, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D20", "LCD-D20", "U13_31", 116, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D22", "LCD-D22", "U13_33", 118, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D19", "LCD-D19", "U13_32", 115, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D21", "LCD-D21", "U13_34", 117, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D22", "LCD-D22", "U13_33", 118, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-CLK", "LCD-CLK", "U13_35", 120, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D21", "LCD-D21", "U13_34", 117, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-D23", "LCD-D23", "U13_36", 119, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-CLK", "LCD-CLK", "U13_35", 120, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-VSYNC", "LCD-VSYNC", "U13_37", 123, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-D23", "LCD-D23", "U13_36", 119, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-HSYNC", "LCD-HSYNC", "U13_38", 122, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-VSYNC", "LCD-VSYNC", "U13_37", 123, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "LCD-HSYNC", "LCD-HSYNC", "U13_38", 122, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "GND", "GND", "U13_39", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "GND", "GND", "U13_39", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "LCD-DE", "LCD-DE", "U13_40", 121, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "LCD-DE", "LCD-DE", "U13_40", 121, BASE_METHOD_AS_IS, -1, -1, CHIP},
{ "GND", "GND", "U14_1", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "GND", "GND", "U14_1", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "VCC-5V", "VCC-5V", "U14_2", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "VCC-5V", "VCC-5V", "U14_2", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "UART1-TX", "UART-TX", "U14_3", 195, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "UART1-TX", "UART-TX", "U14_3", 195, BASE_METHOD_AS_IS, -1, -1, BOTH}, /* THIS IS AP-EINT3 ON CHIP PRO */
{ "HPL", "HPL", "U14_4", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "HPL", "HPL", "U14_4", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "UART1-RX", "UART-RX", "U14_5", 196, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "UART1-RX", "UART-RX", "U14_5", 196, BASE_METHOD_AS_IS, -1, -1, BOTH}, /* THIS IS AP-EINT4 ON CHIP PRO */
{ "HPCOM", "HPCOM", "U14_6", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "HPCOM", "HPCOM", "U14_6", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "FEL", "FEL", "U14_7", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "FEL", "FEL", "U14_7", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "HPR", "HPR", "U14_8", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "HPR", "HPR", "U14_8", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
@ -123,16 +128,21 @@ pins_t pins_info[] = {
{ "CSICK", "SPI-CLK", "U14_28", 129, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSICK", "SPI-CLK", "U14_28", 129, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSIHSYNC", "SPI-MOSI", "U14_29", 130, BASE_METHOD_AS_IS, 1, -1, BOTH}, { "CSIHSYNC", "SPI-MOSI", "U14_29", 130, BASE_METHOD_AS_IS, 1, -1, BOTH},
{ "CSIVSYNC", "SPI-MISO", "U14_30", 131, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSIVSYNC", "SPI-MISO", "U14_30", 131, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID0", "CSID0", "U14_31", 132, BASE_METHOD_AS_IS, 1, -1, BOTH}, { "CSID0", "D0", "U14_31", 132, BASE_METHOD_AS_IS, 1, -1, BOTH},
{ "CSID1", "CSID1", "U14_32", 133, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID1", "D1", "U14_32", 133, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID2", "CSID2", "U14_33", 134, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID2", "D2", "U14_33", 134, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID3", "CSID3", "U14_34", 135, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID3", "D3", "U14_34", 135, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID4", "CSID4", "U14_35", 136, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID4", "D4", "U14_35", 136, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID5", "CSID5", "U14_36", 137, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID5", "D5", "U14_36", 137, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID6", "CSID6", "U14_37", 138, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID6", "D6", "U14_37", 138, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "CSID7", "CSID7", "U14_38", 139, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "CSID7", "D7", "U14_38", 139, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "GND", "GND", "U14_39", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "GND", "GND", "U14_39", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "GND", "GND", "U14_40", -1, BASE_METHOD_AS_IS, -1, -1, BOTH}, { "GND", "GND", "U14_40", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
{ "I2S-MCLK", "EINT19", "21", 37, BASE_METHOD_AS_IS, -1, -1, CHIPPRO},
{ "I2S-BCLK", "I2S-BCLK", "22", 38, BASE_METHOD_AS_IS, -1, -1, CHIPPRO},
{ "I2S-LCLK", "I2S-LCLK", "23", 39, BASE_METHOD_AS_IS, -1, -1, CHIPPRO},
{ "I2S-DO", "I2S-DO", "24", 40, BASE_METHOD_AS_IS, -1, -1, CHIPPRO},
{ "I2S-DI", "EINT24", "25", 41, BASE_METHOD_AS_IS, -1, -1, CHIPPRO},
{ NULL, NULL, NULL, -1, 0, -1, -1, -1} { NULL, NULL, NULL, -1, 0, -1, -1, -1}
}; };
@ -216,12 +226,107 @@ int get_xio_base(void)
return xio_base_address; return xio_base_address;
} /* get_xio_base */ } /* get_xio_base */
#define RAMDETERMINER 380.0
int is_this_chippro(void)
{
int is_pro = 0;
struct sysinfo si;
sysinfo (&si);
const double megabyte = 1024 * 1024;
if (DEBUG)
printf(" ** is_this_chippro: total system ram: %5.1f mb\n", si.totalram / megabyte);
if ((si.totalram/megabyte) > RAMDETERMINER) {
is_pro = 0;
if (DEBUG)
printf(" ** is_this_chippro: we are a chip\n");
} else {
is_pro = 1;
if (DEBUG)
printf(" ** is_this_chippro: we are a chip pro\n");
}
return is_pro;
}
int gpio_allowed(int gpio)
{
int rtnval = -1;
pins_t *p;
int tmpgpio = -1;
// If the return is good, we should be good to go, so let's check the data
// Loop through the pins
for (p = pins_info; p->key != NULL; ++p) {
tmpgpio = gpio_number(p);
if (tmpgpio == gpio) {
if (DEBUG)
printf(" ** gpio_allowed: found match\n");
// We have a CHIP and the pin is for CHIP/BOTH
if (((p->sbc_type == CHIP) || (p->sbc_type == BOTH)) && (is_this_chippro() == 0)) {
if (DEBUG)
printf(" ** gpio_allowed: pin allowed for chip or both and we're a chip\n");
rtnval = 1;
// We have a CHIP Pro and the pin is for CHIPPRO/BOTH
} else if (((p->sbc_type == CHIPPRO) || (p->sbc_type == BOTH)) && (is_this_chippro() == 1)) {
if (DEBUG)
printf(" ** gpio_allowed: pin allowed for chip pro or both and we're a chip pro\n");
rtnval = 1;
} else {
if (DEBUG)
printf(" ** gpio_allowed: pin is not allowed on hardware\n");
rtnval = 0;
}
}
}
return rtnval;
}
int pwm_allowed(const char *key)
{
int rtnval = -1;
pins_t *p;
// Determine if we are CHIP Pro
// Running because we cannot be sure if it was previously run
// If the return is good, we should be good to go, so let's check the data
for (p = pins_info; p->key != NULL; ++p) {
if (strcmp(p->key, key) == 0) {
if (DEBUG)
printf(" ** pwm_allowed: found match\n");
// We have a CHIP and the pin is for CHIP/BOTH
if ((p->sbc_type == BOTH) && (is_this_chippro() == 0)) {
if (DEBUG)
printf(" ** pwm_allowed: pwm allowed for chip or both and we're a chip\n");
rtnval = 1;
// We have a CHIP Pro and the pin is for CHIPPRO/BOTH
} else if (((p->sbc_type == CHIPPRO) || (p->sbc_type == BOTH)) && (is_this_chippro() == 1)) {
if (DEBUG)
printf(" ** pwm_allowed: pwm allowed for chip pro or both and we're a chip pro\n");
rtnval = 1;
} else {
if (DEBUG)
printf(" ** pwm_allowed: pwm is not allowed on hardware\n");
rtnval = 0;
}
}
}
return rtnval;
}
void toggle_debug(void) void toggle_debug(void)
{ {
if (DEBUG) { if (DEBUG) {
DEBUG = 0; DEBUG = 0;
printf(" ** debug disabled\n");
} else { } else {
DEBUG = 1; DEBUG = 1;
printf(" ** debug enabled\n");
} }
} }
@ -266,6 +371,28 @@ int gpio_pud_capable(pins_t *pin)
return capable; return capable;
} }
int lookup_gpio_by_number(const char *num) {
// Convert the char to an int
char *ptr;
long ret;
int gpnum;
ret = strtol(num, &ptr, 10);
if (ret == 0) {
return -1;
}
// If we make it here, lets look for the data
pins_t *p;
for (p = pins_info; p->key != NULL; ++p) {
gpnum = gpio_number(p);
// If the number of the gpio pin matches the input
// we are
if (gpnum == (int)ret) {
return gpnum;
}
}
return -1;
}
int lookup_gpio_by_key(const char *key) int lookup_gpio_by_key(const char *key)
{ {
pins_t *p; pins_t *p;
@ -437,11 +564,14 @@ int get_gpio_number(const char *key, int *gpio)
*gpio = lookup_gpio_by_name(key); *gpio = lookup_gpio_by_name(key);
if (*gpio <= 0) { if (*gpio <= 0) {
*gpio = lookup_gpio_by_altname(key); *gpio = lookup_gpio_by_altname(key);
if (*gpio <=0) {
*gpio = lookup_gpio_by_number(key);
if (*gpio <= 0) { if (*gpio <= 0) {
status = -1; /* error */ status = -1; /* error */
} }
} }
} }
}
return status; return status;
} }
@ -454,7 +584,7 @@ int compute_port_pin(const char *key, int gpio, int *port, int *pin)
if (capable < 0) { if (capable < 0) {
capable = lookup_pud_capable_by_name(key); capable = lookup_pud_capable_by_name(key);
if (capable < 0) { if (capable < 0) {
capable = lookup_gpio_by_altname(key); capable = lookup_pud_capable_by_altname(key);
if (capable < 0) { if (capable < 0) {
capable = 0; // default to false capable = 0; // default to false
} }

View File

@ -86,13 +86,15 @@ typedef struct dyn_int_array_s dyn_int_array_t;
#define FILENAME_BUFFER_SIZE 128 #define FILENAME_BUFFER_SIZE 128
int setup_error; extern int setup_error;
int module_setup; extern int module_setup;
int DEBUG; extern int DEBUG;
int get_xio_base(void); int get_xio_base(void);
int is_this_chippro(void);
int gpio_number(pins_t *pin); int gpio_number(pins_t *pin);
int gpio_pud_capable(pins_t *pin); int gpio_pud_capable(pins_t *pin);
int lookup_gpio_by_number(const char *num);
int lookup_gpio_by_key(const char *key); int lookup_gpio_by_key(const char *key);
int lookup_gpio_by_name(const char *name); int lookup_gpio_by_name(const char *name);
int lookup_gpio_by_altname(const char *altname); int lookup_gpio_by_altname(const char *altname);
@ -118,3 +120,5 @@ char *get_error_msg(void);
void add_error_msg(char *msg); void add_error_msg(char *msg);
void toggle_debug(void); void toggle_debug(void);
int compute_port_pin(const char *key, int gpio, int *port, int *pin); int compute_port_pin(const char *key, int gpio, int *port, int *pin);
int gpio_allowed(int gpio);
int pwm_allowed(const char *key);

View File

@ -85,9 +85,6 @@ void define_constants(PyObject *module)
bcm = Py_BuildValue("i", BCM); bcm = Py_BuildValue("i", BCM);
PyModule_AddObject(module, "BCM", bcm); PyModule_AddObject(module, "BCM", bcm);
module_debug = Py_BuildValue("i", DEBUG ? Py_True: Py_False); version = Py_BuildValue("s", "0.7.1");
PyModule_AddObject(module, "DEBUG", module_debug);
version = Py_BuildValue("s", "0.4.0");
PyModule_AddObject(module, "VERSION", version); PyModule_AddObject(module, "VERSION", version);
} }

View File

@ -13,6 +13,5 @@ PyObject *version;
PyObject *unknown; PyObject *unknown;
PyObject *board; PyObject *board;
PyObject *bcm; PyObject *bcm;
PyObject *module_debug;
void define_constants(PyObject *module); void define_constants(PyObject *module);

View File

@ -171,13 +171,17 @@ int gpio_export(int gpio)
len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio); len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio);
ssize_t s = write(fd, str_gpio, len); e_no = errno; ssize_t s = write(fd, str_gpio, len); e_no = errno;
if (DEBUG)
if (e_no)
printf("gpio_export: something went wrong: %s\n", strerror(e_no));
close(fd); close(fd);
if (s != len) if (s != len)
{ {
char err[256]; char err[256];
snprintf(err, sizeof(err), "gpio_export: could not write '%s' to %s (%s)", str_gpio, filename, strerror(e_no)); snprintf(err, sizeof(err), "gpio_export: could not write '%s' to %s (%s)", str_gpio, filename, strerror(e_no));
add_error_msg(err); add_error_msg(err);
return -1; return -2;
} }
// add to list // add to list
@ -379,12 +383,24 @@ int gpio_set_direction(int gpio, unsigned int in_flag)
char filename[MAX_FILENAME]; filename[0] = '\0'; char filename[MAX_FILENAME]; filename[0] = '\0';
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/direction", gpio); BUF2SMALL(filename); snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/direction", gpio); BUF2SMALL(filename);
if ((fd = open(filename, O_WRONLY)) < 0) {
// NOTIFY THAT WE'RE GOING TO SLEEP AND RETRY
char err[256];
snprintf(err, sizeof(err), "gpio_set_direction: could not open '%s', sleeping for 1 second and retrying", filename);
add_error_msg(err);
// if called as non-root, udev may need time to adjust file
// permissions after setting up gpio
sleep(1);
// TRY AGAIN AND IF THIS TIME FAILS, KICK OUT
if ((fd = open(filename, O_WRONLY)) < 0) { if ((fd = open(filename, O_WRONLY)) < 0) {
char err[256]; char err[256];
snprintf(err, sizeof(err), "gpio_set_direction: could not open '%s' (%s)", filename, strerror(errno)); snprintf(err, sizeof(err), "gpio_set_direction: could not open '%s' (%s)", filename, strerror(errno));
add_error_msg(err); add_error_msg(err);
return -1; return -1;
} }
}
char direction[16]; char direction[16];
if (in_flag) { if (in_flag) {
@ -1023,7 +1039,7 @@ void event_cleanup(void)
} }
// blocking_wait_for_edge assumes the caller has ensured the GPIO is already exported. // blocking_wait_for_edge assumes the caller has ensured the GPIO is already exported.
int blocking_wait_for_edge(int gpio, unsigned int edge) int blocking_wait_for_edge(int gpio, unsigned int edge, int timeout)
// standalone from all the event functions above // standalone from all the event functions above
{ {
int fd = fd_lookup(gpio); int fd = fd_lookup(gpio);
@ -1078,7 +1094,7 @@ int blocking_wait_for_edge(int gpio, unsigned int edge)
// epoll for event // epoll for event
for (i = 0; i<2; i++) // first time triggers with current state, so ignore for (i = 0; i<2; i++) // first time triggers with current state, so ignore
{ {
if ((n = epoll_wait(epfd, &events, 1, -1)) == -1) if ((n = epoll_wait(epfd, &events, 1, timeout)) == -1)
{ {
gpio_event_remove(gpio); gpio_event_remove(gpio);
return 5; return 5;

View File

@ -86,4 +86,4 @@ int gpio_event_remove(int gpio);
int gpio_is_evented(int gpio); int gpio_is_evented(int gpio);
int event_initialise(void); int event_initialise(void);
void event_cleanup(void); void event_cleanup(void);
int blocking_wait_for_edge(int gpio, unsigned int edge); int blocking_wait_for_edge(int gpio, unsigned int edge, int timeout);

View File

@ -36,6 +36,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
#include <stdio.h>
#include "stdlib.h" #include "stdlib.h"
#include "Python.h" #include "Python.h"
#include "constants.h" #include "constants.h"
@ -43,6 +44,7 @@ SOFTWARE.
#include "event_gpio.h" #include "event_gpio.h"
static int gpio_warnings = 1; static int gpio_warnings = 1;
static int r8_mem_setup = 0;
int max_gpio = -1; int max_gpio = -1;
dyn_int_array_t *gpio_direction = NULL; dyn_int_array_t *gpio_direction = NULL;
@ -71,13 +73,6 @@ static int init_module(void)
{ {
clear_error_msg(); clear_error_msg();
if (map_pio_memory() < 0) {
char err[2000];
snprintf(err, sizeof(err), "init_module error (%s)", get_error_msg());
PyErr_SetString(PyExc_RuntimeError, err);
return 0;
}
// If we make it here, we're good to go // If we make it here, we're good to go
if (DEBUG) if (DEBUG)
printf(" ** init_module: setup complete **\n"); printf(" ** init_module: setup complete **\n");
@ -86,6 +81,38 @@ static int init_module(void)
return 0; return 0;
} }
static int init_r8_gpio_mem(void)
{
clear_error_msg();
if (DEBUG)
printf(" ** init_r8_gpio_mem: mapping memory **\n");
if (map_pio_memory() < 0) {
char err[2000];
snprintf(err, sizeof(err), "init_r8_gpio_mem error (%s)", get_error_msg());
PyErr_SetString(PyExc_RuntimeError, err);
return 0;
}
// If we make it here, we're good to go
if (DEBUG)
printf(" ** init_r8_gpio_mem: setup complete **\n");
r8_mem_setup = 1;
return 0;
}
// python function value = is_chip_pro
static PyObject *py_is_chip_pro(PyObject *self, PyObject *args)
{
PyObject *py_value;
py_value = Py_BuildValue("i", is_this_chippro());
return py_value;
}
static void remember_gpio_direction(int gpio, int direction) static void remember_gpio_direction(int gpio, int direction)
{ {
dyn_int_array_set(&gpio_direction, gpio, direction, -1); dyn_int_array_set(&gpio_direction, gpio, direction, -1);
@ -103,14 +130,24 @@ static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
static char *kwlist[] = {"channel", NULL}; static char *kwlist[] = {"channel", NULL};
clear_error_msg(); clear_error_msg();
// Channel is optional // Channel is optional
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel)) { // Try to parse the string
int rtn;
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &inchan);
if (!rtn) {
return NULL; return NULL;
} }
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
// The !channel fixes issues #50 // The !channel fixes issues #50
if (channel == NULL || strcmp(channel, "\0") == 0) { if (channel == NULL || strcmp(channel, "\0") == 0) {
@ -129,7 +166,9 @@ static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
static PyObject *py_setup_channel(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_setup_channel(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
int allowed = -1;
char *channel; char *channel;
int inchan;
int direction; int direction;
int pud = PUD_OFF; int pud = PUD_OFF;
int initial = 0; int initial = 0;
@ -137,13 +176,30 @@ static PyObject *py_setup_channel(PyObject *self, PyObject *args, PyObject *kwar
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "si|ii", kwlist, &channel, &direction, &pud, &initial)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "si|ii", kwlist, &channel, &direction, &pud, &initial);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "ii|ii", kwlist, &inchan, &direction, &pud, &initial);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (!module_setup) { if (!module_setup) {
init_module(); init_module();
} }
if (get_gpio_number(channel, &gpio) < 0) {
char err[2000];
snprintf(err, sizeof(err), "Invalid channel %s. (%s)", channel, get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (direction != INPUT && direction != OUTPUT) if (direction != INPUT && direction != OUTPUT)
{ {
PyErr_SetString(PyExc_ValueError, "An invalid direction was passed to setup()"); PyErr_SetString(PyExc_ValueError, "An invalid direction was passed to setup()");
@ -168,11 +224,36 @@ static PyObject *py_setup_channel(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
if (gpio_export(gpio) < 0) { // Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// Only map /dev/mem if we're not an XIO
if (!r8_mem_setup && !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
init_r8_gpio_mem();
}
int exprtn = gpio_export(gpio);
if (exprtn == -1) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "Error setting up channel %s, maybe already exported? (%s)", channel, get_error_msg()); snprintf(err, sizeof(err), "Error setting up channel %s, maybe already exported? (%s)", channel, get_error_msg());
PyErr_SetString(PyExc_RuntimeError, err); PyErr_SetString(PyExc_RuntimeError, err);
return NULL; return NULL;
} else if (exprtn == -2 && gpio_warnings) {
char warn[2000];
snprintf(warn, sizeof(warn), "Channel %s may already be exported, proceeding with rest of setup", channel);
PyErr_WarnEx(PyExc_Warning, warn, 1);
} }
if (gpio_set_direction(gpio, direction) < 0) { if (gpio_set_direction(gpio, direction) < 0) {
char err[2000]; char err[2000];
@ -211,24 +292,50 @@ static PyObject *py_setup_channel(PyObject *self, PyObject *args, PyObject *kwar
Py_RETURN_NONE; Py_RETURN_NONE;
} /* py_setup_channel */ } /* py_setup_channel */
// python function output(channel, value) // python function output(channel, value)
static PyObject *py_output_gpio(PyObject *self, PyObject *args) static PyObject *py_output_gpio(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
int value; int value;
char *channel; char *channel;
int inchan;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "si", &channel, &value)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "si", &channel, &value);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "ii", &inchan, &value);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (!module_setup || dyn_int_array_get(&gpio_direction, gpio, -1) != OUTPUT) if (!module_setup || dyn_int_array_get(&gpio_direction, gpio, -1) != OUTPUT)
{ {
char err[2000]; char err[2000];
@ -254,19 +361,46 @@ static PyObject *py_input_gpio(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
unsigned int value; unsigned int value;
PyObject *py_value; PyObject *py_value;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "s", &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "i", &inchan);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check channel is set up as an input or output // check channel is set up as an input or output
if (!module_setup || (dyn_int_array_get(&gpio_direction, gpio, -1) == -1)) if (!module_setup || (dyn_int_array_get(&gpio_direction, gpio, -1) == -1))
{ {
@ -292,19 +426,46 @@ static PyObject *py_read_byte_gpio(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
unsigned int value = 0; unsigned int value = 0;
PyObject *py_value; PyObject *py_value;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "s", &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "i", &inchan);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check channel is set up as an input or output // check channel is set up as an input or output
if (!module_setup || (dyn_int_array_get(&gpio_direction, gpio, -1) == -1)) if (!module_setup || (dyn_int_array_get(&gpio_direction, gpio, -1) == -1))
{ {
@ -330,19 +491,46 @@ static PyObject *py_read_word_gpio(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
unsigned int value = 0; unsigned int value = 0;
PyObject *py_value; PyObject *py_value;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "s", &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "i", &inchan);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check channel is set up as an input or output // check channel is set up as an input or output
if (!module_setup || (dyn_int_array_get(&gpio_direction, gpio, -1) == -1)) if (!module_setup || (dyn_int_array_get(&gpio_direction, gpio, -1) == -1))
{ {
@ -436,19 +624,31 @@ static int add_py_callback(char *channel, int gpio, int edge, unsigned int bounc
return 0; return 0;
} }
// python function add_event_callback(gpio, callback, bouncetime=0) // python function add_event_callback(channel, callback, bouncetime=0)
static PyObject *py_add_event_callback(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_add_event_callback(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
int allowed = -1;
unsigned int bouncetime = 0; unsigned int bouncetime = 0;
PyObject *cb_func; PyObject *cb_func;
char *kwlist[] = {"gpio", "callback", "bouncetime", NULL}; char *kwlist[] = {"gpio", "callback", "bouncetime", NULL};
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|i", kwlist, &channel, &cb_func, &bouncetime)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "sO|i", kwlist, &channel, &cb_func, &bouncetime);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "iO|i", kwlist, &inchan, &cb_func, &bouncetime);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (!PyCallable_Check(cb_func)) if (!PyCallable_Check(cb_func))
{ {
@ -461,9 +661,27 @@ static PyObject *py_add_event_callback(PyObject *self, PyObject *args, PyObject
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check to ensure gpio is one of the allowed pins // check to ensure gpio is one of the allowed pins
if (gpio != lookup_gpio_by_name("AP-EINT3") if (gpio != lookup_gpio_by_name("AP-EINT3")
&& gpio != lookup_gpio_by_name("AP-EINT1") && gpio != lookup_gpio_by_name("AP-EINT1")
&& gpio != lookup_gpio_by_name("I2S-MCLK") // CHIP PRO
&& gpio != lookup_gpio_by_name("I2S-DI") // CHIP PRO
&& gpio != lookup_gpio_by_name("PWM1") // CHIP PRO
&& !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { && !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
PyErr_SetString(PyExc_ValueError, "Callbacks currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only"); PyErr_SetString(PyExc_ValueError, "Callbacks currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only");
return NULL; return NULL;
@ -488,20 +706,32 @@ static PyObject *py_add_event_callback(PyObject *self, PyObject *args, PyObject
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python function add_event_detect(gpio, edge, callback=None, bouncetime=0 // python function add_event_detect(channel, edge, callback=None, bouncetime=0)
static PyObject *py_add_event_detect(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_add_event_detect(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
int edge, result; int edge, result;
unsigned int bouncetime = 0; unsigned int bouncetime = 0;
int allowed = -1;
PyObject *cb_func = NULL; PyObject *cb_func = NULL;
char *kwlist[] = {"gpio", "edge", "callback", "bouncetime", NULL}; char *kwlist[] = {"gpio", "edge", "callback", "bouncetime", NULL};
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "si|Oi", kwlist, &channel, &edge, &cb_func, &bouncetime)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "si|Oi", kwlist, &channel, &edge, &cb_func, &bouncetime);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "ii|Oi", kwlist, &inchan, &edge, &cb_func, &bouncetime);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (cb_func != NULL && !PyCallable_Check(cb_func)) if (cb_func != NULL && !PyCallable_Check(cb_func))
{ {
@ -514,9 +744,27 @@ static PyObject *py_add_event_detect(PyObject *self, PyObject *args, PyObject *k
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check to ensure gpio is one of the allowed pins // check to ensure gpio is one of the allowed pins
if (gpio != lookup_gpio_by_name("AP-EINT3") if (gpio != lookup_gpio_by_name("AP-EINT3")
&& gpio != lookup_gpio_by_name("AP-EINT1") && gpio != lookup_gpio_by_name("AP-EINT1")
&& gpio != lookup_gpio_by_name("I2S-MCLK") // CHIP PRO
&& gpio != lookup_gpio_by_name("I2S-DI") // CHIP PRO
&& gpio != lookup_gpio_by_name("PWM1") // CHIP PRO
&& !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { && !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
PyErr_SetString(PyExc_ValueError, "Edge Detection currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only"); PyErr_SetString(PyExc_ValueError, "Edge Detection currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only");
return NULL; return NULL;
@ -555,28 +803,58 @@ static PyObject *py_add_event_detect(PyObject *self, PyObject *args, PyObject *k
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python function remove_event_detect(gpio) // python function remove_event_detect(channel)
static PyObject *py_remove_event_detect(PyObject *self, PyObject *args) static PyObject *py_remove_event_detect(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
struct py_callback *cb = py_callbacks; struct py_callback *cb = py_callbacks;
struct py_callback *temp; struct py_callback *temp;
struct py_callback *prev = NULL; struct py_callback *prev = NULL;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "s", &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "i", &inchan);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check to ensure gpio is one of the allowed pins // check to ensure gpio is one of the allowed pins
if (gpio != lookup_gpio_by_name("AP-EINT3") if (gpio != lookup_gpio_by_name("AP-EINT3")
&& gpio != lookup_gpio_by_name("AP-EINT1") && gpio != lookup_gpio_by_name("AP-EINT1")
&& gpio != lookup_gpio_by_name("I2S-MCLK") // CHIP PRO
&& gpio != lookup_gpio_by_name("I2S-DI") // CHIP PRO
&& gpio != lookup_gpio_by_name("PWM1") // CHIP PRO
&& !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { && !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
PyErr_SetString(PyExc_ValueError, "Edge Detection currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only"); PyErr_SetString(PyExc_ValueError, "Edge Detection currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only");
return NULL; return NULL;
@ -611,44 +889,103 @@ static PyObject *py_event_detected(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "s", &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "i", &inchan);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (event_detected(gpio)) if (event_detected(gpio))
Py_RETURN_TRUE; Py_RETURN_TRUE;
else else
Py_RETURN_FALSE; Py_RETURN_FALSE;
} }
// python function py_wait_for_edge(gpio, edge) // python function py_wait_for_edge(gpio, edge, timeout = -1)
static PyObject *py_wait_for_edge(PyObject *self, PyObject *args) static PyObject *py_wait_for_edge(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
int edge, result; int edge, result, timeout;
char *channel; char *channel;
int inchan;
char error[81]; char error[81];
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "si", &channel, &edge)) timeout = -1;
// Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "si|i", &channel, &edge, &timeout);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "ii|i", &inchan, &edge, &timeout);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// check to ensure gpio is one of the allowed pins // check to ensure gpio is one of the allowed pins
if (gpio != lookup_gpio_by_name("AP-EINT3") if (gpio != lookup_gpio_by_name("AP-EINT3")
&& gpio != lookup_gpio_by_name("AP-EINT1") && gpio != lookup_gpio_by_name("AP-EINT1")
&& gpio != lookup_gpio_by_name("I2S-MCLK") // CHIP PRO
&& gpio != lookup_gpio_by_name("I2S-DI") // CHIP PRO
&& gpio != lookup_gpio_by_name("PWM1") // CHIP PRO
&& !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) { && !(gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
PyErr_SetString(PyExc_ValueError, "Edge Detection currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only"); PyErr_SetString(PyExc_ValueError, "Edge Detection currently available on AP-EINT1, AP-EINT3, and XIO-P0 to XIO-P7 only");
return NULL; return NULL;
@ -669,7 +1006,7 @@ static PyObject *py_wait_for_edge(PyObject *self, PyObject *args)
} }
Py_BEGIN_ALLOW_THREADS // disable GIL Py_BEGIN_ALLOW_THREADS // disable GIL
result = blocking_wait_for_edge(gpio, edge); result = blocking_wait_for_edge(gpio, edge, timeout);
Py_END_ALLOW_THREADS // enable GIL Py_END_ALLOW_THREADS // enable GIL
if (result == 0) { if (result == 0) {
@ -687,24 +1024,51 @@ static PyObject *py_wait_for_edge(PyObject *self, PyObject *args)
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python function value = gpio_function(gpio) // python function value = gpio_function(channel)
static PyObject *py_gpio_function(PyObject *self, PyObject *args) static PyObject *py_gpio_function(PyObject *self, PyObject *args)
{ {
int gpio; int gpio;
unsigned int value; unsigned int value;
PyObject *func; PyObject *func;
char *channel; char *channel;
int inchan;
int allowed = -1;
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTuple(args, "s", &channel);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTuple(args, "i", &inchan);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (get_gpio_number(channel, &gpio)) { if (get_gpio_number(channel, &gpio)) {
PyErr_SetString(PyExc_ValueError, "Invalid channel"); PyErr_SetString(PyExc_ValueError, "Invalid channel");
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (setup_error) if (setup_error)
{ {
PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!"); PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!");
@ -886,18 +1250,30 @@ static const char moduledocstring[] = "GPIO functionality of a CHIP using Python
/* /*
mine for changing pin directipn mine for changing pin directipn
*/ */
// python function set_direction(channel, direction)
static PyObject *py_set_direction(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_set_direction(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char *channel; char *channel;
int inchan;
int direction; int direction;
int allowed = -1;
static char *kwlist[] = { "channel", "direction", NULL }; static char *kwlist[] = { "channel", "direction", NULL };
clear_error_msg(); clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "si|ii", kwlist, &channel, &direction)) // Try to parse the string
int rtn;
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "si", kwlist, &channel, &direction);
if (!rtn) {
// Fall into here are try to parse an int
rtn = PyArg_ParseTupleAndKeywords(args, kwargs, "ii", kwlist, &inchan, &direction);
if (!rtn) {
return NULL; return NULL;
}
// We make it here, we can convert inchan to a string for us to ensure it's valid
asprintf(&channel, "%i", inchan);
}
if (!module_setup) { if (!module_setup) {
init_module(); init_module();
@ -916,6 +1292,21 @@ static PyObject *py_set_direction(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (gpio_set_direction(gpio, direction) < 0) { if (gpio_set_direction(gpio, direction) < 0) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "Error setting direction %d on channel %s. (%s)", direction, channel, get_error_msg()); snprintf(err, sizeof(err), "Error setting direction %d on channel %s. (%s)", direction, channel, get_error_msg());
@ -939,7 +1330,7 @@ PyMethodDef gpio_methods[] = {
{"remove_event_detect", py_remove_event_detect, METH_VARARGS, "Remove edge detection for a particular GPIO channel\ngpio - gpio channel"}, {"remove_event_detect", py_remove_event_detect, METH_VARARGS, "Remove edge detection for a particular GPIO channel\ngpio - gpio channel"},
{"event_detected", py_event_detected, METH_VARARGS, "Returns True if an edge has occured on a given GPIO. You need to enable edge detection using add_event_detect() first.\ngpio - gpio channel"}, {"event_detected", py_event_detected, METH_VARARGS, "Returns True if an edge has occured on a given GPIO. You need to enable edge detection using add_event_detect() first.\ngpio - gpio channel"},
{"add_event_callback", (PyCFunction)py_add_event_callback, METH_VARARGS | METH_KEYWORDS, "Add a callback for an event already defined using add_event_detect()\ngpio - gpio channel\ncallback - a callback function\n[bouncetime] - Switch bounce timeout in ms"}, {"add_event_callback", (PyCFunction)py_add_event_callback, METH_VARARGS | METH_KEYWORDS, "Add a callback for an event already defined using add_event_detect()\ngpio - gpio channel\ncallback - a callback function\n[bouncetime] - Switch bounce timeout in ms"},
{"wait_for_edge", py_wait_for_edge, METH_VARARGS, "Wait for an edge.\ngpio - gpio channel\nedge - RISING, FALLING or BOTH"}, {"wait_for_edge", py_wait_for_edge, METH_VARARGS, "Wait for an edge.\ngpio - gpio channel\nedge - RISING, FALLING or BOTH\ntimeout (optional) - time to wait in miliseconds. -1 will wait forever (default)"},
{"gpio_function", py_gpio_function, METH_VARARGS, "Return the current GPIO function (IN, OUT, ALT0)\ngpio - gpio channel"}, {"gpio_function", py_gpio_function, METH_VARARGS, "Return the current GPIO function (IN, OUT, ALT0)\ngpio - gpio channel"},
{"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"}, {"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
{"get_gpio_base", py_gpio_base, METH_VARARGS, "Get the XIO base number for sysfs"}, {"get_gpio_base", py_gpio_base, METH_VARARGS, "Get the XIO base number for sysfs"},
@ -947,6 +1338,7 @@ PyMethodDef gpio_methods[] = {
{"direction", (PyCFunction)py_set_direction, METH_VARARGS | METH_KEYWORDS, "Change direction of gpio channel. Either INPUT or OUTPUT\n" }, {"direction", (PyCFunction)py_set_direction, METH_VARARGS | METH_KEYWORDS, "Change direction of gpio channel. Either INPUT or OUTPUT\n" },
{"setmode", (PyCFunction)py_setmode, METH_VARARGS, "Dummy function that does nothing but maintain compatibility with RPi.GPIO\n" }, {"setmode", (PyCFunction)py_setmode, METH_VARARGS, "Dummy function that does nothing but maintain compatibility with RPi.GPIO\n" },
{"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"},
{"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"},
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };

View File

@ -34,11 +34,29 @@ SOFTWARE.
#include "common.h" #include "common.h"
#include "c_pwm.h" #include "c_pwm.h"
// python function cleanup() // python function cleanup(channel)
static PyObject *py_cleanup(PyObject *self, PyObject *args) static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
// unexport the PWM char key[8];
char *channel;
static char *kwlist[] = {"channel", NULL};
clear_error_msg();
// Channel is optional
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel)) {
return NULL;
}
// The !channel fixes issues #50
if (channel == NULL || strcmp(channel, "\0") == 0) {
pwm_cleanup(); pwm_cleanup();
} else {
if (!get_pwm_key(channel, key)) {
pwm_cleanup();
}
pwm_disable(key);
}
Py_RETURN_NONE; Py_RETURN_NONE;
} }
@ -52,6 +70,28 @@ static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
Py_RETURN_NONE; Py_RETURN_NONE;
} }
static int init_module(void)
{
clear_error_msg();
// If we make it here, we're good to go
if (DEBUG)
printf(" ** init_module: setup complete **\n");
module_setup = 1;
return 0;
}
// python function value = is_chip_pro
static PyObject *py_is_chip_pro(PyObject *self, PyObject *args)
{
PyObject *py_value;
py_value = Py_BuildValue("i", is_this_chippro());
return py_value;
}
// python function start(channel, duty_cycle, freq) // python function start(channel, duty_cycle, freq)
static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
@ -60,6 +100,7 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
float frequency = 2000.0; float frequency = 2000.0;
float duty_cycle = 0.0; float duty_cycle = 0.0;
int polarity = 0; int polarity = 0;
int allowed = -1;
static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL}; static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL};
clear_error_msg(); clear_error_msg();
@ -68,11 +109,30 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
if (!module_setup) {
init_module();
}
if (!get_pwm_key(channel, key)) { if (!get_pwm_key(channel, key)) {
PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name."); PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name.");
return NULL; return NULL;
} }
// Check to see if PWM is allowed on the hardware
// A 1 means we're good to go
allowed = pwm_allowed(key);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (duty_cycle < 0.0 || duty_cycle > 100.0) { if (duty_cycle < 0.0 || duty_cycle > 100.0) {
PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0"); PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0");
return NULL; return NULL;
@ -103,6 +163,7 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
{ {
char key[8]; char key[8];
char *channel; char *channel;
int allowed = -1;
clear_error_msg(); clear_error_msg();
@ -114,6 +175,21 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
return NULL; return NULL;
} }
// Check to see if PWM is allowed on the hardware
// A 1 means we're good to go
allowed = pwm_allowed(key);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (pwm_disable(key) < 0) { if (pwm_disable(key) < 0) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
@ -129,6 +205,7 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
{ {
char key[8]; char key[8];
char *channel; char *channel;
int allowed = -1;
float duty_cycle = 0.0; float duty_cycle = 0.0;
static char *kwlist[] = {"channel", "duty_cycle", NULL}; static char *kwlist[] = {"channel", "duty_cycle", NULL};
@ -147,6 +224,21 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
return NULL; return NULL;
} }
// Check to see if PWM is allowed on the hardware
// A 1 means we're good to go
allowed = pwm_allowed(key);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (pwm_set_duty_cycle(key, duty_cycle) == -1) { if (pwm_set_duty_cycle(key, duty_cycle) == -1) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
@ -162,6 +254,7 @@ static PyObject *py_set_pulse_width_ns(PyObject *self, PyObject *args, PyObject
{ {
char key[8]; char key[8];
char *channel; char *channel;
int allowed = -1;
unsigned long pulse_width_ns = 0.0; unsigned long pulse_width_ns = 0.0;
unsigned long period_ns; unsigned long period_ns;
static char *kwlist[] = {"channel", "pulse_width_ns", NULL}; static char *kwlist[] = {"channel", "pulse_width_ns", NULL};
@ -176,6 +269,21 @@ static PyObject *py_set_pulse_width_ns(PyObject *self, PyObject *args, PyObject
return NULL; return NULL;
} }
// Check to see if PWM is allowed on the hardware
// A 1 means we're good to go
allowed = pwm_allowed(key);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
// Get the period out of the data struct // Get the period out of the data struct
int rtn = pwm_get_period_ns(key, &period_ns); int rtn = pwm_get_period_ns(key, &period_ns);
if (rtn == -1) { if (rtn == -1) {
@ -203,6 +311,7 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
{ {
char key[8]; char key[8];
char *channel; char *channel;
int allowed = -1;
float frequency = 1.0; float frequency = 1.0;
static char *kwlist[] = {"channel", "frequency", NULL}; static char *kwlist[] = {"channel", "frequency", NULL};
@ -221,6 +330,21 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
// Check to see if PWM is allowed on the hardware
// A 1 means we're good to go
allowed = pwm_allowed(key);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (pwm_set_frequency(key, frequency) < 0) { if (pwm_set_frequency(key, frequency) < 0) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
@ -236,6 +360,7 @@ static PyObject *py_set_period_ns(PyObject *self, PyObject *args, PyObject *kwar
{ {
char key[8]; char key[8];
char *channel; char *channel;
int allowed = -1;
unsigned long period_ns = 2e6; unsigned long period_ns = 2e6;
static char *kwlist[] = {"channel", "period_ns", NULL}; static char *kwlist[] = {"channel", "period_ns", NULL};
@ -254,6 +379,21 @@ static PyObject *py_set_period_ns(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
// Check to see if PWM is allowed on the hardware
// A 1 means we're good to go
allowed = pwm_allowed(key);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "PWM %s not available on current Hardware", key);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (pwm_set_period_ns(key, period_ns) < 0) { if (pwm_set_period_ns(key, period_ns) < 0) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg()); snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
@ -273,8 +413,9 @@ PyMethodDef pwm_methods[] = {
{"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" }, {"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
{"set_period_ns", (PyCFunction)py_set_period_ns, METH_VARARGS, "Change the period\nperiod_ns - period in nanoseconds" }, {"set_period_ns", (PyCFunction)py_set_period_ns, METH_VARARGS, "Change the period\nperiod_ns - period in nanoseconds" },
{"set_pulse_width_ns", (PyCFunction)py_set_pulse_width_ns, METH_VARARGS, "Change the period\npulse_width_ns - pulse width in nanoseconds" }, {"set_pulse_width_ns", (PyCFunction)py_set_pulse_width_ns, METH_VARARGS, "Change the period\npulse_width_ns - pulse width in nanoseconds" },
{"cleanup", py_cleanup, METH_VARARGS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"}, {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting PWM channel(s) that have been used by this program to be disabled"},
{"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"},
{"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"},
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };

View File

@ -50,12 +50,36 @@ static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
// python function cleanup() // python function cleanup()
static PyObject *py_cleanup(PyObject *self, PyObject *args) static PyObject *py_cleanup(PyObject *self, PyObject *args)
{ {
// TODO: PER PIN CLEANUP LIKE EVERYTHING ELSE
// unexport the Servo // unexport the Servo
servo_cleanup(); servo_cleanup();
Py_RETURN_NONE; Py_RETURN_NONE;
} }
static int init_module(void)
{
clear_error_msg();
// If we make it here, we're good to go
if (DEBUG)
printf(" ** init_module: setup complete **\n");
module_setup = 1;
return 0;
}
// python function value = is_chip_pro()
static PyObject *py_is_chip_pro(PyObject *self, PyObject *args)
{
PyObject *py_value;
py_value = Py_BuildValue("i", is_this_chippro());
return py_value;
}
// python function start(channel, angle, range) // python function start(channel, angle, range)
static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
@ -64,6 +88,7 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
char *channel = NULL; char *channel = NULL;
float angle = 0.0; float angle = 0.0;
float range = 180.0; float range = 180.0;
int allowed = -1;
static char *kwlist[] = {"channel", "angle", "range", NULL}; static char *kwlist[] = {"channel", "angle", "range", NULL};
clear_error_msg(); clear_error_msg();
@ -73,6 +98,10 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
} }
ASSRT(channel != NULL); ASSRT(channel != NULL);
if (!module_setup) {
init_module();
}
if (!get_key(channel, key)) { if (!get_key(channel, key)) {
PyErr_SetString(PyExc_ValueError, "Invalid Servo key or name."); PyErr_SetString(PyExc_ValueError, "Invalid Servo key or name.");
return NULL; return NULL;
@ -86,6 +115,21 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (servo_start(key, angle, range) < 0) { if (servo_start(key, angle, range) < 0) {
printf("servo_start failed"); printf("servo_start failed");
char err[2000]; char err[2000];
@ -102,6 +146,7 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
{ {
int gpio; int gpio;
char key[8]; char key[8];
int allowed = -1;
char *channel; char *channel;
clear_error_msg(); clear_error_msg();
@ -122,18 +167,34 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
servo_disable(key); servo_disable(key);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python method SERVO.set_range(channel, duty_cycle) // python method SERVO.set_range(channel, range)
static PyObject *py_set_range(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_set_range(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char key[8]; char key[8];
char *channel; char *channel;
float range = 180.0; float range = 180.0;
int allowed = -1;
static char *kwlist[] = {"channel", "range", NULL}; static char *kwlist[] = {"channel", "range", NULL};
clear_error_msg(); clear_error_msg();
@ -159,6 +220,21 @@ static PyObject *py_set_range(PyObject *self, PyObject *args, PyObject *kwargs)
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (servo_set_range(key, range) == -1) { if (servo_set_range(key, range) == -1) {
PyErr_SetString(PyExc_RuntimeError, "You must start() the Servo channel first"); PyErr_SetString(PyExc_RuntimeError, "You must start() the Servo channel first");
return NULL; return NULL;
@ -167,13 +243,14 @@ static PyObject *py_set_range(PyObject *self, PyObject *args, PyObject *kwargs)
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python method SERVO.set_angle(channel, duty_cycle) // python method SERVO.set_angle(channel, angle)
static PyObject *py_set_angle(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_set_angle(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char key[8]; char key[8];
char *channel; char *channel;
float angle = 0.0; float angle = 0.0;
int allowed = -1;
static char *kwlist[] = {"channel", "angle", NULL}; static char *kwlist[] = {"channel", "angle", NULL};
clear_error_msg(); clear_error_msg();
@ -199,6 +276,21 @@ static PyObject *py_set_angle(PyObject *self, PyObject *args, PyObject *kwargs)
return NULL; return NULL;
} }
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (servo_set_angle(key, angle) == -1) { if (servo_set_angle(key, angle) == -1) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "Error setting servo angle on pin %s (%s)", key, get_error_msg()); snprintf(err, sizeof(err), "Error setting servo angle on pin %s (%s)", key, get_error_msg());
@ -218,6 +310,7 @@ PyMethodDef servo_methods[] = {
{"set_angle", (PyCFunction)py_set_angle, METH_VARARGS, "Change the servo angle\nangle - angle of the servo between +/-(range/2)" }, {"set_angle", (PyCFunction)py_set_angle, METH_VARARGS, "Change the servo angle\nangle - angle of the servo between +/-(range/2)" },
{"cleanup", (PyCFunction)py_cleanup, METH_VARARGS, "Clean up by resetting All or one Servo that have been used by this program."}, {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS, "Clean up by resetting All or one Servo that have been used by this program."},
{"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"},
{"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"},
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };

View File

@ -43,16 +43,56 @@ static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python function cleanup() // python function cleanup(channel)
static PyObject *py_cleanup(PyObject *self, PyObject *args) static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
// unexport the PWM char key[8];
char *channel;
static char *kwlist[] = {"channel", NULL};
clear_error_msg();
// Channel is optional
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel)) {
return NULL;
}
// The !channel fixes issues #50
if (channel == NULL || strcmp(channel, "\0") == 0) {
softpwm_cleanup(); softpwm_cleanup();
} else {
if (!get_key(channel, key)) {
softpwm_cleanup();
}
softpwm_disable(key);
}
Py_RETURN_NONE; Py_RETURN_NONE;
} }
// python function start(channel, duty_cycle, freq) static int init_module(void)
{
clear_error_msg();
// If we make it here, we're good to go
if (DEBUG)
printf(" ** init_module: setup complete **\n");
module_setup = 1;
return 0;
}
// python function value = is_chip_pro()
static PyObject *py_is_chip_pro(PyObject *self, PyObject *args)
{
PyObject *py_value;
py_value = Py_BuildValue("i", is_this_chippro());
return py_value;
}
// python function start(channel, duty_cycle, freq, polarity)
static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
char key[8]; char key[8];
@ -60,6 +100,8 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
float frequency = 2000.0; float frequency = 2000.0;
float duty_cycle = 0.0; float duty_cycle = 0.0;
int polarity = 0; int polarity = 0;
int gpio;
int allowed = -1;
static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL}; static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL};
clear_error_msg(); clear_error_msg();
@ -69,11 +111,34 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
} }
ASSRT(channel != NULL); ASSRT(channel != NULL);
if (!module_setup) {
init_module();
}
if (!get_key(channel, key)) { if (!get_key(channel, key)) {
PyErr_SetString(PyExc_ValueError, "Invalid SOFTPWM key or name."); PyErr_SetString(PyExc_ValueError, "Invalid SOFTPWM key or name.");
return NULL; return NULL;
} }
// check to ensure gpio is one of the allowed pins
// Not protecting the call as if the get_key() fails, we won't make it here
get_gpio_number(channel, &gpio);
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (duty_cycle < 0.0 || duty_cycle > 100.0) { if (duty_cycle < 0.0 || duty_cycle > 100.0) {
PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0"); PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0");
return NULL; return NULL;
@ -105,6 +170,8 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
{ {
char key[8]; char key[8];
char *channel; char *channel;
int gpio;
int allowed = -1;
clear_error_msg(); clear_error_msg();
@ -116,6 +183,25 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
return NULL; return NULL;
} }
// check to ensure gpio is one of the allowed pins
// Not protecting the call as if the get_key() fails, we won't make it here
get_gpio_number(channel, &gpio);
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
softpwm_disable(key); softpwm_disable(key);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -126,6 +212,8 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
{ {
char key[8]; char key[8];
char *channel; char *channel;
int gpio;
int allowed = -1;
float duty_cycle = 0.0; float duty_cycle = 0.0;
static char *kwlist[] = {"channel", "duty_cycle", NULL}; static char *kwlist[] = {"channel", "duty_cycle", NULL};
@ -144,6 +232,25 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
return NULL; return NULL;
} }
// check to ensure gpio is one of the allowed pins
// Not protecting the call as if the get_key() fails, we won't make it here
get_gpio_number(channel, &gpio);
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (softpwm_set_duty_cycle(key, duty_cycle) == -1) { if (softpwm_set_duty_cycle(key, duty_cycle) == -1) {
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first"); PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
return NULL; return NULL;
@ -157,6 +264,8 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
{ {
char key[8]; char key[8];
char *channel; char *channel;
int gpio;
int allowed = -1;
float frequency = 1.0; float frequency = 1.0;
static char *kwlist[] = {"channel", "frequency", NULL}; static char *kwlist[] = {"channel", "frequency", NULL};
@ -175,6 +284,25 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
return NULL; return NULL;
} }
// check to ensure gpio is one of the allowed pins
// Not protecting the call as if the get_key() fails, we won't make it here
get_gpio_number(channel, &gpio);
// Check to see if GPIO is allowed on the hardware
// A 1 means we're good to go
allowed = gpio_allowed(gpio);
if (allowed == -1) {
char err[2000];
snprintf(err, sizeof(err), "Error determining hardware. (%s)", get_error_msg());
PyErr_SetString(PyExc_ValueError, err);
return NULL;
} else if (allowed == 0) {
char err[2000];
snprintf(err, sizeof(err), "GPIO %d not available on current Hardware", gpio);
PyErr_SetString(PyExc_ValueError, err);
return NULL;
}
if (softpwm_set_frequency(key, frequency) == -1) { if (softpwm_set_frequency(key, frequency) == -1) {
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first"); PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
return NULL; return NULL;
@ -190,8 +318,9 @@ PyMethodDef pwm_methods[] = {
{"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the PWM channel. channel can be in the form of 'XIO-P0', or 'U14_13'"}, {"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the PWM channel. channel can be in the form of 'XIO-P0', or 'U14_13'"},
{"set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" }, {"set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" },
{"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" }, {"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
{"cleanup", (PyCFunction)py_cleanup, METH_VARARGS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"}, {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"},
{"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"},
{"is_chip_pro", py_is_chip_pro, METH_VARARGS, "Is hardware a CHIP Pro? Boolean False for normal CHIP/PocketCHIP (R8 SOC)"},
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };

View File

@ -0,0 +1,45 @@
#!/usr/bin/python
import CHIP_IO.SOFTPWM as PWM
import CHIP_IO.GPIO as GPIO
import CHIP_IO.OverlayManager as OM
import time
import datetime
if __name__ == "__main__":
# SETUP VARIABLES
PWMGPIO = "XIO-P7"
#PWMGPIO = "LCD-D4"
COUNT = 150
SLEEPTIME = 0.01
time.sleep(1)
# SETUP PWM
try:
print("PWM START")
#PWM.toggle_debug()
PWM.start(PWMGPIO, 50, 45, 1)
# UNCOMMENT FOR CRASH
print("PWM SET FREQUENCY")
PWM.set_frequency(PWMGPIO, 10)
# UNCOMMENT FOR CRASH
print("PWM SET DUTY CYCLE")
PWM.set_duty_cycle(PWMGPIO, 25)
#time.sleep(COUNT*SLEEPTIME + 1)
raw_input("PRESS ENTER WHEN DONE")
except:
raise
finally:
# CLEANUP
print("CLEANUP")
PWM.stop(PWMGPIO)
PWM.cleanup()
#OM.unload("PWM0")
#GPIO.cleanup()

14
test/test_lradc.py Normal file
View File

@ -0,0 +1,14 @@
import pytest
import CHIP_IO.LRADC as LRADC
class TestLRADC:
def test_scale_factor(self):
assert LRADC.get_scale_factor() == 31.25
def test_sample_rate_values(self):
assert LRADC.get_allowable_sample_rates() == (32.25, 62.5, 125, 250)
def test_set_sample_rate(self):
LRADC.set_sample_rate(32.25)
assert LRADC.get_sample_rate() == 32.25

View File

@ -4,12 +4,15 @@ import time
import CHIP_IO.PWM as PWM import CHIP_IO.PWM as PWM
import CHIP_IO.OverlayManager as OM import CHIP_IO.OverlayManager as OM
import CHIP_IO.Utilities as UT
def setup_module(module): def setup_module(module):
if not UT.is_chip_pro():
OM.load("PWM0") OM.load("PWM0")
def teardown_module(module): def teardown_module(module):
PWM.cleanup() PWM.cleanup()
if not UT.is_chip_pro():
OM.unload("PWM0") OM.unload("PWM0")
class TestPwmSetup: class TestPwmSetup:
@ -17,16 +20,6 @@ class TestPwmSetup:
def setup_method(self, test_method): def setup_method(self, test_method):
time.sleep(0.5) time.sleep(0.5)
#def teardown_method(self, test_method):
# PWM.cleanup()
#OM.unload("PWM0")
#def setup_module(self, module):
# OM.load("PWM0")
#def teardown_module(self, module):
# OM.unload("PWM0")
def test_start_pwm(self): def test_start_pwm(self):
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
@ -38,27 +31,25 @@ class TestPwmSetup:
assert int(duty) == 0 assert int(duty) == 0
assert int(period) == 500000 assert int(period) == 500000
@pytest.mark.xfail(reason="pwm cleanup is doing weirdness for this test")
def test_start_pwm_with_polarity_one(self): def test_start_pwm_with_polarity_one(self):
PWM.cleanup()
PWM.start("PWM0", 0, 2000, 1) PWM.start("PWM0", 0, 2000, 1)
pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' pwm_test = '/sys/class/pwm/pwmchip0/pwm0/'
#assert os.path.exists(pwm_test) == True
duty = open(pwm_test + 'duty_cycle').readline().strip() duty = open(pwm_test + 'duty_cycle').readline().strip()
period = open(pwm_test + 'period').readline().strip() period = open(pwm_test + 'period').readline().strip()
polarity = open(pwm_test + 'polarity').readline().strip() polarity = open(pwm_test + 'polarity').readline().strip()
assert int(duty) == 0 assert int(duty) == 0
assert int(period) == 500000 assert int(period) == 500000
assert str(polarity) == "inverted" assert str(polarity) == "inversed"
@pytest.mark.xfail(reason="pwm cleanup is doing weirdness for this test")
def test_start_pwm_with_polarity_default(self): def test_start_pwm_with_polarity_default(self):
PWM.cleanup()
PWM.start("PWM0", 0, 2000, 0) PWM.start("PWM0", 0, 2000, 0)
pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' pwm_test = '/sys/class/pwm/pwmchip0/pwm0/'
#assert os.path.exists(pwm_test) == True
duty = open(pwm_test + 'duty_cycle').readline().strip() duty = open(pwm_test + 'duty_cycle').readline().strip()
period = open(pwm_test + 'period').readline().strip() period = open(pwm_test + 'period').readline().strip()
polarity = open(pwm_test + 'polarity').readline().strip() polarity = open(pwm_test + 'polarity').readline().strip()
@ -66,13 +57,12 @@ class TestPwmSetup:
assert int(period) == 500000 assert int(period) == 500000
assert str(polarity) == "normal" assert str(polarity) == "normal"
@pytest.mark.xfail(reason="pwm cleanup is doing weirdness for this test")
def test_start_pwm_with_polarity_zero(self): def test_start_pwm_with_polarity_zero(self):
PWM.cleanup()
PWM.start("PWM0", 0, 2000, 0) PWM.start("PWM0", 0, 2000, 0)
pwm_test = '/sys/class/pwm/pwmchip0/pwm0/' pwm_test = '/sys/class/pwm/pwmchip0/pwm0/'
#assert os.path.exists(pwm_test) == True
duty = open(pwm_test + 'duty_cycle').readline().strip() duty = open(pwm_test + 'duty_cycle').readline().strip()
period = open(pwm_test + 'period').readline().strip() period = open(pwm_test + 'period').readline().strip()
polarity = open(pwm_test + 'polarity').readline().strip() polarity = open(pwm_test + 'polarity').readline().strip()
@ -90,11 +80,14 @@ class TestPwmSetup:
def test_pwm_start_valid_duty_cycle_min(self): def test_pwm_start_valid_duty_cycle_min(self):
#testing an exception isn't thrown #testing an exception isn't thrown
PWM.cleanup()
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
PWM.cleanup()
def test_pwm_start_valid_duty_cycle_max(self): def test_pwm_start_valid_duty_cycle_max(self):
#testing an exception isn't thrown #testing an exception isn't thrown
PWM.start("PWM0", 100) PWM.start("PWM0", 100)
PWM.cleanup()
def test_pwm_start_invalid_duty_cycle_high(self): def test_pwm_start_invalid_duty_cycle_high(self):
with pytest.raises(ValueError): with pytest.raises(ValueError):
@ -143,7 +136,8 @@ class TestPwmSetup:
assert int(period) == 500000 assert int(period) == 500000
def test_pwm_duty_cycle_non_setup_key(self): def test_pwm_duty_cycle_non_setup_key(self):
with pytest.raises(RuntimeError): with pytest.raises(ValueError):
PWM.cleanup()
PWM.set_duty_cycle("PWM0", 100) PWM.set_duty_cycle("PWM0", 100)
def test_pwm_duty_cycle_invalid_key(self): def test_pwm_duty_cycle_invalid_key(self):
@ -154,26 +148,31 @@ class TestPwmSetup:
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
with pytest.raises(ValueError): with pytest.raises(ValueError):
PWM.set_duty_cycle("PWM0", 101) PWM.set_duty_cycle("PWM0", 101)
PWM.cleanup()
def test_pwm_duty_cycle_invalid_value_negative(self): def test_pwm_duty_cycle_invalid_value_negative(self):
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
with pytest.raises(ValueError): with pytest.raises(ValueError):
PWM.set_duty_cycle("PWM0", -1) PWM.set_duty_cycle("PWM0", -1)
PWM.cleanup()
def test_pwm_duty_cycle_invalid_value_string(self): def test_pwm_duty_cycle_invalid_value_string(self):
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
with pytest.raises(TypeError): with pytest.raises(TypeError):
PWM.set_duty_cycle("PWM0", "a") PWM.set_duty_cycle("PWM0", "a")
PWM.cleanup()
def test_pwm_frequency_invalid_value_negative(self): def test_pwm_frequency_invalid_value_negative(self):
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
with pytest.raises(ValueError): with pytest.raises(ValueError):
PWM.set_frequency("PWM0", -1) PWM.set_frequency("PWM0", -1)
PWM.cleanup()
def test_pwm_frequency_invalid_value_string(self): def test_pwm_frequency_invalid_value_string(self):
PWM.start("PWM0", 0) PWM.start("PWM0", 0)
with pytest.raises(TypeError): with pytest.raises(TypeError):
PWM.set_frequency("PWM0", "11") PWM.set_frequency("PWM0", "11")
PWM.cleanup()
def test_pwm_freq_non_setup_key(self): def test_pwm_freq_non_setup_key(self):
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError):

11
test/test_utilities.py Normal file
View File

@ -0,0 +1,11 @@
import pytest
import CHIP_IO.Utilities as UT
class TestUtilities:
def test_invalid_set_1v8_with_string(self):
assert not UT.set_1v8_pin_voltage("yaystring")
def test_invalid_set_1v8_with_outofbounds_value(self):
assert not UT.set_1v8_pin_voltage(0.5)
assert not UT.set_1v8_pin_voltage(4.5)