mirror of
https://github.com/xtacocorex/CHIP_IO
synced 2025-07-20 12:53:22 +00:00
Compare commits
135 Commits
Author | SHA1 | Date | |
---|---|---|---|
84df4376f8 | |||
906beb0257 | |||
00cd5c09ad | |||
c87b0ca72a | |||
ff7bf2fa1c | |||
af9555fcdf | |||
e7db735a2f | |||
e3a077bf82 | |||
a0b2ac12a6 | |||
6af974c113 | |||
4670e44758 | |||
2247e9d234 | |||
ff91bcd0d1 | |||
35619e5baf | |||
1e3935c8ea | |||
e038fc9c89 | |||
5b016887fe | |||
aa76edb7b3 | |||
d84c3c03d7 | |||
c47fb197f5 | |||
a6111d8245 | |||
71923f5739 | |||
c9b0ae4229 | |||
5aef829dd1 | |||
3c3ec494dd | |||
bb5f0083e8 | |||
408bf60ffa | |||
310c4a9ae4 | |||
014dcb8a36 | |||
6e93fad1de | |||
41d4b84c56 | |||
024e5d5797 | |||
6ddd0e0b14 | |||
d4b1d8a41c | |||
2b48571ee3 | |||
38a34e7edf | |||
f32733bb07 | |||
4da0812acd | |||
dcd8ea6f40 | |||
29377cf24d | |||
f7bec3f891 | |||
48d9343dba | |||
bab94f7600 | |||
dab60b334d | |||
c3ead5d395 | |||
121ad398e4 | |||
c21c431b7b | |||
f66740b797 | |||
ca7d221b33 | |||
e179e52b5e | |||
fa3108544b | |||
c5dbede3c4 | |||
6bd2e61450 | |||
cd85e2b5eb | |||
6beacbb382 | |||
a498fc12bd | |||
2e2177da26 | |||
541d76f641 | |||
2b23e2d165 | |||
a839661c3b | |||
cb4e272a35 | |||
05b936ca1d | |||
3ff79d43e3 | |||
40381efa74 | |||
73ae207e16 | |||
eafcf0bf69 | |||
bf27e2feea | |||
8221016c10 | |||
bd7f667041 | |||
8c3dab1ecc | |||
962049299a | |||
10e7043269 | |||
3b2e334876 | |||
486cf73860 | |||
5723bf15b3 | |||
6972f352ae | |||
8ecec67bad | |||
d0ed4665aa | |||
1d641ecdff | |||
8241f54891 | |||
abbc4968c6 | |||
9a2e81f093 | |||
7cce06b472 | |||
7489fd21b4 | |||
87303b6083 | |||
8aa402fbd5 | |||
e82f62133a | |||
993ea29213 | |||
7d91bbc47e | |||
b12c0ad2fe | |||
5d8c0f6aaa | |||
4aaff04375 | |||
eeb98d468f | |||
51c38843d9 | |||
5aa08351c2 | |||
9d7fb634a3 | |||
3cd69cfe93 | |||
cf9916018b | |||
e0c65de9a8 | |||
794ce98ed2 | |||
617f562b1c | |||
89cbea038e | |||
82d6fef173 | |||
e2173f0235 | |||
30593306a3 | |||
a9902d1267 | |||
fcd5afcdc8 | |||
d66032ed93 | |||
9a83cf765a | |||
d95847eb5a | |||
12bc9dec67 | |||
29eb018e78 | |||
ee0e27cb22 | |||
c8e4323c27 | |||
1e3e801e60 | |||
40ae9a5cdc | |||
20b72490f2 | |||
7e83fa8435 | |||
c3448ec661 | |||
42e17edc4a | |||
b180fe1d6f | |||
a62a26dae0 | |||
0ed1cfb352 | |||
4f6acf4676 | |||
01347416ab | |||
e270080af8 | |||
44121ed5eb | |||
00140c2008 | |||
ee8445918e | |||
1c4168cf0d | |||
ea4a21235d | |||
bff65d346d | |||
a4dd1558f0 | |||
3d1ecb6b5e | |||
db4493322d |
183
CHANGELOG.rst
183
CHANGELOG.rst
@ -1,3 +1,186 @@
|
||||
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
|
||||
---
|
||||
* Software Servo code added
|
||||
- Only works on the LCD and CSI pins
|
||||
* Fixed cleanup() for the SOFTPWM and SERVO
|
||||
- The per pin cleanup for SOFTPWM doesn't work as stop() clears up the memory for the pin used
|
||||
- SERVO code was based on SOFTPWM, so it inherited this issue
|
||||
|
||||
0.3.5
|
||||
---
|
||||
* Merged in brettcvz's code to read a byte of data from the GPIO
|
||||
- Cleaned the code up and expanded it (in the low level C code) to read up to 32 bits of data
|
||||
- Presented 8 bit and 16 bits of data functions to the Python interface with brettcvz's read_byte() and my read_word()
|
||||
* I think I finally fixed the GPIO.cleanup() code one and for all
|
||||
|
||||
0.3.4.1
|
||||
---
|
||||
* Quick fix as I borked XIO setup as inputs with the latest change that enabled PUD
|
||||
|
||||
0.3.4
|
||||
---
|
||||
* Pull Up/Pull Down resistor setting now available for the R8 GPIO.
|
||||
* Some general cleanup
|
||||
|
||||
0.3.3
|
||||
----
|
||||
* Added Debug printing for all the capabilities with the toggle_debug() function
|
||||
* Added 2 functions from @streamnsight for PWM that allow for setting the period of the PWM and the Pulse Width, both in nanoseconds
|
||||
* Fixed the SPI2 overlay stuff by using the NTC overlay instead of mine.
|
||||
|
||||
0.3.2
|
||||
----
|
||||
* Fixing issue #53 to handle the return values of the set functions in pwm_enable.
|
||||
* Start of whole library debug for #55
|
||||
|
||||
0.3.1
|
||||
----
|
||||
* Fixing issue #50 where I broke GPIO.cleanup() and SOFTPWM.cleanup() when no input is specified.
|
||||
|
||||
0.3.0
|
||||
----
|
||||
* Added setmode() function for GPIO to maintain compatibility with Raspberry Pi scripts, this function literally does nothing
|
||||
* Added per pin cleanup functionality for GPIO and SoftPWM so you can unexport a pin without unexporting every pin
|
||||
* Updated README to make edge detection wording a little better and to add the per pin cleanup code
|
||||
* Version update since I blasted through 3 issues on github and feel like we need a nice bump to 0.3
|
||||
|
||||
0.2.7
|
||||
----
|
||||
* Fix to the Enable 1.8V Pin code as it wasn't working due to bit shifting isn't allowed on a float.
|
||||
* Updated README to denote the PocketCHIP Pin names better
|
||||
|
||||
0.2.6
|
||||
----
|
||||
* Fix to keep the GPIO value file open until the pin is unexported (issue #34)
|
||||
|
||||
0.2.5
|
||||
----
|
||||
* Updates to the pytest code for HWPWM and SoftPWM
|
||||
* Removed the i2c-1 load/unload support in OverlayManager as CHIP Kernel 4.4.13 has that bus brought back by default
|
||||
|
||||
0.2.4
|
||||
----
|
||||
* HW PWM Fixed
|
||||
- Start/Stop/Duty Cycle/Frequency settings work
|
||||
- Polarity cannot be changed, so don't bother setting it to 1 in start()
|
||||
* Added the unexport_all() function to Utilites
|
||||
|
||||
0.2.3
|
||||
----
|
||||
* LRADC Support
|
||||
* Added Utilities
|
||||
- Enable/Disable the 1.8V Pin
|
||||
- Change 1.8V Pin to output either 2.0V, 2.6V, or 3.3V
|
||||
(Current limited to 50mA)
|
||||
|
||||
0.2.2
|
||||
----
|
||||
* Fixes for Issue #16
|
||||
- Pass SoftPWM setup errors to Python layer (aninternetof)
|
||||
- Updated spwmtest.py to test for this issue
|
||||
|
||||
0.2.1
|
||||
----
|
||||
* Pull request #12 fixes:
|
||||
- Fixed indent in the i2c-1 dts
|
||||
- Removed import dependencies in the SPI and PWM overlays
|
||||
- Re-enabled building of the dtbo on setup.py install
|
||||
|
||||
0.2.0
|
||||
----
|
||||
* Added the ability to load DTB Overlays from within CHIP_IO
|
||||
- Support for PWM0, SPI2, and I2C-1 (which comes back as i2c-3 on the 4.4 CHIP
|
||||
- Support for a custom DTB Overlay
|
||||
* Fixes to the pwm unit test, all but 2 now pass :)
|
||||
|
||||
0.1.2
|
||||
----
|
||||
* SoftPWM Fix by aninternetof
|
||||
* Added a verification test for SoftPWM
|
||||
|
||||
0.1.1
|
||||
----
|
||||
* Some refactoring of the edge detection code, made it function better
|
||||
* Added Rising and Both edge detection tests to gptest.py
|
||||
- Small issue with both edge triggering double pumping on first callback hit
|
||||
|
||||
0.1.0
|
||||
----
|
||||
* Fixed edge detection code, will trigger proper for callbacks now
|
||||
|
||||
0.0.9
|
||||
----
|
||||
* Fixed SoftPWM segfault
|
||||
|
233
CHIP_IO/LRADC.py
Normal file
233
CHIP_IO/LRADC.py
Normal file
@ -0,0 +1,233 @@
|
||||
# Copyright (c) 2016 Robert Wolterman
|
||||
#
|
||||
# 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.
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
# Global Variables
|
||||
DEBUG = False
|
||||
DEVICE_EXIST = True
|
||||
|
||||
# Default Sample Rate Variables
|
||||
SAMPLE_RATE_32P25 = 32.25
|
||||
SAMPLE_RATE_62O5 = 62.5
|
||||
SAMPLE_RATE_125 = 125
|
||||
SAMPLE_RATE_250 = 250
|
||||
SAMPLE_RATES = []
|
||||
|
||||
# Scale Factor
|
||||
SCALE_FACTOR = 31.25
|
||||
|
||||
# File Locations
|
||||
LRADC_BASE_DEVICE_FILE = "/sys/bus/iio/devices/iio:device0"
|
||||
AVAILABLE_SAMPLE_RATE_FILE = "/sampling_frequency_available"
|
||||
SCALE_FACTOR_FILE = "/in_voltage_scale"
|
||||
CURRENT_SAMPLE_RATE_FILE = "/in_voltage_sampling_frequency"
|
||||
RAW_VOLTAGE_CHAN0_FILE = "/in_voltage0_raw"
|
||||
RAW_VOLTAGE_CHAN1_FILE = "/in_voltage1_raw"
|
||||
|
||||
def toggle_debug():
|
||||
global DEBUG
|
||||
if DEBUG:
|
||||
DEBUG = False
|
||||
print("debug disabled")
|
||||
else:
|
||||
DEBUG = True
|
||||
print("debug enabled")
|
||||
|
||||
def setup(rate=250):
|
||||
# First we determine if the device exists
|
||||
if not os.path.exists(LRADC_BASE_DEVICE_FILE):
|
||||
global DEVICE_EXIST
|
||||
DEVICE_EXIST = False
|
||||
raise Exception("LRADC Device does not exist")
|
||||
else:
|
||||
# Set the Sample Rate
|
||||
set_sample_rate(rate)
|
||||
|
||||
def get_device_exist():
|
||||
return DEVICE_EXIST
|
||||
|
||||
def get_scale_factor():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the data from the file
|
||||
f = open(LRADC_BASE_DEVICE_FILE+SCALE_FACTOR_FILE,"r")
|
||||
dat = f.readline()
|
||||
f.close()
|
||||
|
||||
# Set the Scale Factor
|
||||
global SCALE_FACTOR
|
||||
SCALE_FACTOR = float(dat.strip())
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_scale_factor: {0}".format(SCALE_FACTOR))
|
||||
|
||||
return SCALE_FACTOR
|
||||
|
||||
def get_allowable_sample_rates():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the data from the file
|
||||
f = open(LRADC_BASE_DEVICE_FILE+AVAILABLE_SAMPLE_RATE_FILE,"r")
|
||||
dat = f.readline()
|
||||
f.close()
|
||||
|
||||
global SAMPLE_RATES
|
||||
tmp = dat.strip().split(" ")
|
||||
for i in range(len(tmp)):
|
||||
if "." in tmp[i]:
|
||||
tmp[i] = float(tmp[i])
|
||||
else:
|
||||
tmp[i] = int(tmp[i])
|
||||
SAMPLE_RATES = tmp
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_allowable_sample_rates:")
|
||||
for rate in SAMPLE_RATES:
|
||||
print("{0}".format(rate))
|
||||
|
||||
return tuple(SAMPLE_RATES)
|
||||
|
||||
def set_sample_rate(rate):
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Check to see if the rates were gathered already
|
||||
global SAMPLE_RATES
|
||||
if SAMPLE_RATES == []:
|
||||
tmp = get_allowable_sample_rates()
|
||||
|
||||
# Range check the input rate
|
||||
if rate not in SAMPLE_RATES:
|
||||
raise ValueError("Input Rate an Acceptable Value")
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.set_sample_rate: {0}".format(rate))
|
||||
|
||||
# Write the rate
|
||||
f = open(LRADC_BASE_DEVICE_FILE+CURRENT_SAMPLE_RATE_FILE,"w")
|
||||
mystr = "%.2f" % rate
|
||||
f.write(mystr)
|
||||
f.close()
|
||||
|
||||
# Verify write went well
|
||||
crate = get_sample_rate()
|
||||
if crate != rate:
|
||||
raise Exception("Unable to write new Sampling Rate")
|
||||
|
||||
def get_sample_rate():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the data from the file
|
||||
f = open(LRADC_BASE_DEVICE_FILE+CURRENT_SAMPLE_RATE_FILE,"r")
|
||||
dat = f.read()
|
||||
f.close()
|
||||
|
||||
dat = dat.strip()
|
||||
if "." in dat:
|
||||
dat = float(dat)
|
||||
else:
|
||||
dat = int(dat)
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_sample_rate: {0}".format(dat))
|
||||
|
||||
return dat
|
||||
|
||||
def get_chan0_raw():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the data from the file
|
||||
f = open(LRADC_BASE_DEVICE_FILE+RAW_VOLTAGE_CHAN0_FILE,"r")
|
||||
dat = f.readline()
|
||||
f.close()
|
||||
|
||||
dat = float(dat.strip())
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_chan0_raw: {0}".format(dat))
|
||||
|
||||
return dat
|
||||
|
||||
def get_chan1_raw():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the data from the file
|
||||
f = open(LRADC_BASE_DEVICE_FILE+RAW_VOLTAGE_CHAN1_FILE,"r")
|
||||
dat = f.readline()
|
||||
f.close()
|
||||
|
||||
dat = float(dat.strip())
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_chan1_raw: {0}".format(dat))
|
||||
|
||||
return dat
|
||||
|
||||
def get_chan0():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the raw data first
|
||||
dat = get_chan0_raw()
|
||||
# Apply scale factor
|
||||
dat *= SCALE_FACTOR
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_chan0: {0}".format(dat))
|
||||
|
||||
return dat
|
||||
|
||||
def get_chan1():
|
||||
# If we do not have a device, lets throw an exception
|
||||
if not DEVICE_EXIST:
|
||||
raise Exception("LRADC Device does not exist")
|
||||
|
||||
# Get the raw data first
|
||||
dat = get_chan1_raw()
|
||||
# Apply scale factor
|
||||
dat *= SCALE_FACTOR
|
||||
|
||||
# Debug
|
||||
if DEBUG:
|
||||
print("lradc.get_chan1: {0}".format(dat))
|
||||
|
||||
return dat
|
||||
|
||||
|
216
CHIP_IO/OverlayManager.py
Normal file
216
CHIP_IO/OverlayManager.py
Normal file
@ -0,0 +1,216 @@
|
||||
# Copyright (c) 2016 Robert Wolterman
|
||||
#
|
||||
# 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.
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import sys
|
||||
from .Utilities import is_chip_pro
|
||||
|
||||
DEBUG = False
|
||||
|
||||
OVERLAYINSTALLPATH = "/lib/firmware/nextthingco/chip"
|
||||
OVERLAYCONFIGPATH = "/sys/kernel/config/device-tree/overlays"
|
||||
CUSTOMOVERLAYFILEPATH = ""
|
||||
|
||||
PWMSYSFSPATH = "/sys/class/pwm/pwmchip0"
|
||||
# USING THE BASE DIRECTORY FOR SPI AS THE DEVICE NUMBER CHANGES ON LOAD/UNLOAD
|
||||
SPI2SYSFSPATH = "/sys/class/spi_master/"
|
||||
|
||||
# LOADED VARIABLES
|
||||
# DO NOT MODIFY BY HAND WHEN USING
|
||||
# AS IT COULD BREAK FUNCTIONALITY
|
||||
_LOADED = {
|
||||
"SPI2" : False,
|
||||
"PWM0" : False,
|
||||
"CUST" : False
|
||||
}
|
||||
|
||||
_OVERLAYS = {
|
||||
"SPI2" : "sample-spi.dtbo",
|
||||
"PWM0" : "sample-pwm.dtbo",
|
||||
"CUST" : ""
|
||||
}
|
||||
|
||||
_FOLDERS = {
|
||||
"SPI2" : "chip-spi",
|
||||
"PWM0" : "chip-pwm",
|
||||
"CUST" : "chip-cust"
|
||||
}
|
||||
|
||||
def toggle_debug():
|
||||
global DEBUG
|
||||
if DEBUG:
|
||||
DEBUG = False
|
||||
print("debug disabled")
|
||||
else:
|
||||
DEBUG = True
|
||||
print("debug enabled")
|
||||
|
||||
def get_spi_loaded():
|
||||
"""
|
||||
get_spi_loaded - Returns True/False based upon if the spi2 Overlay is loaded
|
||||
"""
|
||||
global _LOADED
|
||||
return _LOADED["SPI2"]
|
||||
|
||||
def get_pwm_loaded():
|
||||
"""
|
||||
get_pwm_loaded - Returns True/False based upon if the pwm0 Overlay is loaded
|
||||
"""
|
||||
global _LOADED
|
||||
return _LOADED["PWM0"]
|
||||
|
||||
def get_custom_loaded():
|
||||
"""
|
||||
get_custom_loaded - Returns True/False based upon if a Custom Overlay is loaded
|
||||
"""
|
||||
global _LOADED
|
||||
return _LOADED["CUST"]
|
||||
|
||||
def _set_overlay_verify(name, overlay_path, config_path):
|
||||
"""
|
||||
_set_overlay_verify - Function to load the overlay and verify it was setup properly
|
||||
"""
|
||||
global DEBUG
|
||||
# VERIFY PATH IS NOT THERE
|
||||
if os.path.exists(config_path):
|
||||
print("Config path already exists! Not moving forward")
|
||||
print("config_path: {0}".format(config_path))
|
||||
return -1
|
||||
|
||||
# MAKE THE CONFIGURATION PATH
|
||||
os.makedirs(config_path)
|
||||
|
||||
# CAT THE OVERLAY INTO THE CONFIG FILESYSTEM
|
||||
with open(config_path + "/dtbo", 'wb') as outfile:
|
||||
with open(overlay_path, 'rb') as infile:
|
||||
shutil.copyfileobj(infile, outfile)
|
||||
|
||||
# SLEEP TO ENABLE THE KERNEL TO DO ITS JOB
|
||||
time.sleep(0.2)
|
||||
|
||||
# VERIFY
|
||||
if name == "CUST":
|
||||
# BLINDLY ACCEPT THAT IT LOADED
|
||||
return 0
|
||||
elif name == "PWM0":
|
||||
if os.path.exists(PWMSYSFSPATH):
|
||||
if DEBUG:
|
||||
print("PWM IS LOADED!")
|
||||
return 0
|
||||
else:
|
||||
if DEBUG:
|
||||
print("ERROR LOAIDNG PWM0")
|
||||
return 1
|
||||
elif name == "SPI2":
|
||||
if os.listdir(SPI2SYSFSPATH) != "":
|
||||
if DEBUG:
|
||||
print("SPI2 IS LOADED!")
|
||||
return 0
|
||||
else:
|
||||
if DEBUG:
|
||||
print("ERROR LOADING SPI2")
|
||||
return 0
|
||||
|
||||
def load(overlay, path=""):
|
||||
"""
|
||||
load - Load a DTB Overlay
|
||||
|
||||
Inputs:
|
||||
overlay - Overlay Key: SPI2, PWM0, CUST
|
||||
path - Full Path to where the custom overlay is stored
|
||||
|
||||
Returns:
|
||||
0 - Successful Load
|
||||
1 - Unsuccessful Load
|
||||
2 - Overlay was previously set
|
||||
"""
|
||||
global DEBUG
|
||||
global _LOADED
|
||||
if DEBUG:
|
||||
print("LOAD OVERLAY: {0} @ {1}".format(overlay,path))
|
||||
# SEE IF OUR OVERLAY NAME IS IN THE KEYS
|
||||
if overlay.upper() in _OVERLAYS.keys():
|
||||
cpath = OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()]
|
||||
if DEBUG:
|
||||
print("VALID OVERLAY")
|
||||
print("CONFIG PATH: {0}".format(cpath))
|
||||
# CHECK TO SEE IF WE HAVE A PATH FOR CUSTOM OVERLAY
|
||||
if overlay.upper() == "CUST" and path == "":
|
||||
raise ValueError("Path must be specified for Custom Overlay Choice")
|
||||
elif overlay.upper() == "CUST" and _LOADED[overlay.upper()]:
|
||||
print("Custom Overlay already loaded")
|
||||
return 2
|
||||
elif overlay.upper() == "CUST" and not os.path.exists(path):
|
||||
print("Custom Overlay path does not exist")
|
||||
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
|
||||
if overlay.upper() != "CUST":
|
||||
opath = OVERLAYINSTALLPATH
|
||||
opath += "/" + _OVERLAYS[overlay.upper()]
|
||||
else:
|
||||
opath = path
|
||||
if DEBUG:
|
||||
print("OVERLAY PATH: {0}".format(opath))
|
||||
|
||||
if overlay.upper() == "PWM0" and _LOADED[overlay.upper()]:
|
||||
print("PWM0 Overlay already loaded")
|
||||
return 2
|
||||
|
||||
if overlay.upper() == "SPI2" and _LOADED[overlay.upper()]:
|
||||
print("SPI2 Overlay already loaded")
|
||||
return 2
|
||||
|
||||
# LOAD THE OVERLAY
|
||||
errc = _set_overlay_verify(overlay.upper(), opath, cpath)
|
||||
if DEBUG:
|
||||
print("_SET_OVERLAY_VERIFY ERRC: {0}".format(errc))
|
||||
if errc == 0:
|
||||
_LOADED[overlay.upper()] = True
|
||||
|
||||
else:
|
||||
raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST")
|
||||
|
||||
def unload(overlay):
|
||||
global DEBUG
|
||||
global _LOADED
|
||||
if DEBUG:
|
||||
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
|
||||
if overlay.upper() in _OVERLAYS.keys():
|
||||
# BRUTE FORCE REMOVE AS THE DIRECTORY CONTAINS FILES
|
||||
os.system('rmdir \"{}\"'.format(OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()]))
|
||||
_LOADED[overlay.upper()] = False
|
||||
else:
|
||||
raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST")
|
||||
|
||||
|
144
CHIP_IO/Utilities.py
Normal file
144
CHIP_IO/Utilities.py
Normal file
@ -0,0 +1,144 @@
|
||||
# Copyright (c) 2016 Robert Wolterman
|
||||
#
|
||||
# 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.
|
||||
|
||||
# CHIP_IO Utilities
|
||||
# Random functions to enable fun stuff on the CHIP!
|
||||
|
||||
# Credit goes to nonokuono (https://bbs.nextthing.co/users/nonokunono)
|
||||
# for gathering the i2cset commands from the AXP-209 datasheet for 2.0, 2.6, and 3.3V output
|
||||
# and for figuring out the ADC setup on the AXP-209
|
||||
|
||||
import subprocess
|
||||
import glob
|
||||
import re
|
||||
|
||||
# Global Variables
|
||||
DEBUG = False
|
||||
|
||||
def toggle_debug():
|
||||
global DEBUG
|
||||
if DEBUG:
|
||||
DEBUG = False
|
||||
print("debug disabled")
|
||||
else:
|
||||
DEBUG = True
|
||||
print("debug enabled")
|
||||
|
||||
# Set the 1.8V-pin on the CHIP U13-header to given voltage
|
||||
# Return False on error
|
||||
def set_1v8_pin_voltage(voltage):
|
||||
if not is_chip_pro():
|
||||
if not isinstance(voltage, int) and not isinstance(voltage, float):
|
||||
return False
|
||||
if voltage < 1.8 or voltage > 3.3:
|
||||
return False
|
||||
if DEBUG:
|
||||
print("Setting 1.8V Pin voltage: {0}".format(voltage))
|
||||
voltage=int(round((voltage - 1.8) / 0.1)) << 4
|
||||
if subprocess.call(["/usr/sbin/i2cset", "-f", "-y" ,"0", "0x34", "0x90", "0x03"]):
|
||||
if DEBUG:
|
||||
print("Pin enable command failed")
|
||||
return False
|
||||
if subprocess.call(["/usr/sbin/i2cset", "-f", "-y", "0", "0x34", "0x91", str(voltage)]):
|
||||
if DEBUG:
|
||||
print("Pin set voltage command failed")
|
||||
return False
|
||||
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
|
||||
# Return False on error
|
||||
def get_1v8_pin_voltage():
|
||||
if not is_chip_pro():
|
||||
p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x90"], stdout=subprocess.PIPE)
|
||||
output=p.communicate()[0].decode("utf-8").strip()
|
||||
#Not configured as an output
|
||||
if output != "0x03":
|
||||
if DEBUG:
|
||||
print("1.8V Pin is currently disabled")
|
||||
return False
|
||||
p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x91"], stdout=subprocess.PIPE)
|
||||
output=p.communicate()[0].decode("utf-8").strip()
|
||||
voltage=round((int(output, 16) >> 4) * 0.1 + 1.8, 1)
|
||||
if DEBUG:
|
||||
print("Current 1.8V Pin voltage: {0}".format(voltage))
|
||||
return voltage
|
||||
else:
|
||||
print("Get 1.8V Pin Voltage not supported on the CHIP Pro")
|
||||
|
||||
# Enable 1.8V Pin on CHIP U13 Header
|
||||
def enable_1v8_pin():
|
||||
if not is_chip_pro():
|
||||
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
|
||||
def disable_1v8_pin():
|
||||
|
||||
if not is_chip_pro():
|
||||
if DEBUG:
|
||||
print("Disabling the 1.8V Pin")
|
||||
# CANNOT USE I2C LIB AS WE NEED TO FORCE THE COMMAND DUE TO THE KERNEL OWNING THE DEVICE
|
||||
# First we have to write 0x05 to AXP-209 Register 0x91
|
||||
subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x91 0x05', shell=True)
|
||||
# Then we have to write 0x07 to AXP-209 Register 0x90
|
||||
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
|
||||
def unexport_all():
|
||||
if DEBUG:
|
||||
print("Unexporting all the pins")
|
||||
gpios = glob.glob("/sys/class/gpio/gpio[0-9]*")
|
||||
for g in gpios:
|
||||
tmp = g.split("/")
|
||||
gpio = tmp[4]
|
||||
num = re.sub("[a-z]","",gpio)
|
||||
cmd = "echo " + num + " > /sys/class/gpio/unexport"
|
||||
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
|
4
MANIFEST.in
Normal file
4
MANIFEST.in
Normal file
@ -0,0 +1,4 @@
|
||||
include distribute_setup.py
|
||||
include README.rst
|
||||
include CHANGELOG.rst
|
||||
recursive-include source *.h
|
64
Makefile
64
Makefile
@ -1,19 +1,67 @@
|
||||
time:
|
||||
/usr/bin/ntpdate -b -s -u pool.ntp.org
|
||||
# PyPi Packaging
|
||||
package: clean
|
||||
@echo " ** PACKAGING FOR PYPI **"
|
||||
python setup.py sdist bdist_wheel
|
||||
python3 setup.py bdist_wheel
|
||||
|
||||
publish: clean
|
||||
python setup.py sdist upload
|
||||
# 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/*
|
||||
|
||||
# Clean all the things
|
||||
clean:
|
||||
@echo " ** CLEANING CHIP_IO **"
|
||||
rm -rf CHIP_IO.* build dist
|
||||
rm -f *.pyo
|
||||
rm -f *.pyo *.pyc
|
||||
rm -f *.egg
|
||||
rm -f overlays/*.pyo overlays/*.pyc
|
||||
tests:
|
||||
py.test
|
||||
rm -rf __pycache__
|
||||
rm -rf test/__pycache__/
|
||||
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:
|
||||
@echo " ** BUILDING CHIP_IO: PYTHON 2 **"
|
||||
python setup.py build --force
|
||||
|
||||
# Install all the things
|
||||
install: build
|
||||
@echo " ** INSTALLING CHIP_IO: PYTHON 2 **"
|
||||
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
|
||||
|
557
README.rst
557
README.rst
@ -2,134 +2,182 @@ CHIP_IO
|
||||
============================
|
||||
A CHIP GPIO library
|
||||
|
||||
Manual::
|
||||
Debian File Installation:
|
||||
|
||||
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::
|
||||
|
||||
sudo ntpdate pool.ntp.org
|
||||
sudo apt-get update
|
||||
sudo apt-get install git build-essential python-dev python-pip -y
|
||||
sudo apt-get install git build-essential python-dev python-pip flex bison chip-dt-overlays -y
|
||||
git clone git://github.com/xtacocorex/CHIP_IO.git
|
||||
cd CHIP_IO
|
||||
sudo python setup.py install
|
||||
cd ..
|
||||
sudo rm -rf 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
|
||||
git clone git://github.com/xtacocorex/CHIP_IO.git
|
||||
cd CHIP_IO
|
||||
sudo python3 setup.py install
|
||||
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**
|
||||
|
||||
Using the library is very similar to the excellent RPi.GPIO library used on the Raspberry Pi. Below are some examples.
|
||||
|
||||
All scripts that require GPIO and PWM (HW and/or SW) access need to be run with super user permissions!
|
||||
All scripts that require GPIO, PWM (HW and/or SW), and Overlay Manager need to be run with super user permissions!
|
||||
|
||||
**Allowable Pin Names for the Library**
|
||||
|
||||
The following "table" is the allowable pin names that are able to be used by the library.
|
||||
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.
|
||||
|
||||
+-----------+-------------+--------+
|
||||
| Name | Alt Name | Key |
|
||||
+-----------+-------------+--------+
|
||||
| TWI1-SDA | KPD-I2C-SDA | U13_9 |
|
||||
+-----------+-------------+--------+
|
||||
| TWI1-SCK | KPD-I2C-SCL | U13_11 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D2 | LCD-D2 | U13_17 |
|
||||
+-----------+-------------+--------+
|
||||
| PWM0 | PWM0 | U13_18 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D4 | LCD-D4 | U13_19 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D3 | LCD-D3 | U13_20 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D6 | LCD-D6 | U13_21 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D5 | LCD-D5 | U13_22 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D10 | LCD-D10 | U13_23 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D7 | LCD-D7 | U13_24 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D12 | LCD-D12 | U13_25 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D11 | LCD-D11 | U13_26 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D14 | LCD-D14 | U13_27 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D13 | LCD-D13 | U13_28 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D18 | LCD-D18 | U13_29 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D15 | LCD-D15 | U13_30 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D20 | LCD-D20 | U13_31 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D19 | LCD-D19 | U13_32 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D22 | LCD-D22 | U13_33 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D21 | LCD-D21 | U13_34 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-CLK | LCD-CLK | U13_35 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-D23 | LCD-D23 | U13_36 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-VSYNC | LCD-VSYNC | U13_37 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-HSYNC | LCD-HSYNC | U13_38 |
|
||||
+-----------+-------------+--------+
|
||||
| LCD-DE | LCD-DE | U13_40 |
|
||||
+-----------+-------------+--------+
|
||||
| UART1-TX | UART-TX | U14_3 |
|
||||
+-----------+-------------+--------+
|
||||
| UART1-RX | UART-RX | U14_5 |
|
||||
+-----------+-------------+--------+
|
||||
| LRADC | ADC | U14_11 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P0 | XIO-P0 | U14_13 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P1 | XIO-P1 | U14_14 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P2 | GPIO1 | U14_15 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P3 | GPIO2 | U14_16 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P4 | GPIO3 | U14_17 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P5 | GPIO4 | U14_18 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P6 | GPIO5 | U14_19 |
|
||||
+-----------+-------------+--------+
|
||||
| XIO-P7 | GPIO6 | U14_20 |
|
||||
+-----------+-------------+--------+
|
||||
| AP-EINT1 | KPD-INT | U14_23 |
|
||||
+-----------+-------------+--------+
|
||||
| AP-EINT3 | AP-INT3 | U14_24 |
|
||||
+-----------+-------------+--------+
|
||||
| TWI2-SDA | I2C-SDA | U14_25 |
|
||||
+-----------+-------------+--------+
|
||||
| TWI2-SCK | I2C-SCL | U14_26 |
|
||||
+-----------+-------------+--------+
|
||||
| CSIPCK | SPI-SEL | U14_27 |
|
||||
+-----------+-------------+--------+
|
||||
| CSICK | SPI-CLK | U14_28 |
|
||||
+-----------+-------------+--------+
|
||||
| CSIHSYNC | SPI-MOSI | U14_29 |
|
||||
+-----------+-------------+--------+
|
||||
| CSIVSYNC | SPI-MISO | U14_30 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID0 | CSID0 | U14_31 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID1 | CSID1 | U14_32 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID2 | CSID2 | U14_33 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID3 | CSID3 | U14_34 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID4 | CSID4 | U14_35 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID5 | CSID5 | U14_36 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID6 | CSID6 | U14_37 |
|
||||
+-----------+-------------+--------+
|
||||
| CSID7 | CSID7 | U14_38 |
|
||||
+-----------+-------------+--------+
|
||||
+------------------+--------------------------+----------------+-----------------+-----------------+
|
||||
| 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 |
|
||||
+------------------+--------------------------+----------------+-----------------+-----------------+
|
||||
|
||||
**GPIO Setup**
|
||||
|
||||
@ -146,6 +194,20 @@ You can also refer to the bin based upon its alternate name::
|
||||
|
||||
GPIO.setup("GPIO1", GPIO.IN)
|
||||
|
||||
**GPIO Miscellaneous**
|
||||
|
||||
Debug can be enabled/disabled by the following command::
|
||||
|
||||
# Enable 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**
|
||||
|
||||
Setup the pin for output, and write GPIO.HIGH or GPIO.LOW. Or you can use 1 or 0.::
|
||||
@ -161,17 +223,47 @@ Inputs work similarly to outputs.::
|
||||
import CHIP_IO.GPIO as GPIO
|
||||
GPIO.setup("CSID0", GPIO.IN)
|
||||
|
||||
Other options when setting up pins::
|
||||
|
||||
# Specify pull up/pull down settings on a pin
|
||||
GPIO.setup("CSID0", GPIO.IN, pull_up_down=GPIO.PUD_UP)
|
||||
|
||||
# Specify initial value for an output
|
||||
GPIO.setup("CSID0", GPIO.OUT, initial=1)
|
||||
|
||||
Pull Up/Down values are only for pins that are provided by the R8, the XIO are not capable of this. The allowable values are: PUD_OFF, PUD_UP, and PUD_DOWN.
|
||||
|
||||
Polling inputs::
|
||||
|
||||
if GPIO.input("CSID0"):
|
||||
print("HIGH")
|
||||
print("HIGH")
|
||||
else:
|
||||
print("LOW")
|
||||
print("LOW")
|
||||
|
||||
Read lots of data::
|
||||
|
||||
# Get 8 bits of data in one shot
|
||||
mybyte = GPIO.read_byte("LCD-D3")
|
||||
|
||||
# Get 16 bits of data in one shot
|
||||
myword = GPIO.read_word("XIO-P4")
|
||||
|
||||
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.
|
||||
|
||||
Waiting for an edge (GPIO.RISING, GPIO.FALLING, or GPIO.BOTH::
|
||||
|
||||
This only works for the AP-EINT1, AP-EINT3, and XPO Pins on the CHIP
|
||||
|
||||
GPIO.wait_for_edge(channel, GPIO.RISING)
|
||||
|
||||
Detecting events::
|
||||
@ -179,68 +271,259 @@ Detecting events::
|
||||
GPIO.setup("XIO-P0", GPIO.IN)
|
||||
GPIO.add_event_detect("XIO-P0", GPIO.FALLING)
|
||||
#your amazing code here
|
||||
|
||||
#detect wherever:
|
||||
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. 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):
|
||||
print("we hit the edge we want")
|
||||
|
||||
GPIO.setup("GPIO3", GPIO.IN)
|
||||
|
||||
# Add Event Detect and Callback Separately for Falling Edge
|
||||
GPIO.add_event_detect("GPIO3", GPIO.FALLING)
|
||||
GPIO.add_event_callback("GPIO3", mycallback)
|
||||
|
||||
# Add Event Detect and Callback Separately for Rising Edge
|
||||
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")
|
||||
|
||||
# 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**
|
||||
|
||||
To clean up the GPIO when done, do the following::
|
||||
|
||||
# Clean up every exported GPIO Pin
|
||||
GPIO.cleanup()
|
||||
|
||||
# Clean up a single pin (keeping everything else intact)
|
||||
GPIO.cleanup("XIO-P0")
|
||||
|
||||
**PWM**::
|
||||
|
||||
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
|
||||
# Determine hardware
|
||||
# 0 For CHIP
|
||||
# 1 For CHIP Pro
|
||||
PWM.is_chip_pro()
|
||||
|
||||
# Enable/Disable Debug
|
||||
PWM.toggle_debug()
|
||||
|
||||
#PWM.start(channel, duty, freq=2000, polarity=0)
|
||||
#duty values are valid 0 (off) to 100 (on)
|
||||
PWM.start("PWM0", 50)
|
||||
PWM.set_duty_cycle("PWM0", 25.5)
|
||||
PWM.set_frequency("PWM0", 10)
|
||||
|
||||
|
||||
# To stop PWM
|
||||
PWM.stop("PWM0")
|
||||
PWM.cleanup()
|
||||
|
||||
#set polarity to 1 on start:
|
||||
|
||||
#For specific polarity: this example sets polarity to 1 on start:
|
||||
PWM.start("PWM0", 50, 2000, 1)
|
||||
|
||||
**SOFTPWM**::
|
||||
|
||||
import CHIP_IO.SOFTPWM as PWM
|
||||
#PWM.start(channel, duty, freq=2000, polarity=0)
|
||||
import CHIP_IO.SOFTPWM as SPWM
|
||||
# Determine hardware
|
||||
# 0 For CHIP
|
||||
# 1 For CHIP Pro
|
||||
SPWM.is_chip_pro()
|
||||
|
||||
# Enable/Disable Debug
|
||||
SPWM.toggle_debug()
|
||||
|
||||
#SPWM.start(channel, duty, freq=2000, polarity=0)
|
||||
#duty values are valid 0 (off) to 100 (on)
|
||||
#you can choose any pin
|
||||
PWM.start("XIO-P7", 50)
|
||||
PWM.set_duty_cycle("XIO-P7", 25.5)
|
||||
PWM.set_frequency("XIO-P7", 10)
|
||||
|
||||
PWM.stop("XIO-P7")
|
||||
PWM.cleanup()
|
||||
|
||||
#set polarity to 1 on start:
|
||||
PWM.start("XIO-P7", 50, 2000, 1)
|
||||
SPWM.start("XIO-P7", 50)
|
||||
SPWM.set_duty_cycle("XIO-P7", 25.5)
|
||||
SPWM.set_frequency("XIO-P7", 10)
|
||||
|
||||
# To Stop SPWM
|
||||
SPWM.stop("XIO-P7")
|
||||
|
||||
# Cleanup
|
||||
SPWM.cleanup()
|
||||
|
||||
#For specific polarity: this example sets polarity to 1 on start:
|
||||
SPWM.start("XIO-P7", 50, 2000, 1)
|
||||
|
||||
Use SOFTPWM at low speeds (hundreds of Hz) for the best results. Do not use for anything that needs high precision or reliability.
|
||||
|
||||
**ADC**::
|
||||
If using SOFTPWM and PWM at the same time, import CHIP_IO.SOFTPWM as SPWM or something different than PWM as to not confuse the library.
|
||||
|
||||
Not Implemented yet
|
||||
**SERVO**::
|
||||
|
||||
import CHIP_IO.SERVO as SERVO
|
||||
# Determine hardware
|
||||
# 0 For CHIP
|
||||
# 1 For CHIP Pro
|
||||
SERVO.is_chip_pro()
|
||||
|
||||
# Enable/Disable Debug
|
||||
SERVO.toggle_debug()
|
||||
|
||||
#SPWM.start(channel, angle=0, range=180)
|
||||
#angle values are between +/- range/2)
|
||||
#you can choose any pin except the XIO's
|
||||
SERVO.start("CSID4", 50)
|
||||
SERVO.set_angle("CSID4", 25.5)
|
||||
SERVO.set_range("CSID4", 90)
|
||||
|
||||
# To Stop Servo
|
||||
SERVO.stop("CSID4")
|
||||
|
||||
# Cleanup
|
||||
SERVO.cleanup()
|
||||
|
||||
The Software Servo control only works on the LCD and CSI pins. The XIO is too slow to control.
|
||||
|
||||
**LRADC**::
|
||||
|
||||
The LRADC was enabled in the 4.4.13-ntc-mlc. This is a 6 bit ADC that is 2 Volt tolerant.
|
||||
Sample code below details how to talk to the LRADC.::
|
||||
|
||||
import CHIP_IO.LRADC as ADC
|
||||
# Enable/Disable Debug
|
||||
ADC.toggle_debug()
|
||||
|
||||
# Check to see if the LRADC Device exists
|
||||
# Returns True/False
|
||||
ADC.get_device_exists()
|
||||
|
||||
# Setup the LRADC
|
||||
# Specify a sampling rate if needed
|
||||
ADC.setup(rate)
|
||||
|
||||
# Get the Scale Factor
|
||||
factor = ADC.get_scale_factor()
|
||||
|
||||
# Get the allowable Sampling Rates
|
||||
sampleratestuple = ADC.get_allowable_sample_rates()
|
||||
|
||||
# Set the sampling rate
|
||||
ADC.set_sample_rate(rate)
|
||||
|
||||
# Get the current sampling rate
|
||||
currentrate = ADC.get_sample_rate()
|
||||
|
||||
# Get the Raw Channel 0 or 1 data
|
||||
raw = ADC.get_chan0_raw()
|
||||
raw = ADC.get_chan1_raw()
|
||||
|
||||
# Get the factored ADC Channel data
|
||||
fulldata = ADC.get_chan0()
|
||||
fulldata = ADC.get_chan1()
|
||||
|
||||
**SPI**::
|
||||
|
||||
SPI requires a DTB Overlay to access. CHIP_IO does not contain any SPI specific code as the Python spidev module works when it can see the SPI bus.
|
||||
|
||||
**Overlay Manager**::
|
||||
|
||||
The Overlay Manager enables you to quickly load simple Device Tree Overlays. The options for loading are:
|
||||
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 without PWM0, but you cannot have SPI2 loaded twice.
|
||||
::
|
||||
import CHIP_IO.OverlayManager as OM
|
||||
# The toggle_debug() function turns on/off debug printing
|
||||
OM.toggle_debug()
|
||||
|
||||
# To load an overlay, feed in the name to load()
|
||||
OM.load("PWM0")
|
||||
|
||||
# To verify the overlay was properly loaded, the get_ functions return booleans
|
||||
OM.get_pwm_loaded()
|
||||
OM.get_spi_loaded()
|
||||
|
||||
# To unload an overlay, feed in the name to unload()
|
||||
OM.unload("PWM0")
|
||||
|
||||
To use a custom overlay, you must build and compile it properly per the DIP Docs: http://docs.getchip.com/dip.html#development-by-example
|
||||
There is no verification that the Custom Overlay is setup properly, it's fire and forget
|
||||
::
|
||||
import CHIP_IO.OverlayManager as OM
|
||||
# The full path to the dtbo file needs to be specified
|
||||
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
|
||||
OM.get_custom_loaded()
|
||||
|
||||
# To unload, just call unload()
|
||||
OM.unload("CUST")
|
||||
|
||||
**OverlayManager requires a 4.4 kernel with the CONFIG_OF_CONFIGFS option enabled in the kernel config.**
|
||||
|
||||
**Utilties**::
|
||||
|
||||
CHIP_IO now supports the ability to enable and disable the 1.8V port on U13. This voltage rail isn't enabled during boot.
|
||||
|
||||
To use the utilities, here is sample code::
|
||||
|
||||
import CHIP_IO.Utilities as UT
|
||||
# Enable/Disable Debug
|
||||
UT.toggle_debug()
|
||||
|
||||
# Enable 1.8V Output
|
||||
UT.enable_1v8_pin()
|
||||
|
||||
# Set 2.0V Output
|
||||
UT.set_1v8_pin_voltage(2.0)
|
||||
|
||||
# Set 2.6V Output
|
||||
UT.set_1v8_pin_voltage(2.6)
|
||||
|
||||
# Set 3.3V Output
|
||||
UT.set_1v8_pin_voltage(3.3)
|
||||
|
||||
# Disable 1.8V Output
|
||||
UT.disable_1v8_pin()
|
||||
|
||||
# Get currently-configured voltage (returns False if the pin is not enabled as output)
|
||||
UT.get_1v8_pin_voltage()
|
||||
|
||||
# Unexport Everything
|
||||
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**
|
||||
|
||||
Install py.test to run the tests. You'll also need the python compiler package for py.test.::
|
||||
|
||||
# Python 2.7
|
||||
sudo apt-get install python-pytest
|
||||
# Python 3
|
||||
sudo apt-get install python3-pytest
|
||||
|
||||
Execute the following in the root of the project::
|
||||
To run the tests, do the following.::
|
||||
|
||||
sudo py.test
|
||||
# If only one version of Python is installed
|
||||
# Python 2
|
||||
sudo make pytest2
|
||||
# Python 3
|
||||
sudo make pytest3
|
||||
# If more than one version of Python, run through both
|
||||
sudo make test
|
||||
|
||||
**Credits**
|
||||
|
||||
|
108
debian/changelog
vendored
Normal file
108
debian/changelog
vendored
Normal 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
1
debian/compat
vendored
Normal file
@ -0,0 +1 @@
|
||||
9
|
23
debian/control
vendored
Normal file
23
debian/control
vendored
Normal 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
2
debian/files
vendored
Normal 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
9
debian/rules
vendored
Executable 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
1
debian/source/format
vendored
Normal file
@ -0,0 +1 @@
|
||||
3.0 (quilt)
|
1
docs/_config.yml
Normal file
1
docs/_config.yml
Normal file
@ -0,0 +1 @@
|
||||
theme: jekyll-theme-minimal
|
354
docs/gpio.md
Normal file
354
docs/gpio.md
Normal 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
75
docs/index.md
Normal 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
200
docs/lradc.md
Normal 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
117
docs/overlaymanager.md
Normal 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
172
docs/pwm.md
Normal 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
131
docs/servo.md
Normal 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
132
docs/softpwm.md
Normal 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
132
docs/utilities.md
Normal 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)
|
6
setup.cfg
Normal file
6
setup.cfg
Normal file
@ -0,0 +1,6 @@
|
||||
[bdist_wheel]
|
||||
universal = 1
|
||||
|
||||
[metadata]
|
||||
license_file = LICENSE
|
||||
|
14
setup.py
14
setup.py
@ -1,10 +1,3 @@
|
||||
try:
|
||||
from overlays import builder
|
||||
builder.compile()
|
||||
builder.copy()
|
||||
except:
|
||||
pass
|
||||
|
||||
import distribute_setup
|
||||
distribute_setup.use_setuptools()
|
||||
from setuptools import setup, Extension, find_packages
|
||||
@ -20,17 +13,18 @@ classifiers = ['Development Status :: 3 - Alpha',
|
||||
'Topic :: System :: Hardware']
|
||||
|
||||
setup(name = 'CHIP_IO',
|
||||
version = '0.0.9',
|
||||
version = '0.7.1',
|
||||
author = 'Robert Wolterman',
|
||||
author_email = 'robert.wolterman@gmail.com',
|
||||
description = 'A module to control CHIP IO channels',
|
||||
long_description = open('README.rst').read() + open('CHANGELOG.rst').read(),
|
||||
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/',
|
||||
classifiers = classifiers,
|
||||
packages = find_packages(),
|
||||
ext_modules = [Extension('CHIP_IO.GPIO', ['source/py_gpio.c', 'source/event_gpio.c', 'source/constants.c', 'source/common.c'], extra_compile_args=['-Wno-format-security']),
|
||||
Extension('CHIP_IO.PWM', ['source/py_pwm.c', 'source/c_pwm.c', 'source/constants.c', 'source/common.c'], extra_compile_args=['-Wno-format-security']),
|
||||
Extension('CHIP_IO.SOFTPWM', ['source/py_softpwm.c', 'source/c_softpwm.c', 'source/constants.c', 'source/common.c', 'source/event_gpio.c'], extra_compile_args=['-Wno-format-security'])]) #,
|
||||
Extension('CHIP_IO.SOFTPWM', ['source/py_softpwm.c', 'source/c_softpwm.c', 'source/constants.c', 'source/common.c', 'source/event_gpio.c'], extra_compile_args=['-Wno-format-security']),
|
||||
Extension('CHIP_IO.SERVO', ['source/py_servo.c', 'source/c_softservo.c', 'source/constants.c', 'source/common.c', 'source/event_gpio.c'], extra_compile_args=['-Wno-format-security'])]) #,
|
||||
# Extension('CHIP_IO.ADC', ['source/py_adc.c', 'source/c_adc.c', 'source/constants.c', 'source/common.c'], extra_compile_args=['-Wno-format-security']),
|
||||
|
436
source/c_pwm.c
436
source/c_pwm.c
@ -33,6 +33,7 @@ SOFTWARE.
|
||||
#include <stdlib.h>
|
||||
#include <sys/types.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include "c_pwm.h"
|
||||
@ -42,13 +43,18 @@ SOFTWARE.
|
||||
|
||||
#define PERIOD 0
|
||||
#define DUTY 1
|
||||
#define ENABLE 1
|
||||
#define DISABLE 0
|
||||
|
||||
int pwm_initialized = 0;
|
||||
// Global variables
|
||||
|
||||
// pwm exports
|
||||
struct pwm_exp
|
||||
{
|
||||
char key[KEYLEN+1]; /* leave room for terminating NUL byte */
|
||||
int iscpro;
|
||||
int gpio;
|
||||
int initialized;
|
||||
int period_fd;
|
||||
int duty_fd;
|
||||
int polarity_fd;
|
||||
@ -71,131 +77,331 @@ struct pwm_exp *lookup_exported_pwm(const char *key)
|
||||
}
|
||||
pwm = pwm->next;
|
||||
}
|
||||
|
||||
return NULL; /* standard for pointers */
|
||||
}
|
||||
|
||||
int initialize_pwm(void)
|
||||
int initialize_pwm(int *initialized, int gpio)
|
||||
{
|
||||
if (!pwm_initialized) {
|
||||
int e_no;
|
||||
if (!*initialized) {
|
||||
int fd, len;
|
||||
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)
|
||||
printf(" ** initialize_pwm **\n");
|
||||
if ((fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY)) < 0)
|
||||
{
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "initialize_pwm: could not open export file");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio);
|
||||
ssize_t s = write(fd, str_gpio, len); ASSRT(s == len);
|
||||
ssize_t s = write(fd, str_gpio, len); e_no = errno;
|
||||
close(fd);
|
||||
|
||||
pwm_initialized = 1;
|
||||
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "initialize_pwm: could not export pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** initialize_pwm: export pin: s = %d, len = %d\n", s, len);
|
||||
|
||||
*initialized = 1;
|
||||
return 1;
|
||||
} else {
|
||||
if (DEBUG)
|
||||
printf(" ** initialize_pwm: pwm is already initialized\n");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int pwm_set_frequency(const char *key, float freq) {
|
||||
int len;
|
||||
int len, e_no;
|
||||
int rtnval = -1;
|
||||
char buffer[80];
|
||||
unsigned long period_ns;
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
if (freq <= 0.0)
|
||||
return -1;
|
||||
return rtnval;
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
return -1;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
period_ns = (unsigned long)(1e9 / freq);
|
||||
|
||||
if (period_ns != pwm->period_ns) {
|
||||
pwm->period_ns = period_ns;
|
||||
if (pwm->enable) {
|
||||
if (period_ns != pwm->period_ns) {
|
||||
pwm->period_ns = period_ns;
|
||||
|
||||
len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->period_fd, buffer, len); ASSRT(s == len);
|
||||
len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->period_fd, buffer, len); e_no = errno;
|
||||
if (DEBUG) {
|
||||
printf(" ** pwm_set_frequency: pwm_initialized = %d\n", pwm->initialized);
|
||||
printf(" ** pwm_set_frequency: buffer: %s\n", buffer);
|
||||
printf(" ** pwm_set_frequency: s = %d, len = %d\n", s, len);
|
||||
}
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_set_frequency: could not change frequency of pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
rtnval = -1;
|
||||
} else {
|
||||
rtnval = 1;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_set_period_ns(const char *key, unsigned long period_ns) {
|
||||
int len, e_no;
|
||||
int rtnval = -1;
|
||||
char buffer[80];
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
//TODO: ADD CHECK FOR period_ns
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
if (pwm->enable) {
|
||||
if (period_ns != pwm->period_ns) {
|
||||
pwm->period_ns = period_ns;
|
||||
|
||||
len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->period_fd, buffer, len); e_no = errno;
|
||||
if (DEBUG) {
|
||||
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: s = %d, len = %d\n", s, len);
|
||||
}
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_set_period_ns: could not change period of pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
rtnval = -1;
|
||||
} else {
|
||||
rtnval = 1;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_get_period_ns(const char *key, unsigned long *period_ns) {
|
||||
int rtnval = -1;
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_get_period_ns: %lu **\n",pwm->period_ns);
|
||||
|
||||
// Set period_ns to what we have in the struct
|
||||
*period_ns = pwm->period_ns;
|
||||
|
||||
rtnval = 0;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_set_polarity(const char *key, int polarity) {
|
||||
int len;
|
||||
int len, e_no;
|
||||
int rtnval = -1;
|
||||
char buffer[80];
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
return -1;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
if (polarity < 0 || polarity > 1) {
|
||||
return -1;
|
||||
if (polarity != 0 && polarity != 1) {
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
if (polarity == 0) {
|
||||
len = snprintf(buffer, sizeof(buffer), "%s", "normal"); BUF2SMALL(buffer);
|
||||
// THIS ONLY WORKS WHEN PWM IS NOT ENABLED
|
||||
if (pwm->enable == 0) {
|
||||
if (polarity == 0) {
|
||||
len = snprintf(buffer, sizeof(buffer), "%s", "normal"); BUF2SMALL(buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
len = snprintf(buffer, sizeof(buffer), "%s", "inversed"); BUF2SMALL(buffer);
|
||||
}
|
||||
ssize_t s = write(pwm->polarity_fd, buffer, len); e_no = errno;
|
||||
if (DEBUG) {
|
||||
printf(" ** pwm_set_polarity: pwm_initialized = %d\n", pwm->initialized);
|
||||
printf(" ** pwm_set_polarity: buffer: %s\n", buffer);
|
||||
printf(" ** pwm_set_polarity: s = %d, len = %d\n", s, len);
|
||||
}
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_set_polarity: could not change polarity of pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
rtnval = -1;
|
||||
} else {
|
||||
rtnval = 1;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
len = snprintf(buffer, sizeof(buffer), "%s", "inverted"); BUF2SMALL(buffer);
|
||||
}
|
||||
ssize_t s = write(pwm->polarity_fd, buffer, len); ASSRT(s == len);
|
||||
|
||||
return 0;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_set_duty_cycle(const char *key, float duty) {
|
||||
int len;
|
||||
int len, e_no;
|
||||
int rtnval = -1;
|
||||
char buffer[80];
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
if (duty < 0.0 || duty > 100.0)
|
||||
return -1;
|
||||
if (duty < 0.0 || duty > 100.0) {
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
return -1;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
pwm->duty = (unsigned long)(pwm->period_ns * (duty / 100.0));
|
||||
|
||||
len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->duty_fd, buffer, len); ASSRT(s == len);
|
||||
if (pwm->enable) {
|
||||
len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->duty_fd, buffer, len); e_no = errno;
|
||||
if (DEBUG) {
|
||||
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: s = %d, len = %d\n", s, len);
|
||||
}
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_set_duty_cycle: could not change duty cycle of pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
rtnval = -1;
|
||||
} else {
|
||||
rtnval = 1;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_set_enable(const char *key, int enable)
|
||||
{
|
||||
int len;
|
||||
int pwm_set_pulse_width_ns(const char *key, unsigned long pulse_width_ns) {
|
||||
int len, e_no;
|
||||
int rtnval = -1;
|
||||
char buffer[80];
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
if (enable != 0 || enable != 1)
|
||||
return -1;
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
return -1;
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
pwm->enable = enable;
|
||||
if (pulse_width_ns < 0 || pulse_width_ns > pwm->period_ns)
|
||||
return rtnval;
|
||||
|
||||
len = snprintf(buffer, sizeof(buffer), "%d", pwm->enable); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->enable_fd, buffer, len); ASSRT(s == len);
|
||||
pwm->duty = pulse_width_ns / pwm->period_ns;
|
||||
|
||||
if (pwm->enable) {
|
||||
len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->duty_fd, buffer, len); e_no = errno;
|
||||
if (DEBUG) {
|
||||
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: s = %d, len = %d\n", s, len);
|
||||
}
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_set_pulse_width_ns: could not change pulse width of pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
rtnval = -1;
|
||||
} else {
|
||||
rtnval = 1;
|
||||
}
|
||||
} else {
|
||||
rtnval = 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return rtnval;
|
||||
|
||||
}
|
||||
|
||||
int pwm_set_enable(const char *key, int enable)
|
||||
{
|
||||
int len, e_no;
|
||||
int rtnval = -1;
|
||||
char buffer[80];
|
||||
struct pwm_exp *pwm;
|
||||
|
||||
if (enable != 0 && enable != 1) {
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_set_enable: enable needs to be 0 or 1! **\n");
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_set_enable: pwm struct is null **\n");
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
|
||||
len = snprintf(buffer, sizeof(buffer), "%d", enable); BUF2SMALL(buffer);
|
||||
ssize_t s = write(pwm->enable_fd, buffer, len); e_no = errno;
|
||||
if (DEBUG) {
|
||||
printf(" ** pwm_set_enable: pwm_initialized = %d\n", pwm->initialized);
|
||||
printf(" ** pwm_set_enable: buffer: %s\n", buffer);
|
||||
printf(" ** pwm_set_enable: s = %d, len = %d\n", s, len);
|
||||
}
|
||||
|
||||
if (s == len)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_set_enable: pwm->enable to %d\n", enable);
|
||||
pwm->enable = enable;
|
||||
rtnval = 0;
|
||||
} else {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_set_enable: could not enable/disable pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
rtnval = -1;
|
||||
}
|
||||
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_start(const char *key, float duty, float freq, int polarity)
|
||||
@ -207,13 +413,35 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
|
||||
char polarity_path[80];
|
||||
int period_fd, duty_fd, polarity_fd, enable_fd;
|
||||
struct pwm_exp *new_pwm, *pwm;
|
||||
int gpio = 0;
|
||||
int initialized = 0;
|
||||
int iscpro = 0;
|
||||
|
||||
if(!pwm_initialized) {
|
||||
initialize_pwm();
|
||||
// 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)
|
||||
printf(" ** pwm_start: pwm(%d) initialized = %d\n", gpio, initialized);
|
||||
} else {
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_start: pwm(%d) already initialized, cleaning up **", gpio);
|
||||
pwm_cleanup();
|
||||
}
|
||||
|
||||
//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
|
||||
snprintf(enable_path, sizeof(enable_path), "%s/enable", pwm_base_path); BUF2SMALL(enable_path);
|
||||
@ -221,39 +449,67 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
|
||||
snprintf(duty_path, sizeof(duty_path), "%s/duty_cycle", pwm_base_path); BUF2SMALL(duty_path);
|
||||
snprintf(polarity_path, sizeof(polarity_path), "%s/polarity", pwm_base_path); BUF2SMALL(polarity_path);
|
||||
|
||||
if (DEBUG) {
|
||||
printf(" ** pwm_start: pwm_base_path: %s\n", pwm_base_path);
|
||||
printf(" ** pwm_start: enable_path: %s\n", enable_path);
|
||||
printf(" ** pwm_start: period_path: %s\n", period_path);
|
||||
printf(" ** pwm_start: duty_path: %s\n", duty_path);
|
||||
printf(" ** pwm_start: polarity_path: %s\n", polarity_path);
|
||||
}
|
||||
|
||||
//add period and duty fd to pwm list
|
||||
if ((enable_fd = open(enable_path, O_RDWR)) < 0)
|
||||
return -1;
|
||||
|
||||
if ((period_fd = open(period_path, O_RDWR)) < 0) {
|
||||
close(enable_fd);
|
||||
if ((enable_fd = open(enable_path, O_WRONLY)) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_start: could not open enable file");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((period_fd = open(period_path, O_WRONLY)) < 0) {
|
||||
close(enable_fd);
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_start: could not open period file");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((duty_fd = open(duty_path, O_RDWR)) < 0) {
|
||||
if ((duty_fd = open(duty_path, O_WRONLY)) < 0) {
|
||||
//error, close already opened period_fd.
|
||||
close(enable_fd);
|
||||
close(period_fd);
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_start: could not open duty cycle file");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((polarity_fd = open(polarity_path, O_RDWR)) < 0) {
|
||||
if ((polarity_fd = open(polarity_path, O_WRONLY)) < 0) {
|
||||
//error, close already opened period_fd and duty_fd.
|
||||
close(enable_fd);
|
||||
close(period_fd);
|
||||
close(duty_fd);
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_start: could not open polarity file");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// add to list
|
||||
new_pwm = malloc(sizeof(struct pwm_exp));
|
||||
if (new_pwm == 0) {
|
||||
return -1; // out of memory
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_start: unable to allocate memory");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_start: sysfs files opened successfully **\n");
|
||||
strncpy(new_pwm->key, key, KEYLEN); /* can leave string unterminated */
|
||||
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->duty_fd = duty_fd;
|
||||
new_pwm->polarity_fd = polarity_fd;
|
||||
@ -272,50 +528,78 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
|
||||
pwm->next = new_pwm;
|
||||
}
|
||||
|
||||
pwm_set_frequency(key, freq);
|
||||
pwm_set_polarity(key, polarity);
|
||||
pwm_set_enable(key, 1);
|
||||
pwm_set_duty_cycle(key, duty);
|
||||
|
||||
return 1;
|
||||
int rtnval = 0;
|
||||
// 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) {
|
||||
rtnval = 0;
|
||||
rtnval = pwm_set_frequency(key, freq);
|
||||
if (rtnval != -1) {
|
||||
rtnval = 0;
|
||||
rtnval = pwm_set_duty_cycle(key, duty);
|
||||
}
|
||||
}
|
||||
}
|
||||
return rtnval;
|
||||
}
|
||||
|
||||
int pwm_disable(const char *key)
|
||||
{
|
||||
struct pwm_exp *pwm, *temp, *prev_pwm = NULL;
|
||||
|
||||
int fd, len;
|
||||
int fd, len, e_no;
|
||||
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;
|
||||
|
||||
pwm = lookup_exported_pwm(key);
|
||||
|
||||
if (pwm == NULL) {
|
||||
if (DEBUG)
|
||||
printf(" ** pwm_disable: pwm struct is null **\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Disable the PWM
|
||||
pwm_set_frequency(key, 0);
|
||||
pwm_set_polarity(key, 0);
|
||||
pwm_set_enable(key, 0);
|
||||
pwm_set_duty_cycle(key, 0);
|
||||
pwm_set_enable(key, DISABLE);
|
||||
pwm_set_polarity(key, 0);
|
||||
|
||||
if ((fd = open("/sys/class/pwm/pwmchip0/unexport", O_WRONLY)) < 0)
|
||||
{
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_disable: could not open unexport file");
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio);
|
||||
ssize_t s = write(fd, str_gpio, len); ASSRT(s == len);
|
||||
len = snprintf(str_gpio, sizeof(str_gpio), "%d", pwm->gpio); BUF2SMALL(str_gpio);
|
||||
ssize_t s = write(fd, str_gpio, len); e_no = errno;
|
||||
close(fd);
|
||||
|
||||
if (s != len) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "pwm_disable: could not unexport pwm (%s)", strerror(e_no));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// remove from list
|
||||
pwm = exported_pwms;
|
||||
while (pwm != NULL)
|
||||
{
|
||||
if (strcmp(pwm->key, key) == 0)
|
||||
{
|
||||
if (DEBUG) {
|
||||
printf(" ** pwm_disable: freeing memory %s\n", key);
|
||||
}
|
||||
//close the fd
|
||||
close(pwm->enable_fd);
|
||||
close(pwm->period_fd);
|
||||
close(pwm->duty_fd);
|
||||
close(pwm->polarity_fd);
|
||||
|
||||
|
||||
if (prev_pwm == NULL)
|
||||
{
|
||||
exported_pwms = pwm->next;
|
||||
@ -323,7 +607,6 @@ int pwm_disable(const char *key)
|
||||
} else {
|
||||
prev_pwm->next = pwm->next;
|
||||
}
|
||||
|
||||
temp = pwm;
|
||||
pwm = pwm->next;
|
||||
free(temp);
|
||||
@ -341,3 +624,4 @@ void pwm_cleanup(void)
|
||||
pwm_disable(exported_pwms->key);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -32,6 +32,9 @@ SOFTWARE.
|
||||
int pwm_start(const char *key, float duty, float freq, int polarity);
|
||||
int pwm_disable(const char *key);
|
||||
int pwm_set_frequency(const char *key, float freq);
|
||||
int pwm_set_period_ns(const char *key, unsigned long period_ns);
|
||||
int pwm_get_period_ns(const char *key, unsigned long *period_ns);
|
||||
int pwm_set_duty_cycle(const char *key, float duty);
|
||||
int pwm_set_pulse_width_ns(const char *key, unsigned long pulse_width_ns);
|
||||
int pwm_set_enable(const char *key, int enable);
|
||||
void pwm_cleanup(void);
|
||||
|
@ -35,13 +35,13 @@ SOFTWARE.
|
||||
#include <sys/types.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <pthread.h>
|
||||
#include <time.h>
|
||||
#include "c_pwm.h"
|
||||
#include "c_softpwm.h"
|
||||
#include "common.h"
|
||||
#include "event_gpio.h"
|
||||
#include "Python.h"
|
||||
|
||||
#define KEYLEN 7
|
||||
|
||||
@ -97,11 +97,13 @@ int softpwm_set_frequency(const char *key, float freq) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_set_frequency: %f **\n", freq);
|
||||
pthread_mutex_lock(pwm->params_lock);
|
||||
pwm->params.freq = freq;
|
||||
pthread_mutex_unlock(pwm->params_lock);
|
||||
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int softpwm_set_polarity(const char *key, int polarity) {
|
||||
@ -117,6 +119,8 @@ int softpwm_set_polarity(const char *key, int polarity) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_set_polarity: %d **\n", polarity);
|
||||
pthread_mutex_lock(pwm->params_lock);
|
||||
pwm->params.polarity = polarity;
|
||||
pthread_mutex_unlock(pwm->params_lock);
|
||||
@ -136,6 +140,8 @@ int softpwm_set_duty_cycle(const char *key, float duty) {;
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_set_duty_cycle: %f **\n", duty);
|
||||
pthread_mutex_lock(pwm->params_lock);
|
||||
pwm->params.duty = duty;
|
||||
pthread_mutex_unlock(pwm->params_lock);
|
||||
@ -195,7 +201,6 @@ void *softpwm_thread_toggle(void *arg)
|
||||
|
||||
if (enabled_local)
|
||||
{
|
||||
|
||||
/* Force 0 duty cycle to be 0 */
|
||||
if (duty_local != 0)
|
||||
{
|
||||
@ -239,12 +244,27 @@ int softpwm_start(const char *key, float duty, float freq, int polarity)
|
||||
int gpio;
|
||||
int ret;
|
||||
|
||||
if (get_gpio_number(key, &gpio) < 0)
|
||||
if (get_gpio_number(key, &gpio) < 0) {
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_start: invalid gpio specified **\n");
|
||||
return -1;
|
||||
if (gpio_export(gpio) < 0)
|
||||
return -1;
|
||||
if (gpio_set_direction(gpio, OUTPUT) < 0)
|
||||
}
|
||||
|
||||
if (gpio_export(gpio) < 0) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Error setting up softpwm on pin %d, maybe already exported? (%s)", gpio, get_error_msg());
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_start: %d exported **\n", gpio);
|
||||
|
||||
if (gpio_set_direction(gpio, OUTPUT) < 0) {
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_start: gpio_set_direction failed **\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// add to list
|
||||
new_pwm = malloc(sizeof(struct softpwm)); ASSRT(new_pwm != NULL);
|
||||
@ -274,12 +294,18 @@ int softpwm_start(const char *key, float duty, float freq, int polarity)
|
||||
pwm = pwm->next;
|
||||
pwm->next = new_pwm;
|
||||
}
|
||||
pthread_mutex_unlock(new_params_lock);
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_enable: setting softpwm parameters **\n");
|
||||
ASSRT(softpwm_set_duty_cycle(new_pwm->key, duty) == 0);
|
||||
ASSRT(softpwm_set_frequency(new_pwm->key, freq) == 0);
|
||||
ASSRT(softpwm_set_polarity(new_pwm->key, polarity) == 0);
|
||||
|
||||
pthread_mutex_lock(new_params_lock);
|
||||
// create thread for pwm
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_enable: creating thread **\n");
|
||||
ret = pthread_create(&new_thread, NULL, softpwm_thread_toggle, (void *)new_pwm);
|
||||
ASSRT(ret == 0);
|
||||
|
||||
@ -294,17 +320,23 @@ int softpwm_disable(const char *key)
|
||||
{
|
||||
struct softpwm *pwm, *temp, *prev_pwm = NULL;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** in softpwm_disable **\n");
|
||||
// remove from list
|
||||
pwm = exported_pwms;
|
||||
while (pwm != NULL)
|
||||
{
|
||||
if (strcmp(pwm->key, key) == 0)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_disable: found pin **\n");
|
||||
pthread_mutex_lock(pwm->params_lock);
|
||||
pwm->params.stop_flag = true;
|
||||
pthread_mutex_unlock(pwm->params_lock);
|
||||
pthread_join(pwm->thread, NULL); /* wait for thread to exit */
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** softpwm_disable: unexporting %d **\n", pwm->gpio);
|
||||
gpio_unexport(pwm->gpio);
|
||||
|
||||
if (prev_pwm == NULL)
|
||||
|
355
source/c_softservo.c
Normal file
355
source/c_softservo.c
Normal file
@ -0,0 +1,355 @@
|
||||
/*
|
||||
Copyright (c) 2017 Robert Wolterman
|
||||
|
||||
Using CHIP_IO servo code from Brady Hurlburt as a basis for the servo code
|
||||
|
||||
Copyright (c) 2016 Brady Hurlburt
|
||||
|
||||
Original BBIO Author Justin Cooper
|
||||
Modified for CHIP_IO Author Brady Hurlburt
|
||||
|
||||
This file incorporates work covered by the following copyright and
|
||||
permission notice, all modified code adopts the original license:
|
||||
|
||||
Copyright (c) 2013 Adafruit
|
||||
Author: Justin Cooper
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <sys/types.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <pthread.h>
|
||||
#include <time.h>
|
||||
#include "c_softservo.h"
|
||||
#include "common.h"
|
||||
#include "event_gpio.h"
|
||||
|
||||
#define KEYLEN 7
|
||||
|
||||
#define PERIOD 0
|
||||
#define DUTY 1
|
||||
|
||||
#define MSTONS 1000000
|
||||
#define BLOCKNS 20 * MSTONS
|
||||
#define FUDGEFACTOR 450
|
||||
#define MSTOMICROS 1000
|
||||
#define MICROSTONS 1000
|
||||
#define MINMICROS 1000
|
||||
#define NEUTRAL 1500
|
||||
#define MAXMICROS 2000
|
||||
|
||||
int servo_initialized = 0;
|
||||
|
||||
struct servo_params
|
||||
{
|
||||
float range;
|
||||
float min_angle;
|
||||
float max_angle;
|
||||
float current_angle;
|
||||
bool enabled;
|
||||
bool stop_flag;
|
||||
};
|
||||
|
||||
struct servo
|
||||
{
|
||||
char key[KEYLEN+1]; /* leave room for terminating NUL byte */
|
||||
int gpio;
|
||||
struct servo_params params;
|
||||
pthread_mutex_t* params_lock;
|
||||
pthread_t thread;
|
||||
struct servo *next;
|
||||
};
|
||||
struct servo *exported_servos = NULL;
|
||||
|
||||
struct servo *lookup_exported_servo(const char *key)
|
||||
{
|
||||
struct servo *srv = exported_servos;
|
||||
|
||||
while (srv != NULL)
|
||||
{
|
||||
if (strcmp(srv->key, key) == 0) {
|
||||
return srv;
|
||||
}
|
||||
srv = srv->next;
|
||||
}
|
||||
|
||||
return NULL; /* standard for pointers */
|
||||
}
|
||||
|
||||
void *servo_thread_toggle(void *arg)
|
||||
{
|
||||
struct servo *srv = (struct servo *)arg;
|
||||
int gpio = srv->gpio;
|
||||
struct timespec tim_on;
|
||||
struct timespec tim_off;
|
||||
float on_time_microsec = 0;
|
||||
unsigned int on_ns;
|
||||
unsigned int off_ns;
|
||||
|
||||
/* Used to determine if something has
|
||||
* has changed
|
||||
*/
|
||||
float angle_local = 0;
|
||||
float range_local = 0;
|
||||
bool stop_flag_local = false;
|
||||
bool enabled_local = false;
|
||||
bool recalculate_timing = false;
|
||||
|
||||
while (!stop_flag_local) {
|
||||
/* Take a snapshot of the parameter block */
|
||||
pthread_mutex_lock(srv->params_lock);
|
||||
if ((angle_local != srv->params.current_angle) || (range_local != srv->params.range)) {
|
||||
recalculate_timing = true;
|
||||
}
|
||||
angle_local = srv->params.current_angle;
|
||||
range_local = srv->params.range;
|
||||
enabled_local = srv->params.enabled;
|
||||
stop_flag_local = srv->params.stop_flag;
|
||||
pthread_mutex_unlock(srv->params_lock);
|
||||
|
||||
/* If freq or duty has been changed, update the
|
||||
* sleep times
|
||||
*/
|
||||
if (recalculate_timing) {
|
||||
if (DEBUG)
|
||||
printf(" ** servo updating timing: new angle: (%.2f)\n",angle_local);
|
||||
on_time_microsec = (((MAXMICROS - MINMICROS) / range_local) * angle_local) + NEUTRAL;
|
||||
on_ns = (unsigned long)(on_time_microsec * MICROSTONS - FUDGEFACTOR);
|
||||
off_ns = BLOCKNS - on_ns;
|
||||
tim_on.tv_sec = 0;
|
||||
tim_on.tv_nsec = on_ns;
|
||||
tim_off.tv_sec = 0;
|
||||
tim_off.tv_nsec = off_ns;
|
||||
recalculate_timing = false;
|
||||
}
|
||||
|
||||
if (enabled_local)
|
||||
{
|
||||
/* Set gpio */
|
||||
gpio_set_value(gpio, HIGH);
|
||||
|
||||
nanosleep(&tim_on, NULL);
|
||||
|
||||
/* Unset gpio */
|
||||
gpio_set_value(gpio, LOW);
|
||||
|
||||
nanosleep(&tim_off, NULL);
|
||||
//printf("AFTER SECOND NANOSLEEP\n");
|
||||
} /* if enabled_local */
|
||||
} /* while !stop_flag_local */
|
||||
|
||||
gpio_set_value(gpio, LOW);
|
||||
|
||||
/* This servo has been disabled */
|
||||
pthread_exit(NULL);
|
||||
}
|
||||
|
||||
int servo_start(const char *key, float angle, float range)
|
||||
{
|
||||
struct servo *new_srv, *srv;
|
||||
pthread_t new_thread;
|
||||
pthread_mutex_t *new_params_lock;
|
||||
int gpio;
|
||||
int ret;
|
||||
|
||||
if (get_gpio_number(key, &gpio) < 0) {
|
||||
if (DEBUG)
|
||||
printf(" ** servo_start: invalid gpio specified **\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (gpio_export(gpio) < 0) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Error setting up servo on pin %d, maybe already exported? (%s)", gpio, get_error_msg());
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** servo_start: %d exported **\n", gpio);
|
||||
|
||||
if (gpio_set_direction(gpio, OUTPUT) < 0) {
|
||||
if (DEBUG)
|
||||
printf(" ** servo_start: gpio_set_direction failed **\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("c_softservo.c: servo_start(%d,%.2f,%.2f)\n",gpio,angle,range);
|
||||
|
||||
// add to list
|
||||
new_srv = malloc(sizeof(struct servo)); ASSRT(new_srv != NULL);
|
||||
new_params_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
|
||||
if (new_srv == 0) {
|
||||
return -1; // out of memory
|
||||
}
|
||||
pthread_mutex_init(new_params_lock, NULL);
|
||||
pthread_mutex_lock(new_params_lock);
|
||||
|
||||
strncpy(new_srv->key, key, KEYLEN); /* can leave string unterminated */
|
||||
new_srv->key[KEYLEN] = '\0'; /* terminate string */
|
||||
new_srv->gpio = gpio;
|
||||
new_srv->params.enabled = true;
|
||||
new_srv->params.stop_flag = false;
|
||||
new_srv->params_lock = new_params_lock;
|
||||
new_srv->next = NULL;
|
||||
|
||||
if (exported_servos == NULL)
|
||||
{
|
||||
// create new list
|
||||
exported_servos = new_srv;
|
||||
} else {
|
||||
// add to end of existing list
|
||||
srv = exported_servos;
|
||||
while (srv->next != NULL)
|
||||
srv = srv->next;
|
||||
srv->next = new_srv;
|
||||
}
|
||||
pthread_mutex_unlock(new_params_lock);
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** servo_enable: setting servo parameters **\n");
|
||||
ASSRT(servo_set_range(new_srv->key, range) == 0);
|
||||
ASSRT(servo_set_angle(new_srv->key, angle) == 0);
|
||||
|
||||
pthread_mutex_lock(new_params_lock);
|
||||
// create thread for srv
|
||||
if (DEBUG)
|
||||
printf(" ** servo_enable: creating thread **\n");
|
||||
ret = pthread_create(&new_thread, NULL, servo_thread_toggle, (void *)new_srv);
|
||||
ASSRT(ret == 0);
|
||||
|
||||
new_srv->thread = new_thread;
|
||||
|
||||
pthread_mutex_unlock(new_params_lock);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
int servo_disable(const char *key)
|
||||
{
|
||||
struct servo *srv, *temp, *prev_srv = NULL;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** in servo_disable **\n");
|
||||
// remove from list
|
||||
srv = exported_servos;
|
||||
while (srv != NULL)
|
||||
{
|
||||
if (strcmp(srv->key, key) == 0)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** servo_disable: found pin **\n");
|
||||
pthread_mutex_lock(srv->params_lock);
|
||||
srv->params.stop_flag = true;
|
||||
pthread_mutex_unlock(srv->params_lock);
|
||||
pthread_join(srv->thread, NULL); /* wait for thread to exit */
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** servo_disable: unexporting %d **\n", srv->gpio);
|
||||
gpio_unexport(srv->gpio);
|
||||
|
||||
if (prev_srv == NULL)
|
||||
{
|
||||
exported_servos = srv->next;
|
||||
prev_srv = srv;
|
||||
} else {
|
||||
prev_srv->next = srv->next;
|
||||
}
|
||||
|
||||
temp = srv;
|
||||
srv = srv->next;
|
||||
free(temp->params_lock);
|
||||
free(temp);
|
||||
} else {
|
||||
prev_srv = srv;
|
||||
srv = srv->next;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int servo_set_range(const char *key, float range)
|
||||
{
|
||||
struct servo *srv;
|
||||
float min_angle, max_angle;
|
||||
|
||||
srv = lookup_exported_servo(key);
|
||||
|
||||
if (srv == NULL) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Compute the min and max angle
|
||||
max_angle = range / 2.0;
|
||||
min_angle = -max_angle;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** servo_set_range(%d,%.2f = %.2f,%.2f)\n",srv->gpio,range,min_angle,max_angle);
|
||||
pthread_mutex_lock(srv->params_lock);
|
||||
srv->params.range = range;
|
||||
srv->params.min_angle = min_angle;
|
||||
srv->params.max_angle = max_angle;
|
||||
pthread_mutex_unlock(srv->params_lock);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int servo_set_angle(const char *key, float angle)
|
||||
{
|
||||
struct servo *srv;
|
||||
|
||||
srv = lookup_exported_servo(key);
|
||||
|
||||
if (srv == NULL) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Make sure we're between the range of allowable angles
|
||||
if (angle < srv->params.min_angle || angle > srv->params.max_angle) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Angle specified (%.2f) for pin %d, is outside allowable range (%.2f,%.2f)", angle, srv->gpio, srv->params.min_angle,srv->params.max_angle);
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** servo_set_angle(%d,%.2f)\n",srv->gpio,angle);
|
||||
pthread_mutex_lock(srv->params_lock);
|
||||
srv->params.current_angle = angle;
|
||||
pthread_mutex_unlock(srv->params_lock);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void servo_cleanup(void)
|
||||
{
|
||||
while (exported_servos != NULL) {
|
||||
servo_disable(exported_servos->key);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
40
source/c_softservo.h
Normal file
40
source/c_softservo.h
Normal file
@ -0,0 +1,40 @@
|
||||
/*
|
||||
Copyright (c) 2017 Robert Wolterman
|
||||
|
||||
Using CHIP_IO SoftPWM code from Brady Hurlburt as a basis for the servo code
|
||||
|
||||
Copyright (c) 2016 Brady Hurlburt
|
||||
|
||||
Original BBIO Author Justin Cooper
|
||||
Modified for CHIP_IO Author Brady Hurlburt
|
||||
|
||||
This file incorporates work covered by the following copyright and
|
||||
permission notice, all modified code adopts the original license:
|
||||
|
||||
Copyright (c) 2013 Adafruit
|
||||
Author: Justin Cooper
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
int servo_start(const char *key, float angle, float range);
|
||||
int servo_disable(const char *key);
|
||||
int servo_set_range(const char *key, float range);
|
||||
int servo_set_angle(const char *key, float angle);
|
||||
void servo_cleanup(void);
|
424
source/common.c
424
source/common.c
@ -36,7 +36,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "Python.h"
|
||||
#include <dirent.h>
|
||||
#include <time.h>
|
||||
#include "common.h"
|
||||
@ -46,94 +45,106 @@ SOFTWARE.
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/sysinfo.h>
|
||||
|
||||
int setup_error = 0;
|
||||
int module_setup = 0;
|
||||
|
||||
pins_t pins_info[] = {
|
||||
{ "GND", "GND", "U13_1", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CHG-IN", "CHG-IN", "U13_2", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "VCC-5V", "VCC-5V", "U13_3", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U13_4", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "VCC-3V3", "VCC-3V3", "U13_5", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "TS", "TS", "U13_6", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "VCC-1V8", "VCC-1V8", "U13_7", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "BAT", "BAT", "U13_8", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "TWI1-SDA", "KPD-I2C-SDA", "U13_9", 48, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "PWRON", "PWRON", "U13_10", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "TWI1-SCK", "KPD-I2C-SCL", "U13_11", 47, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U13_12", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "X1", "X1", "U13_13", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "X2", "X2", "U13_14", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "Y1", "Y1", "U13_15", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "Y2", "Y2", "U13_16", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D2", "LCD-D2", "U13_17", 98, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "PWM0", "PWM0", "U13_18", 34, BASE_METHOD_AS_IS, 0, -1},
|
||||
{ "LCD-D4", "LCD-D4", "U13_19", 100, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D3", "LCD-D3", "U13_20", 99, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D6", "LCD-D6", "U13_21", 102, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D5", "LCD-D5", "U13_22", 101, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D10", "LCD-D10", "U13_23", 106, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D7", "LCD-D7", "U13_24", 103, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D12", "LCD-D12", "U13_25", 108, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D11", "LCD-D11", "U13_26", 107, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D14", "LCD-D14", "U13_27", 110, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D13", "LCD-D13", "U13_28", 109, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D18", "LCD-D18", "U13_29", 114, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D15", "LCD-D15", "U13_30", 111, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D20", "LCD-D20", "U13_31", 116, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D19", "LCD-D19", "U13_32", 115, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D22", "LCD-D22", "U13_33", 118, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D21", "LCD-D21", "U13_34", 117, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-CLK", "LCD-CLK", "U13_35", 120, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-D23", "LCD-D23", "U13_36", 119, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-VSYNC", "LCD-VSYNC", "U13_37", 123, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-HSYNC", "LCD-HSYNC", "U13_38", 122, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U13_39", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LCD-DE", "LCD-DE", "U13_40", 121, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U14_1", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "VCC-5V", "VCC-5V", "U14_2", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "UART1-TX", "UART-TX", "U14_3", 195, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "HPL", "HPL", "U14_4", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "UART1-RX", "UART-RX", "U14_5", 196, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "HPCOM", "HPCOM", "U14_6", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "FEL", "FEL", "U14_7", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "HPR", "HPR", "U14_8", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "VCC-3V3", "VCC-3V3", "U14_9", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "MICM", "MICM", "U14_10", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "LRADC", "ADC", "U14_11", -1, BASE_METHOD_AS_IS, -1, 0},
|
||||
{ "MICIN1", "MICIN1", "U14_12", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "XIO-P0", "XIO-P0", "U14_13", 0, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P1", "XIO-P1", "U14_14", 1, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P2", "GPIO1", "U14_15", 2, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P3", "GPIO2", "U14_16", 3, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P4", "GPIO3", "U14_17", 4, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P5", "GPIO4", "U14_18", 5, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P6", "GPIO5", "U14_19", 6, BASE_METHOD_XIO, -1, -1},
|
||||
{ "XIO-P7", "GPIO6", "U14_20", 7, BASE_METHOD_XIO, -1, -1},
|
||||
{ "GND", "GND", "U14_21", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U14_22", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "AP-EINT1", "KPD-INT", "U14_23", 193, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "AP-EINT3", "AP-INT3", "U14_24", 35, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "TWI2-SDA", "I2C-SDA", "U14_25", 50, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "TWI2-SCK", "I2C-SCL", "U14_26", 49, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSIPCK", "SPI-SEL", "U14_27", 128, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSICK", "SPI-CLK", "U14_28", 129, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSIHSYNC", "SPI-MOSI", "U14_29", 130, BASE_METHOD_AS_IS, 1, -1},
|
||||
{ "CSIVSYNC", "SPI-MISO", "U14_30", 131, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID0", "CSID0", "U14_31", 132, BASE_METHOD_AS_IS, 1, -1},
|
||||
{ "CSID1", "CSID1", "U14_32", 133, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID2", "CSID2", "U14_33", 134, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID3", "CSID3", "U14_34", 135, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID4", "CSID4", "U14_35", 136, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID5", "CSID5", "U14_36", 137, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID6", "CSID6", "U14_37", 138, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "CSID7", "CSID7", "U14_38", 139, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U14_39", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ "GND", "GND", "U14_40", -1, BASE_METHOD_AS_IS, -1, -1},
|
||||
{ NULL, NULL, NULL, -1, 0, -1, -1}
|
||||
};
|
||||
// Library Debug
|
||||
int DEBUG = 0;
|
||||
|
||||
// Is This a CHIP PRO
|
||||
int is_chip_pro = 0;
|
||||
|
||||
pins_t pins_info[] = {
|
||||
{ "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},
|
||||
{ "VCC-5V", "VCC-5V", "U13_3", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "GND", "GND", "U13_4", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "VCC-3V3", "VCC-3V3", "U13_5", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "TS", "TS", "U13_6", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "VCC-1V8", "VCC-1V8", "U13_7", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "BAT", "BAT", "U13_8", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "TWI1-SDA", "KPD-I2C-SDA", "U13_9", 48, 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},
|
||||
{ "GND", "GND", "U13_12", -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, CHIP},
|
||||
{ "Y1", "Y1", "U13_15", -1, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "Y2", "Y2", "U13_16", -1, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "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},
|
||||
{ "PWM1", "PWM1", "EINT13", 205, BASE_METHOD_AS_IS, 0, -1, CHIPPRO},
|
||||
{ "LCD-D4", "UART2-CTS", "U13_19", 100, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "LCD-D3", "UART2-RX", "U13_20", 99, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "LCD-D6", "LCD-D6", "U13_21", 102, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D5", "UART2-RTS", "U13_22", 101, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "LCD-D10", "LCD-D10", "U13_23", 106, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D7", "LCD-D7", "U13_24", 103, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D12", "LCD-D12", "U13_25", 108, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D11", "LCD-D11", "U13_26", 107, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D14", "LCD-D14", "U13_27", 110, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D13", "LCD-D13", "U13_28", 109, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D18", "LCD-D18", "U13_29", 114, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D15", "LCD-D15", "U13_30", 111, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D20", "LCD-D20", "U13_31", 116, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D19", "LCD-D19", "U13_32", 115, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D22", "LCD-D22", "U13_33", 118, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D21", "LCD-D21", "U13_34", 117, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-CLK", "LCD-CLK", "U13_35", 120, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "LCD-D23", "LCD-D23", "U13_36", 119, BASE_METHOD_AS_IS, -1, -1, CHIP},
|
||||
{ "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},
|
||||
{ "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},
|
||||
{ "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}, /* THIS IS AP-EINT3 ON CHIP PRO */
|
||||
{ "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}, /* THIS IS AP-EINT4 ON CHIP PRO */
|
||||
{ "HPCOM", "HPCOM", "U14_6", -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},
|
||||
{ "VCC-3V3", "VCC-3V3", "U14_9", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "MICM", "MICM", "U14_10", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "LRADC", "ADC", "U14_11", -1, BASE_METHOD_AS_IS, -1, 0, BOTH},
|
||||
{ "MICIN1", "MICIN1", "U14_12", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "XIO-P0", "XIO-P0", "U14_13", 0, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P1", "XIO-P1", "U14_14", 1, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P2", "GPIO1", "U14_15", 2, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P3", "GPIO2", "U14_16", 3, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P4", "GPIO3", "U14_17", 4, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P5", "GPIO4", "U14_18", 5, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P6", "GPIO5", "U14_19", 6, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "XIO-P7", "GPIO6", "U14_20", 7, BASE_METHOD_XIO, -1, -1, CHIP},
|
||||
{ "GND", "GND", "U14_21", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "GND", "GND", "U14_22", -1, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "AP-EINT1", "KPD-INT", "U14_23", 193, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "AP-EINT3", "AP-INT3", "U14_24", 35, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "TWI2-SDA", "I2C-SDA", "U14_25", 50, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "TWI2-SCK", "I2C-SCL", "U14_26", 49, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSIPCK", "SPI-SEL", "U14_27", 128, 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},
|
||||
{ "CSIVSYNC", "SPI-MISO", "U14_30", 131, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSID0", "D0", "U14_31", 132, BASE_METHOD_AS_IS, 1, -1, BOTH},
|
||||
{ "CSID1", "D1", "U14_32", 133, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSID2", "D2", "U14_33", 134, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSID3", "D3", "U14_34", 135, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSID4", "D4", "U14_35", 136, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSID5", "D5", "U14_36", 137, BASE_METHOD_AS_IS, -1, -1, BOTH},
|
||||
{ "CSID6", "D6", "U14_37", 138, 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_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}
|
||||
};
|
||||
|
||||
// CREDIT FOR THIS FUNCTION DUE TO HOWIE KATZ OF NTC AND STEVE FORD
|
||||
// THIS WILL FIND THE PROPER XIO BASE SYSFS NUMBER
|
||||
@ -215,6 +226,109 @@ int get_xio_base(void)
|
||||
return xio_base_address;
|
||||
} /* 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)
|
||||
{
|
||||
if (DEBUG) {
|
||||
DEBUG = 0;
|
||||
printf(" ** debug disabled\n");
|
||||
} else {
|
||||
DEBUG = 1;
|
||||
printf(" ** debug enabled\n");
|
||||
}
|
||||
}
|
||||
|
||||
int gpio_number(pins_t *pin)
|
||||
{
|
||||
@ -240,6 +354,44 @@ int gpio_number(pins_t *pin)
|
||||
return gpio_num;
|
||||
} /* gpio_number */
|
||||
|
||||
int gpio_pud_capable(pins_t *pin)
|
||||
{
|
||||
int capable = -1;
|
||||
|
||||
switch (pin->base_method) {
|
||||
case BASE_METHOD_AS_IS:
|
||||
capable = 1;
|
||||
break;
|
||||
|
||||
case BASE_METHOD_XIO:
|
||||
capable = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
@ -274,6 +426,39 @@ int lookup_gpio_by_altname(const char *altname)
|
||||
return -1;
|
||||
}
|
||||
|
||||
int lookup_pud_capable_by_key(const char *key)
|
||||
{
|
||||
pins_t *p;
|
||||
for (p = pins_info; p->key != NULL; ++p) {
|
||||
if (strcmp(p->key, key) == 0) {
|
||||
return gpio_pud_capable(p);
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int lookup_pud_capable_by_name(const char *name)
|
||||
{
|
||||
pins_t *p;
|
||||
for (p = pins_info; p->name != NULL; ++p) {
|
||||
if (strcmp(p->name, name) == 0) {
|
||||
return gpio_pud_capable(p);
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int lookup_pud_capable_by_altname(const char *altname)
|
||||
{
|
||||
pins_t *p;
|
||||
for (p = pins_info; p->altname != NULL; ++p) {
|
||||
if (strcmp(p->altname, altname) == 0) {
|
||||
return gpio_pud_capable(p);
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int lookup_ain_by_key(const char *key)
|
||||
{
|
||||
pins_t *p;
|
||||
@ -352,10 +537,16 @@ int get_pwm_key_by_name(const char *name, char *key)
|
||||
pins_t *p;
|
||||
for (p = pins_info; p->name != NULL; ++p) {
|
||||
if (strcmp(p->name, name) == 0) {
|
||||
if (DEBUG) {
|
||||
printf(" ** get_pwm_key_by_name: FOUND PWM KEY, VALIDATING MUX MODE **\n");
|
||||
}
|
||||
//validate it's a valid pwm pin
|
||||
if (p->pwm_mux_mode == -1)
|
||||
return 0;
|
||||
|
||||
if (DEBUG) {
|
||||
printf(" ** get_pwm_key_by_name: PWM KEY IS VALID ##\n");
|
||||
}
|
||||
strncpy(key, p->key, 7);
|
||||
key[7] = '\0';
|
||||
return 1;
|
||||
@ -372,15 +563,45 @@ int get_gpio_number(const char *key, int *gpio)
|
||||
if (*gpio <= 0) {
|
||||
*gpio = lookup_gpio_by_name(key);
|
||||
if (*gpio <= 0) {
|
||||
*gpio = lookup_gpio_by_altname(key);
|
||||
if (*gpio <=0) {
|
||||
status = -1; /* error */
|
||||
}
|
||||
*gpio = lookup_gpio_by_altname(key);
|
||||
if (*gpio <=0) {
|
||||
*gpio = lookup_gpio_by_number(key);
|
||||
if (*gpio <= 0) {
|
||||
status = -1; /* error */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
int compute_port_pin(const char *key, int gpio, int *port, int *pin)
|
||||
{
|
||||
int capable = 0;
|
||||
int rtn = -1;
|
||||
|
||||
capable = lookup_pud_capable_by_key(key);
|
||||
if (capable < 0) {
|
||||
capable = lookup_pud_capable_by_name(key);
|
||||
if (capable < 0) {
|
||||
capable = lookup_pud_capable_by_altname(key);
|
||||
if (capable < 0) {
|
||||
capable = 0; // default to false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (capable) {
|
||||
// Method from:
|
||||
// https://bbs.nextthing.co/t/chippy-gonzales-fast-gpio/14056/6?u=xtacocorex
|
||||
*port = gpio / 32;
|
||||
*pin = gpio % 32;
|
||||
rtn = 0;
|
||||
}
|
||||
|
||||
return rtn;
|
||||
}
|
||||
|
||||
int get_key(const char *input, char *key)
|
||||
{
|
||||
if (!copy_key_by_key(input, key)) {
|
||||
@ -439,33 +660,6 @@ int build_path(const char *partial_path, const char *prefix, char *full_path, si
|
||||
return 0;
|
||||
}
|
||||
|
||||
int get_spi_bus_path_number(unsigned int spi)
|
||||
{
|
||||
char path[FILENAME_BUFFER_SIZE];
|
||||
char ocp_dir[FILENAME_BUFFER_SIZE];
|
||||
|
||||
build_path("/sys/devices", "ocp", ocp_dir, sizeof(ocp_dir)); BUF2SMALL(ocp_dir);
|
||||
|
||||
if (spi == 0) {
|
||||
snprintf(path, sizeof(path), "%s/48030000.spi/spi_master/spi1", ocp_dir); BUF2SMALL(path);
|
||||
} else {
|
||||
snprintf(path, sizeof(path), "%s/481a0000.spi/spi_master/spi1", ocp_dir); BUF2SMALL(path);
|
||||
}
|
||||
|
||||
DIR* dir = opendir(path);
|
||||
if (dir) {
|
||||
closedir(dir);
|
||||
//device is using /dev/spidev1.x
|
||||
return 1;
|
||||
} else if (ENOENT == errno) {
|
||||
//device is using /dev/spidev2.x
|
||||
return 2;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// We do not know at compile time how many GPIOs there are, so it is not safe
|
||||
// to declare per-GPIO arrays with a static size. The "dyn_int_array_*"
|
||||
// functions implement a dynamic integer array which grows as needed at run
|
||||
|
@ -54,20 +54,27 @@ SOFTWARE.
|
||||
#define MODE_UNKNOWN -1
|
||||
#define BOARD 10
|
||||
#define BCM 11
|
||||
#define CHIP 0
|
||||
#define CHIPPRO 1
|
||||
#define BOTH 2
|
||||
|
||||
// In the pins_t structure, the "base_method" field tells how
|
||||
// the "gpio" field should be interpreted.
|
||||
#define BASE_METHOD_AS_IS 1 /* use the gpio value directly */
|
||||
#define BASE_METHOD_XIO 2 /* add the gpio value to the XIO base */
|
||||
#define SPWM_ENABLED 1 /* pin able to be used by software pwm */
|
||||
#define SPWM_DISABLED 0 /* pin unable to be used by software pwm */
|
||||
|
||||
typedef struct pins_t {
|
||||
const char *name;
|
||||
const char *altname; /* alternate name as referenced on pocketchip pin header */
|
||||
const char *key;
|
||||
//const char *altkey; /* alternate key for chip pro */
|
||||
int gpio; /* port number to use under /sys/class/gpio */
|
||||
int base_method; /* modifier for port number; see BASE_METHOD_... */
|
||||
int pwm_mux_mode;
|
||||
int ain;
|
||||
int pwm_mux_mode; /* pwm pin */
|
||||
int ain; /* analog pin */
|
||||
int sbc_type; /* which sbc pin is allowed */
|
||||
} pins_t;
|
||||
|
||||
|
||||
@ -77,17 +84,23 @@ struct dyn_int_array_s {
|
||||
};
|
||||
typedef struct dyn_int_array_s dyn_int_array_t;
|
||||
|
||||
|
||||
#define FILENAME_BUFFER_SIZE 128
|
||||
|
||||
int setup_error;
|
||||
int module_setup;
|
||||
extern int setup_error;
|
||||
extern int module_setup;
|
||||
extern int DEBUG;
|
||||
|
||||
int get_xio_base(void);
|
||||
int is_this_chippro(void);
|
||||
int gpio_number(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_name(const char *name);
|
||||
int lookup_gpio_by_altname(const char *altname);
|
||||
int lookup_pud_capable_by_key(const char *key);
|
||||
int lookup_pud_capable_by_name(const char *name);
|
||||
int lookup_pud_capable_by_altname(const char *altname);
|
||||
int lookup_ain_by_key(const char *key);
|
||||
int lookup_ain_by_name(const char *name);
|
||||
int copy_key_by_key(const char *input_key, char *key);
|
||||
@ -99,10 +112,13 @@ int get_key(const char *input, char *key);
|
||||
int get_pwm_key(const char *input, char *key);
|
||||
int get_adc_ain(const char *key, unsigned int *ain);
|
||||
int build_path(const char *partial_path, const char *prefix, char *full_path, size_t full_path_len);
|
||||
int get_spi_bus_path_number(unsigned int spi);
|
||||
void dyn_int_array_set(dyn_int_array_t **in_array, int i, int val, int initial_val);
|
||||
int dyn_int_array_get(dyn_int_array_t **in_array, int i, int initial_val);
|
||||
void dyn_int_array_delete(dyn_int_array_t **in_array);
|
||||
void clear_error_msg(void);
|
||||
char *get_error_msg(void);
|
||||
void add_error_msg(char *msg);
|
||||
void toggle_debug(void);
|
||||
int compute_port_pin(const char *key, int gpio, int *port, int *pin);
|
||||
int gpio_allowed(int gpio);
|
||||
int pwm_allowed(const char *key);
|
||||
|
@ -76,6 +76,15 @@ void define_constants(PyObject *module)
|
||||
both_edge = Py_BuildValue("i", BOTH_EDGE);
|
||||
PyModule_AddObject(module, "BOTH", both_edge);
|
||||
|
||||
version = Py_BuildValue("s", "0.0.9");
|
||||
unknown = Py_BuildValue("i", MODE_UNKNOWN);
|
||||
PyModule_AddObject(module, "UNKNOWN", unknown);
|
||||
|
||||
board = Py_BuildValue("i", BOARD);
|
||||
PyModule_AddObject(module, "BOARD", board);
|
||||
|
||||
bcm = Py_BuildValue("i", BCM);
|
||||
PyModule_AddObject(module, "BCM", bcm);
|
||||
|
||||
version = Py_BuildValue("s", "0.7.1");
|
||||
PyModule_AddObject(module, "VERSION", version);
|
||||
}
|
||||
|
@ -10,5 +10,8 @@ PyObject *rising_edge;
|
||||
PyObject *falling_edge;
|
||||
PyObject *both_edge;
|
||||
PyObject *version;
|
||||
PyObject *unknown;
|
||||
PyObject *board;
|
||||
PyObject *bcm;
|
||||
|
||||
void define_constants(PyObject *module);
|
||||
void define_constants(PyObject *module);
|
||||
|
@ -38,17 +38,23 @@ SOFTWARE.
|
||||
|
||||
#include <pthread.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/mman.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
#include "event_gpio.h"
|
||||
#include "common.h"
|
||||
|
||||
const char *stredge[4] = {"none", "rising", "falling", "both"};
|
||||
|
||||
// Memory Map for PUD
|
||||
uint8_t *memmap;
|
||||
|
||||
// file descriptors
|
||||
struct fdx
|
||||
{
|
||||
@ -63,8 +69,11 @@ struct fdx *fd_list = NULL;
|
||||
// event callbacks
|
||||
struct callback
|
||||
{
|
||||
int fde;
|
||||
int gpio;
|
||||
void (*func)(int gpio);
|
||||
int edge;
|
||||
void* data;
|
||||
void (*func)(int gpio, void* data);
|
||||
struct callback *next;
|
||||
};
|
||||
struct callback *callbacks = NULL;
|
||||
@ -82,6 +91,63 @@ dyn_int_array_t *event_occurred = NULL;
|
||||
int thread_running = 0;
|
||||
int epfd = -1;
|
||||
|
||||
// Thanks to WereCatf and Chippy-Gonzales for the Memory Mapping code/help
|
||||
int map_pio_memory()
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** map_pio_memory: opening /dev/mem **\n");
|
||||
int fd = open("/dev/mem", O_RDWR|O_SYNC);
|
||||
if(fd < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "map_pio_memory: could not open /dev/mem (%s)", strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
// uint32_t addr = 0x01c20800 & ~(getpagesize() - 1);
|
||||
//Requires memmap to be on pagesize-boundary
|
||||
if (DEBUG)
|
||||
printf(" ** map_pio_memory: mapping memory **\n");
|
||||
memmap = (uint8_t *)mmap(NULL, getpagesize()*2, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x01C20000);
|
||||
if(memmap == NULL) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "map_pio_memory: mmap failed (%s)", strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
close(fd);
|
||||
|
||||
//Set memmap to point to PIO-registers
|
||||
if (DEBUG)
|
||||
printf(" ** map_pio_memory: moving to pio registers **\n");
|
||||
memmap=memmap+0x800;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int gpio_get_pud(int port, int pin)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_get_pud: port %d, pin %d **\n", port, pin);
|
||||
volatile uint32_t *pioMem32, *configRegister;
|
||||
pioMem32=(uint32_t *)(memmap+port*0x24+0x1c); //0x1c == pull-register
|
||||
configRegister=pioMem32+(pin >> 4);
|
||||
return *configRegister >> ((pin & 15) * 2) & 3;
|
||||
}
|
||||
|
||||
int gpio_set_pud(int port, int pin, uint8_t value)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_set_pud: port %d, pin %d, value %d **\n", port, pin, value);
|
||||
value &= 3;
|
||||
volatile uint32_t *pioMem32, *configRegister;
|
||||
uint32_t mask;
|
||||
pioMem32=(uint32_t *)(memmap+port*0x24+0x1c); //0x1c == pull-register
|
||||
configRegister=pioMem32+(pin >> 4);
|
||||
mask = ~(3 << ((pin & 15) * 2));
|
||||
*configRegister &= mask;
|
||||
*configRegister |= value << ((pin & 15) * 2);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int gpio_export(int gpio)
|
||||
{
|
||||
@ -90,6 +156,9 @@ int gpio_export(int gpio)
|
||||
char str_gpio[80];
|
||||
struct gpio_exp *new_gpio, *g;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_export **\n");
|
||||
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/export"); BUF2SMALL(filename);
|
||||
|
||||
if ((fd = open(filename, O_WRONLY)) < 0)
|
||||
@ -102,16 +171,22 @@ int gpio_export(int gpio)
|
||||
|
||||
len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio);
|
||||
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);
|
||||
if (s != len)
|
||||
{
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_export: could not write '%s' to %s (%s)", str_gpio, filename, strerror(e_no));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
return -2;
|
||||
}
|
||||
|
||||
// add to list
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_export: creating data struct **\n");
|
||||
new_gpio = malloc(sizeof(struct gpio_exp)); ASSRT(new_gpio != NULL);
|
||||
|
||||
new_gpio->gpio = gpio;
|
||||
@ -158,7 +233,6 @@ void close_value_fd(int gpio)
|
||||
}
|
||||
} /* close_value_fd */
|
||||
|
||||
|
||||
int fd_lookup(int gpio)
|
||||
{
|
||||
struct fdx *f = fd_list;
|
||||
@ -172,6 +246,18 @@ int fd_lookup(int gpio)
|
||||
return 0;
|
||||
}
|
||||
|
||||
int fde_lookup(int gpio)
|
||||
{
|
||||
struct callback *cb = callbacks;
|
||||
while (cb != NULL)
|
||||
{
|
||||
if (cb->gpio == gpio)
|
||||
return cb->fde;
|
||||
cb = cb->next;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int add_fd_list(int gpio, int fd)
|
||||
{
|
||||
@ -201,7 +287,11 @@ int open_value_file(int gpio)
|
||||
// create file descriptor of value file
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/value", gpio); BUF2SMALL(filename);
|
||||
|
||||
if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) < 0) {
|
||||
// Changed this to open Read/Write to prevent a ton of file open/closes from happening when using
|
||||
// the GPIO for SOFTPWM
|
||||
if (DEBUG)
|
||||
printf(" ** open_value_file **\n");
|
||||
if ((fd = open(filename, O_RDWR | O_NONBLOCK)) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "open_value_file: could not open '%s' (%s)", filename, strerror(errno));
|
||||
add_error_msg(err);
|
||||
@ -212,6 +302,25 @@ int open_value_file(int gpio)
|
||||
return fd;
|
||||
} /* open_value_file */
|
||||
|
||||
int open_edge_file(int gpio)
|
||||
{
|
||||
int fd;
|
||||
char filename[MAX_FILENAME];
|
||||
|
||||
// create file descriptor of value file
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/edge", gpio); BUF2SMALL(filename);
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** open_edge_file **\n");
|
||||
if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "open_edge_file: could not open '%s' (%s)", filename, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return fd;
|
||||
} /* open_edge_file */
|
||||
|
||||
int gpio_unexport(int gpio)
|
||||
{
|
||||
@ -220,6 +329,9 @@ int gpio_unexport(int gpio)
|
||||
char str_gpio[16];
|
||||
struct gpio_exp *g, *temp, *prev_g = NULL;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_unexport **\n");
|
||||
|
||||
close_value_fd(gpio);
|
||||
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/unexport"); BUF2SMALL(filename);
|
||||
@ -241,6 +353,8 @@ int gpio_unexport(int gpio)
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_unexport: freeing memory **\n");
|
||||
// remove from list
|
||||
g = exported_gpios;
|
||||
while (g != NULL)
|
||||
@ -269,11 +383,23 @@ int gpio_set_direction(int gpio, unsigned int in_flag)
|
||||
char filename[MAX_FILENAME]; filename[0] = '\0';
|
||||
|
||||
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' (%s)", filename, strerror(errno));
|
||||
snprintf(err, sizeof(err), "gpio_set_direction: could not open '%s', sleeping for 1 second and retrying", filename);
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
// 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) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_set_direction: could not open '%s' (%s)", filename, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
char direction[16];
|
||||
@ -282,6 +408,9 @@ int gpio_set_direction(int gpio, unsigned int in_flag)
|
||||
} else {
|
||||
strncpy(direction, "in", ARRAY_SIZE(direction) - 1);
|
||||
}
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_set_direction: %s **\n",direction);
|
||||
|
||||
ssize_t s = write(fd, direction, strlen(direction)); e_no = errno;
|
||||
close(fd);
|
||||
if (s != strlen(direction)) {
|
||||
@ -327,6 +456,9 @@ int gpio_get_direction(int gpio, unsigned int *value)
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_get_direction: %s **\n",direction);
|
||||
|
||||
if (strcmp(direction, "out") == 0)
|
||||
*value = OUTPUT;
|
||||
@ -345,17 +477,23 @@ int gpio_get_direction(int gpio, unsigned int *value)
|
||||
|
||||
int gpio_set_value(int gpio, unsigned int value)
|
||||
{
|
||||
int fd, e_no;
|
||||
// This now uses the value file descriptor that is set in the other struct
|
||||
// in an effort to minimize opening/closing this
|
||||
int fd = fd_lookup(gpio);
|
||||
int e_no;
|
||||
char filename[MAX_FILENAME];
|
||||
char vstr[16];
|
||||
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/value", gpio); BUF2SMALL(filename);
|
||||
|
||||
if ((fd = open(filename, O_WRONLY)) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_set_value: could not open '%s' (%s)", filename, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
if (!fd)
|
||||
{
|
||||
if ((fd = open_value_file(gpio)) == -1) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_value: could not open GPIO %d value file", gpio);
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (value) {
|
||||
@ -364,8 +502,10 @@ int gpio_set_value(int gpio, unsigned int value)
|
||||
strncpy(vstr, "0", ARRAY_SIZE(vstr) - 1);
|
||||
}
|
||||
|
||||
//if (DEBUG)
|
||||
// printf(" ** gpio_set_value: writing %s **\n", vstr);
|
||||
|
||||
ssize_t s = write(fd, vstr, strlen(vstr)); e_no = errno;
|
||||
close(fd);
|
||||
|
||||
if (s != strlen(vstr)) {
|
||||
char err[256];
|
||||
@ -382,8 +522,7 @@ int gpio_get_value(int gpio, unsigned int *value)
|
||||
int fd = fd_lookup(gpio);
|
||||
char ch;
|
||||
|
||||
if (!fd)
|
||||
{
|
||||
if (!fd) {
|
||||
if ((fd = open_value_file(gpio)) == -1) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_value: could not open GPIO %d value file", gpio);
|
||||
@ -406,6 +545,9 @@ int gpio_get_value(int gpio, unsigned int *value)
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_get_value: %c **\n", ch);
|
||||
|
||||
if (ch == '1') {
|
||||
*value = 1;
|
||||
} else if (ch == '0') {
|
||||
@ -420,30 +562,141 @@ int gpio_get_value(int gpio, unsigned int *value)
|
||||
return 0;
|
||||
}
|
||||
|
||||
int gpio_set_edge(int gpio, unsigned int edge)
|
||||
int gpio_get_more(int gpio, int bits, unsigned int *value)
|
||||
{
|
||||
int fd;
|
||||
char filename[MAX_FILENAME];
|
||||
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/edge", gpio); BUF2SMALL(filename);
|
||||
|
||||
if ((fd = open(filename, O_WRONLY)) < 0) {
|
||||
int fd = fd_lookup(gpio);
|
||||
char ch;
|
||||
|
||||
if (!fd) {
|
||||
if ((fd = open_value_file(gpio)) == -1) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_set_edge: could not open '%s' (%s)", filename, strerror(errno));
|
||||
snprintf(err, sizeof(err), "gpio_get_more: could not open GPIO %d value file", gpio);
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
ssize_t s = write(fd, stredge[edge], strlen(stredge[edge]) + 1);
|
||||
// Loop for our number of bits
|
||||
int i;
|
||||
for (i = 0; i < bits; i++) {
|
||||
|
||||
if (lseek(fd, 0, SEEK_SET) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_more: could not seek GPIO %d (%s)", gpio, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
ssize_t s = read(fd, &ch, sizeof(ch));
|
||||
if (s < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_set_edge: could not write '%s' to %s (%s)", stredge[edge], filename, strerror(errno));
|
||||
snprintf(err, sizeof(err), "gpio_get_more: could not read GPIO %d (%s)", gpio, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
close(fd);
|
||||
|
||||
if (ch == '1') {
|
||||
*value |= (1 << i);
|
||||
} else if (ch == '0') {
|
||||
*value |= (0 << i);
|
||||
} else {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_more: unrecognized read GPIO %d (%c)", gpio, ch);
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
if (DEBUG) {
|
||||
printf(" ** gpio_get_more: %c **\n", ch);
|
||||
printf(" ** gpio_get_more: current value: %u **\n", *value);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
|
||||
}
|
||||
|
||||
int gpio_set_edge(int gpio, unsigned int edge)
|
||||
{
|
||||
int fd;
|
||||
char filename[MAX_FILENAME];
|
||||
|
||||
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/edge", gpio); BUF2SMALL(filename);
|
||||
|
||||
if ((fd = open(filename, O_WRONLY)) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_set_edge: could not open '%s' (%s)", filename, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_set_edge: %s **\n", stredge[edge]);
|
||||
|
||||
ssize_t s = write(fd, stredge[edge], strlen(stredge[edge]) + 1);
|
||||
if (s < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_set_edge: could not write '%s' to %s (%s)", stredge[edge], filename, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
close(fd);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int gpio_get_edge(int gpio)
|
||||
{
|
||||
int fd = fde_lookup(gpio);
|
||||
int rtnedge = -1;
|
||||
|
||||
if (!fd)
|
||||
{
|
||||
if ((fd = open_edge_file(gpio)) == -1) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_value: could not open GPIO %d edge file", gpio);
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (lseek(fd, 0, SEEK_SET) < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_value: could not seek GPIO %d (%s)", gpio, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
char edge[16] = { 0 }; /* make sure read is null-terminated */
|
||||
ssize_t s = read(fd, &edge, sizeof(edge) - 1);
|
||||
close(fd);
|
||||
while (s > 0 && edge[s-1] == '\n') { /* strip trailing newlines */
|
||||
edge[s-1] = '\0';
|
||||
s --;
|
||||
}
|
||||
|
||||
if (s < 0) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "gpio_get_value: could not read GPIO %d (%s)", gpio, strerror(errno));
|
||||
add_error_msg(err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** gpio_get_edge: %s **\n", edge);
|
||||
|
||||
if (strcmp(edge, "rising") == 0)
|
||||
{
|
||||
rtnedge = 1;
|
||||
}
|
||||
else if (strcmp(edge, "falling") == 0)
|
||||
{
|
||||
rtnedge = 2;
|
||||
}
|
||||
else if (strcmp(edge, "both") == 0)
|
||||
{
|
||||
rtnedge = 3;
|
||||
}
|
||||
|
||||
return rtnedge;
|
||||
}
|
||||
|
||||
int gpio_lookup(int fd)
|
||||
@ -462,18 +715,25 @@ int gpio_lookup(int fd)
|
||||
void exports_cleanup(void)
|
||||
{
|
||||
// unexport everything
|
||||
if (DEBUG)
|
||||
printf(" ** exports_cleanup **\n");
|
||||
while (exported_gpios != NULL)
|
||||
gpio_unexport(exported_gpios->gpio);
|
||||
}
|
||||
|
||||
int add_edge_callback(int gpio, void (*func)(int gpio))
|
||||
int add_edge_callback(int gpio, int edge, void (*func)(int gpio, void* data), void* data)
|
||||
{
|
||||
struct callback *cb = callbacks;
|
||||
struct callback *new_cb;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** add_edge_callback **\n");
|
||||
new_cb = malloc(sizeof(struct callback)); ASSRT(new_cb != NULL);
|
||||
|
||||
new_cb->fde = open_edge_file(gpio);
|
||||
new_cb->gpio = gpio;
|
||||
new_cb->edge = edge;
|
||||
new_cb->data = data;
|
||||
new_cb->func = func;
|
||||
new_cb->next = NULL;
|
||||
|
||||
@ -495,7 +755,34 @@ void run_callbacks(int gpio)
|
||||
while (cb != NULL)
|
||||
{
|
||||
if (cb->gpio == gpio)
|
||||
cb->func(cb->gpio);
|
||||
{
|
||||
int canrun = 0;
|
||||
unsigned int value = 0;
|
||||
gpio_get_value(gpio, &value);
|
||||
// Both Edge
|
||||
if (cb->edge == 3)
|
||||
{
|
||||
canrun = 1;
|
||||
}
|
||||
// Rising Edge
|
||||
else if ((cb->edge == 1) && (value == 1))
|
||||
{
|
||||
canrun = 1;
|
||||
}
|
||||
// Falling Edge
|
||||
else if ((cb->edge == 2) && (value == 0))
|
||||
{
|
||||
canrun = 1;
|
||||
}
|
||||
// Only run if we are allowed
|
||||
if (canrun)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** run_callbacks: gpio triggered: %d **\n", gpio);
|
||||
cb->func(cb->gpio, cb->data);
|
||||
}
|
||||
|
||||
}
|
||||
cb = cb->next;
|
||||
}
|
||||
}
|
||||
@ -510,6 +797,9 @@ void remove_callbacks(int gpio)
|
||||
{
|
||||
if (cb->gpio == gpio)
|
||||
{
|
||||
if (DEBUG)
|
||||
printf(" ** remove_callbacks: gpio: %d **\n", gpio);
|
||||
close(cb->fde);
|
||||
if (prev == NULL)
|
||||
callbacks = cb->next;
|
||||
else
|
||||
@ -642,6 +932,9 @@ int add_edge_detect(int gpio, unsigned int edge)
|
||||
struct epoll_event ev;
|
||||
long t = 0;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** add_edge_detect: gpio: %d **\n", gpio);
|
||||
|
||||
// check to see if this gpio has been added already
|
||||
if (gpio_event_add(gpio) != 0)
|
||||
return 1;
|
||||
@ -708,6 +1001,9 @@ void remove_edge_detect(int gpio)
|
||||
struct epoll_event ev;
|
||||
int fd = fd_lookup(gpio);
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** remove_edge_detect: gpio : %d **\n", gpio);
|
||||
|
||||
// delete callbacks for gpio
|
||||
remove_callbacks(gpio);
|
||||
|
||||
@ -743,7 +1039,7 @@ void event_cleanup(void)
|
||||
}
|
||||
|
||||
// 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
|
||||
{
|
||||
int fd = fd_lookup(gpio);
|
||||
@ -751,6 +1047,9 @@ int blocking_wait_for_edge(int gpio, unsigned int edge)
|
||||
struct epoll_event events, ev;
|
||||
char buf;
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** blocking_wait_for_edge: gpio: %d **\n", gpio);
|
||||
|
||||
if ((epfd = epoll_create(1)) == -1) {
|
||||
char err[256];
|
||||
snprintf(err, sizeof(err), "blocking_wait_for_edge: could not epoll_create GPIO %d (%s)", gpio, strerror(errno));
|
||||
@ -795,7 +1094,7 @@ int blocking_wait_for_edge(int gpio, unsigned int edge)
|
||||
// epoll for event
|
||||
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);
|
||||
return 5;
|
||||
@ -829,6 +1128,9 @@ int blocking_wait_for_edge(int gpio, unsigned int edge)
|
||||
}
|
||||
}
|
||||
|
||||
if (DEBUG)
|
||||
printf(" ** blocking_wait_for_edge: gpio triggered: %d **\n", gpio);
|
||||
|
||||
gpio_event_remove(gpio);
|
||||
close(epfd);
|
||||
return 0;
|
||||
|
@ -36,6 +36,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define NO_EDGE 0
|
||||
#define RISING_EDGE 1
|
||||
#define FALLING_EDGE 2
|
||||
@ -54,6 +56,12 @@ SOFTWARE.
|
||||
#define PUD_DOWN 1
|
||||
#define PUD_UP 2
|
||||
|
||||
extern uint8_t *memmap;
|
||||
|
||||
int map_pio_memory(void);
|
||||
int gpio_get_pud(int port, int pin);
|
||||
int gpio_set_pud(int port, int pin, uint8_t value);
|
||||
|
||||
int gpio_export(int gpio);
|
||||
int gpio_unexport(int gpio);
|
||||
void exports_cleanup(void);
|
||||
@ -61,14 +69,21 @@ int gpio_set_direction(int gpio, unsigned int in_flag);
|
||||
int gpio_get_direction(int gpio, unsigned int *value);
|
||||
int gpio_set_value(int gpio, unsigned int value);
|
||||
int gpio_get_value(int gpio, unsigned int *value);
|
||||
int gpio_get_more(int gpio, int bits, unsigned int *value);
|
||||
int fd_lookup(int gpio);
|
||||
int open_value_file(int gpio);
|
||||
|
||||
int fde_lookup(int gpio);
|
||||
int open_edge_file(int gpio);
|
||||
int gpio_set_edge(int gpio, unsigned int edge);
|
||||
int gpio_get_edge(int gpio);
|
||||
int add_edge_detect(int gpio, unsigned int edge);
|
||||
void remove_edge_detect(int gpio);
|
||||
int add_edge_callback(int gpio, void (*func)(int gpio));
|
||||
int add_edge_callback(int gpio, int edge, void (*func)(int gpio, void* data), void* data);
|
||||
int event_detected(int gpio);
|
||||
int gpio_event_add(int gpio);
|
||||
int gpio_event_remove(int gpio);
|
||||
int gpio_is_evented(int gpio);
|
||||
int event_initialise(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);
|
||||
|
770
source/py_gpio.c
770
source/py_gpio.c
File diff suppressed because it is too large
Load Diff
284
source/py_pwm.c
284
source/py_pwm.c
@ -34,15 +34,64 @@ SOFTWARE.
|
||||
#include "common.h"
|
||||
#include "c_pwm.h"
|
||||
|
||||
// python function cleanup()
|
||||
static PyObject *py_cleanup(PyObject *self, PyObject *args)
|
||||
// python function cleanup(channel)
|
||||
static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
// unexport the PWM
|
||||
pwm_cleanup();
|
||||
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();
|
||||
} else {
|
||||
if (!get_pwm_key(channel, key)) {
|
||||
pwm_cleanup();
|
||||
}
|
||||
pwm_disable(key);
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python function toggle_debug()
|
||||
static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
|
||||
{
|
||||
// toggle debug printing
|
||||
toggle_debug();
|
||||
|
||||
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)
|
||||
static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
@ -51,25 +100,45 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
|
||||
float frequency = 2000.0;
|
||||
float duty_cycle = 0.0;
|
||||
int polarity = 0;
|
||||
int allowed = -1;
|
||||
static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ffi", kwlist, &channel, &duty_cycle, &frequency, &polarity)) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!module_setup) {
|
||||
init_module();
|
||||
}
|
||||
|
||||
if (!get_pwm_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name.");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (duty_cycle < 0.0 || duty_cycle > 100.0)
|
||||
{
|
||||
// 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) {
|
||||
PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (frequency <= 0.0)
|
||||
{
|
||||
if (frequency <= 0.0) {
|
||||
PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0");
|
||||
return NULL;
|
||||
}
|
||||
@ -79,8 +148,12 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!pwm_start(key, duty_cycle, frequency, polarity))
|
||||
if (pwm_start(key, duty_cycle, frequency, polarity) < 0) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Unable to start PWM: %s (%s)", channel, get_error_msg());
|
||||
PyErr_SetString(PyExc_ValueError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
@ -90,6 +163,9 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int allowed = -1;
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s", &channel))
|
||||
return NULL;
|
||||
@ -99,7 +175,27 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
|
||||
return NULL;
|
||||
}
|
||||
|
||||
pwm_disable(key);
|
||||
// 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) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
|
||||
PyErr_SetString(PyExc_ValueError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
@ -109,14 +205,16 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int allowed = -1;
|
||||
float duty_cycle = 0.0;
|
||||
static char *kwlist[] = {"channel", "duty_cycle", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle))
|
||||
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");
|
||||
return NULL;
|
||||
}
|
||||
@ -126,8 +224,82 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
|
||||
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) {
|
||||
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
|
||||
PyErr_SetString(PyExc_ValueError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python method PWM.set_pulse_width(channel, pulse_width_ns)
|
||||
static PyObject *py_set_pulse_width_ns(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int allowed = -1;
|
||||
unsigned long pulse_width_ns = 0.0;
|
||||
unsigned long period_ns;
|
||||
static char *kwlist[] = {"channel", "pulse_width_ns", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|k", kwlist, &channel, &pulse_width_ns))
|
||||
return NULL;
|
||||
|
||||
if (!get_pwm_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name.");
|
||||
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
|
||||
int rtn = pwm_get_period_ns(key, &period_ns);
|
||||
if (rtn == -1) {
|
||||
PyErr_SetString(PyExc_ValueError, "period unable to be obtained");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (pulse_width_ns < 0.0 || pulse_width_ns > period_ns) {
|
||||
PyErr_SetString(PyExc_ValueError, "pulse width must have a value from 0 to period");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (pwm_set_pulse_width_ns(key, pulse_width_ns) < 0) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
|
||||
PyErr_SetString(PyExc_ValueError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@ -139,14 +311,16 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int allowed = -1;
|
||||
float frequency = 1.0;
|
||||
static char *kwlist[] = {"channel", "frequency", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency))
|
||||
return NULL;
|
||||
|
||||
if (frequency <= 0.0)
|
||||
{
|
||||
if (frequency <= 0.0) {
|
||||
PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0");
|
||||
return NULL;
|
||||
}
|
||||
@ -156,24 +330,92 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (pwm_set_frequency(key, frequency) == -1) {
|
||||
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
|
||||
// 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) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
|
||||
PyErr_SetString(PyExc_ValueError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python method PWM.set_period_ns(channel, period_ns)
|
||||
static PyObject *py_set_period_ns(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int allowed = -1;
|
||||
unsigned long period_ns = 2e6;
|
||||
static char *kwlist[] = {"channel", "period_ns", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|k", kwlist, &channel, &period_ns))
|
||||
return NULL;
|
||||
|
||||
if (period_ns <= 0) {
|
||||
PyErr_SetString(PyExc_ValueError, "period must be greater than 0ns");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!get_pwm_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid PWM key or name.");
|
||||
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) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "PWM: %s issue: (%s)", channel, get_error_msg());
|
||||
PyErr_SetString(PyExc_ValueError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
static const char moduledocstring[] = "Hardware PWM functionality of a CHIP using Python";
|
||||
|
||||
PyMethodDef pwm_methods[] = {
|
||||
{"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start the PWM channel. channel can be in the form of 'PWM0', or 'U13_18'"},
|
||||
{"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the PWM channel. channel can be in the form of 'PWM0', or 'U13_18'"},
|
||||
{ "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)" },
|
||||
{"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"},
|
||||
//{"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
|
||||
{"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_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" },
|
||||
{"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"},
|
||||
{"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}
|
||||
};
|
||||
|
||||
|
351
source/py_servo.c
Normal file
351
source/py_servo.c
Normal file
@ -0,0 +1,351 @@
|
||||
/*
|
||||
Copyright (c) 2017 Robert Wolterman
|
||||
|
||||
Using CHIP_IO servo code from Brady Hurlburt as a basis for the servo code
|
||||
|
||||
Copyright (c) 2016 Brady Hurlburt
|
||||
|
||||
Original BBIO Author Justin Cooper
|
||||
Modified for CHIP_IO Author Brady Hurlburt
|
||||
|
||||
This file incorporates work covered by the following copyright and
|
||||
permission notice, all modified code adopts the original license:
|
||||
|
||||
Copyright (c) 2013 Adafruit
|
||||
Author: Justin Cooper
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#include "Python.h"
|
||||
#include "constants.h"
|
||||
#include "common.h"
|
||||
#include "c_softservo.h"
|
||||
|
||||
// python function toggle_debug()
|
||||
static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
|
||||
{
|
||||
// toggle debug printing
|
||||
toggle_debug();
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python function cleanup()
|
||||
static PyObject *py_cleanup(PyObject *self, PyObject *args)
|
||||
{
|
||||
// TODO: PER PIN CLEANUP LIKE EVERYTHING ELSE
|
||||
|
||||
// unexport the Servo
|
||||
servo_cleanup();
|
||||
|
||||
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)
|
||||
static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
int gpio;
|
||||
char key[8];
|
||||
char *channel = NULL;
|
||||
float angle = 0.0;
|
||||
float range = 180.0;
|
||||
int allowed = -1;
|
||||
static char *kwlist[] = {"channel", "angle", "range", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ff", kwlist, &channel, &angle, &range)) {
|
||||
return NULL;
|
||||
}
|
||||
ASSRT(channel != NULL);
|
||||
|
||||
if (!module_setup) {
|
||||
init_module();
|
||||
}
|
||||
|
||||
if (!get_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid Servo key or name.");
|
||||
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);
|
||||
if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
|
||||
PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7");
|
||||
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) {
|
||||
printf("servo_start failed");
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Error starting servo on pin %s (%s)", key, get_error_msg());
|
||||
PyErr_SetString(PyExc_RuntimeError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python function stop(channel)
|
||||
static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
int gpio;
|
||||
char key[8];
|
||||
int allowed = -1;
|
||||
char *channel;
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s", &channel))
|
||||
return NULL;
|
||||
|
||||
if (!get_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid key or name");
|
||||
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);
|
||||
if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
|
||||
PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7");
|
||||
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);
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python method SERVO.set_range(channel, range)
|
||||
static PyObject *py_set_range(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
int gpio;
|
||||
char key[8];
|
||||
char *channel;
|
||||
float range = 180.0;
|
||||
int allowed = -1;
|
||||
static char *kwlist[] = {"channel", "range", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &range))
|
||||
return NULL;
|
||||
|
||||
if (range > 360.0) {
|
||||
PyErr_SetString(PyExc_ValueError, "range can not be greater than 360.0");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!get_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid key or name.");
|
||||
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);
|
||||
if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
|
||||
PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7");
|
||||
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) {
|
||||
PyErr_SetString(PyExc_RuntimeError, "You must start() the Servo channel first");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python method SERVO.set_angle(channel, angle)
|
||||
static PyObject *py_set_angle(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
int gpio;
|
||||
char key[8];
|
||||
char *channel;
|
||||
float angle = 0.0;
|
||||
int allowed = -1;
|
||||
static char *kwlist[] = {"channel", "angle", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &angle))
|
||||
return NULL;
|
||||
|
||||
//if (range > 360.0) {
|
||||
// PyErr_SetString(PyExc_ValueError, "range can not be greater than 360.0");
|
||||
// return NULL;
|
||||
//}
|
||||
|
||||
if (!get_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid key or name.");
|
||||
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);
|
||||
if ((gpio >= lookup_gpio_by_name("XIO-P0") && gpio <= lookup_gpio_by_name("XIO-P7"))) {
|
||||
PyErr_SetString(PyExc_ValueError, "Servo currently not available on XIO-P0 to XIO-P7");
|
||||
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) {
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Error setting servo angle on pin %s (%s)", key, get_error_msg());
|
||||
PyErr_SetString(PyExc_RuntimeError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
static const char moduledocstring[] = "Software Servo functionality of a CHIP using Python";
|
||||
|
||||
PyMethodDef servo_methods[] = {
|
||||
{"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start the Servo. channel can be in the form of 'XIO-P0', or 'U14_13'"},
|
||||
{"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the Servo. channel can be in the form of 'XIO-P0', or 'U14_13'"},
|
||||
{"set_range", (PyCFunction)py_set_range, METH_VARARGS, "Change the servo range\nrange - max angular range of the servo" },
|
||||
{"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."},
|
||||
{"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}
|
||||
};
|
||||
|
||||
#if PY_MAJOR_VERSION > 2
|
||||
static struct PyModuleDef chipservomodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
"SERVO", // name of module
|
||||
moduledocstring, // module documentation, may be NULL
|
||||
-1, // size of per-interpreter state of the module, or -1 if the module keeps state in global variables.
|
||||
servo_methods
|
||||
};
|
||||
#endif
|
||||
|
||||
#if PY_MAJOR_VERSION > 2
|
||||
PyMODINIT_FUNC PyInit_SERVO(void)
|
||||
#else
|
||||
PyMODINIT_FUNC initSERVO(void)
|
||||
#endif
|
||||
{
|
||||
PyObject *module = NULL;
|
||||
|
||||
#if PY_MAJOR_VERSION > 2
|
||||
if ((module = PyModule_Create(&chipservomodule)) == NULL)
|
||||
return NULL;
|
||||
#else
|
||||
if ((module = Py_InitModule3("SERVO", servo_methods, moduledocstring)) == NULL)
|
||||
return;
|
||||
#endif
|
||||
|
||||
define_constants(module);
|
||||
|
||||
|
||||
#if PY_MAJOR_VERSION > 2
|
||||
return module;
|
||||
#else
|
||||
return;
|
||||
#endif
|
||||
}
|
@ -34,16 +34,65 @@ SOFTWARE.
|
||||
#include "common.h"
|
||||
#include "c_softpwm.h"
|
||||
|
||||
// python function cleanup()
|
||||
static PyObject *py_cleanup(PyObject *self, PyObject *args)
|
||||
// python function toggle_debug()
|
||||
static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
|
||||
{
|
||||
// unexport the PWM
|
||||
softpwm_cleanup();
|
||||
// toggle debug printing
|
||||
toggle_debug();
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
// python function start(channel, duty_cycle, freq)
|
||||
// python function cleanup(channel)
|
||||
static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
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();
|
||||
} else {
|
||||
if (!get_key(channel, key)) {
|
||||
softpwm_cleanup();
|
||||
}
|
||||
softpwm_disable(key);
|
||||
}
|
||||
|
||||
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, polarity)
|
||||
static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
{
|
||||
char key[8];
|
||||
@ -51,26 +100,51 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
|
||||
float frequency = 2000.0;
|
||||
float duty_cycle = 0.0;
|
||||
int polarity = 0;
|
||||
int gpio;
|
||||
int allowed = -1;
|
||||
static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ffi", kwlist, &channel, &duty_cycle, &frequency, &polarity)) {
|
||||
return NULL;
|
||||
}
|
||||
ASSRT(channel != NULL);
|
||||
|
||||
if (!module_setup) {
|
||||
init_module();
|
||||
}
|
||||
|
||||
if (!get_key(channel, key)) {
|
||||
PyErr_SetString(PyExc_ValueError, "Invalid SOFTPWM key or name.");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (duty_cycle < 0.0 || duty_cycle > 100.0)
|
||||
{
|
||||
// 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) {
|
||||
PyErr_SetString(PyExc_ValueError, "duty_cycle must have a value from 0.0 to 100.0");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (frequency <= 0.0)
|
||||
{
|
||||
if (frequency <= 0.0) {
|
||||
PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0");
|
||||
return NULL;
|
||||
}
|
||||
@ -80,8 +154,13 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!softpwm_start(key, duty_cycle, frequency, polarity))
|
||||
return NULL;
|
||||
if (softpwm_start(key, duty_cycle, frequency, polarity) < 0) {
|
||||
printf("softpwm_start failed");
|
||||
char err[2000];
|
||||
snprintf(err, sizeof(err), "Error starting softpwm on pin %s (%s)", key, get_error_msg());
|
||||
PyErr_SetString(PyExc_RuntimeError, err);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
@ -91,6 +170,10 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int gpio;
|
||||
int allowed = -1;
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s", &channel))
|
||||
return NULL;
|
||||
@ -100,6 +183,25 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
|
||||
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);
|
||||
|
||||
Py_RETURN_NONE;
|
||||
@ -110,14 +212,17 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int gpio;
|
||||
int allowed = -1;
|
||||
float duty_cycle = 0.0;
|
||||
static char *kwlist[] = {"channel", "duty_cycle", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle))
|
||||
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");
|
||||
return NULL;
|
||||
}
|
||||
@ -127,6 +232,25 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
|
||||
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) {
|
||||
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
|
||||
return NULL;
|
||||
@ -140,14 +264,17 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
|
||||
{
|
||||
char key[8];
|
||||
char *channel;
|
||||
int gpio;
|
||||
int allowed = -1;
|
||||
float frequency = 1.0;
|
||||
static char *kwlist[] = {"channel", "frequency", NULL};
|
||||
|
||||
clear_error_msg();
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency))
|
||||
return NULL;
|
||||
|
||||
if ((frequency <= 0.0) || (frequency > 10000.0))
|
||||
{
|
||||
if ((frequency <= 0.0) || (frequency > 10000.0)) {
|
||||
PyErr_SetString(PyExc_ValueError, "frequency must be greater than 0.0 and less than 10000.0");
|
||||
return NULL;
|
||||
}
|
||||
@ -157,6 +284,25 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
|
||||
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) {
|
||||
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
|
||||
return NULL;
|
||||
@ -165,21 +311,21 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
|
||||
static const char moduledocstring[] = "Software PWM functionality of a CHIP using Python";
|
||||
|
||||
PyMethodDef pwm_methods[] = {
|
||||
{"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start 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_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
|
||||
{"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"},
|
||||
//{"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
|
||||
{"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)" },
|
||||
{"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"},
|
||||
{"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}
|
||||
};
|
||||
|
||||
#if PY_MAJOR_VERSION > 2
|
||||
static struct PyModuleDef chippwmmodule = {
|
||||
static struct PyModuleDef chipspwmmodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
"SOFTPWM", // name of module
|
||||
moduledocstring, // module documentation, may be NULL
|
||||
@ -197,7 +343,7 @@ PyMODINIT_FUNC initSOFTPWM(void)
|
||||
PyObject *module = NULL;
|
||||
|
||||
#if PY_MAJOR_VERSION > 2
|
||||
if ((module = PyModule_Create(&chippwmmodule)) == NULL)
|
||||
if ((module = PyModule_Create(&chipspwmmodule)) == NULL)
|
||||
return NULL;
|
||||
#else
|
||||
if ((module = Py_InitModule3("SOFTPWM", pwm_methods, moduledocstring)) == NULL)
|
||||
|
@ -1,96 +0,0 @@
|
||||
# The default ``config.py``
|
||||
|
||||
|
||||
def set_prefs(prefs):
|
||||
"""This function is called before opening the project"""
|
||||
|
||||
# Specify which files and folders to ignore in the project.
|
||||
# Changes to ignored resources are not added to the history and
|
||||
# VCSs. Also they are not returned in `Project.get_files()`.
|
||||
# Note that ``?`` and ``*`` match all characters but slashes.
|
||||
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
|
||||
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
|
||||
# '.svn': matches 'pkg/.svn' and all of its children
|
||||
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
|
||||
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
|
||||
prefs['ignored_resources'] = [
|
||||
'*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git',
|
||||
'.tox', '.env', 'node_modules', 'bower_components']
|
||||
|
||||
# Specifies which files should be considered python files. It is
|
||||
# useful when you have scripts inside your project. Only files
|
||||
# ending with ``.py`` are considered to be python files by
|
||||
# default.
|
||||
#prefs['python_files'] = ['*.py']
|
||||
|
||||
# Custom source folders: By default rope searches the project
|
||||
# for finding source folders (folders that should be searched
|
||||
# for finding modules). You can add paths to that list. Note
|
||||
# that rope guesses project source folders correctly most of the
|
||||
# time; use this if you have any problems.
|
||||
# The folders should be relative to project root and use '/' for
|
||||
# separating folders regardless of the platform rope is running on.
|
||||
# 'src/my_source_folder' for instance.
|
||||
#prefs.add('source_folders', 'src')
|
||||
|
||||
# You can extend python path for looking up modules
|
||||
#prefs.add('python_path', '~/python/')
|
||||
|
||||
# Should rope save object information or not.
|
||||
prefs['save_objectdb'] = True
|
||||
prefs['compress_objectdb'] = False
|
||||
|
||||
# If `True`, rope analyzes each module when it is being saved.
|
||||
prefs['automatic_soa'] = True
|
||||
# The depth of calls to follow in static object analysis
|
||||
prefs['soa_followed_calls'] = 0
|
||||
|
||||
# If `False` when running modules or unit tests "dynamic object
|
||||
# analysis" is turned off. This makes them much faster.
|
||||
prefs['perform_doa'] = True
|
||||
|
||||
# Rope can check the validity of its object DB when running.
|
||||
prefs['validate_objectdb'] = True
|
||||
|
||||
# How many undos to hold?
|
||||
prefs['max_history_items'] = 32
|
||||
|
||||
# Shows whether to save history across sessions.
|
||||
prefs['save_history'] = True
|
||||
prefs['compress_history'] = False
|
||||
|
||||
# Set the number spaces used for indenting. According to
|
||||
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
|
||||
# unit-tests use 4 spaces it is more reliable, too.
|
||||
prefs['indent_size'] = 4
|
||||
|
||||
# Builtin and c-extension modules that are allowed to be imported
|
||||
# and inspected by rope.
|
||||
prefs['extension_modules'] = []
|
||||
|
||||
# Add all standard c-extensions to extension_modules list.
|
||||
prefs['import_dynload_stdmods'] = True
|
||||
|
||||
# If `True` modules with syntax errors are considered to be empty.
|
||||
# The default value is `False`; When `False` syntax errors raise
|
||||
# `rope.base.exceptions.ModuleSyntaxError` exception.
|
||||
prefs['ignore_syntax_errors'] = False
|
||||
|
||||
# If `True`, rope ignores unresolvable imports. Otherwise, they
|
||||
# appear in the importing namespace.
|
||||
prefs['ignore_bad_imports'] = False
|
||||
|
||||
# If `True`, rope will transform a comma list of imports into
|
||||
# multiple separate import statements when organizing
|
||||
# imports.
|
||||
prefs['split_imports'] = False
|
||||
|
||||
# If `True`, rope will sort imports alphabetically by module name
|
||||
# instead of alphabetically by import statement, with from imports
|
||||
# after normal imports.
|
||||
prefs['sort_imports_alphabetically'] = False
|
||||
|
||||
|
||||
def project_opened(project):
|
||||
"""This function is called after opening the project"""
|
||||
# Do whatever you like here!
|
@ -1,2 +0,0 @@
|
||||
<EFBFBD>}q(Utest_softpwm_setup]q(Uteardown_moduleqUTestSoftpwmSetupqeUtest_gpio_output]q(hUTestGPIOOutputqeUtest_pwm_setup]q(hUTestPwmSetupqeUtest_gpio_setup]q (hU TestSetupq
|
||||
eUtest_gpio_input]q(hU
|
@ -1 +0,0 @@
|
||||
<EFBFBD>]q(]q]qe.
|
@ -1 +0,0 @@
|
||||
<EFBFBD>}q.
|
120
test/gptest.py → test/integrations/gptest.py
Executable file → Normal file
120
test/gptest.py → test/integrations/gptest.py
Executable file → Normal file
@ -4,13 +4,8 @@ import CHIP_IO.GPIO as GPIO
|
||||
import time
|
||||
import threading
|
||||
|
||||
DO_APEINT1_TEST = False
|
||||
DO_APEINT3_TEST = False
|
||||
DO_XIOP2_TEST = True
|
||||
|
||||
num_callbacks = 0
|
||||
|
||||
|
||||
def myfuncallback(channel):
|
||||
global num_callbacks
|
||||
num_callbacks += 1
|
||||
@ -19,9 +14,8 @@ def myfuncallback(channel):
|
||||
|
||||
loopfunction_exit = False
|
||||
|
||||
|
||||
def loopfunction():
|
||||
print("LOOP FUNCTION")
|
||||
print("LOOP FUNCTION START")
|
||||
for i in xrange(4):
|
||||
if loopfunction_exit:
|
||||
break
|
||||
@ -33,12 +27,16 @@ def loopfunction():
|
||||
mystr = "SETTING CSID0 HIGH (i=%d)" % i
|
||||
print(mystr)
|
||||
GPIO.output("CSID0", GPIO.HIGH)
|
||||
print("SLEEPING")
|
||||
print(" LOOP FUNCTION SLEEPING")
|
||||
time.sleep(1)
|
||||
|
||||
num_errs = 0
|
||||
|
||||
print("RUNNING GPIO SELF TEST")
|
||||
print("GETTING CHIP_IO VERSION")
|
||||
mystr = "CHIP_IO VERSION: %s" % GPIO.VERSION
|
||||
print(mystr)
|
||||
|
||||
print("\nRUNNING GPIO SELF TEST")
|
||||
GPIO.selftest(0)
|
||||
|
||||
print("\nVERIFYING SIMPLE FUNCTIONALITY")
|
||||
@ -52,7 +50,7 @@ else:
|
||||
print(" Able to use alternate names for GPIO")
|
||||
GPIO.cleanup()
|
||||
|
||||
GPIO.setup("U14_15", GPIO.IN) # XIO-P0
|
||||
GPIO.setup("U14_15", GPIO.IN) # XIO-P2
|
||||
GPIO.setup("CSID0", GPIO.OUT, initial=GPIO.LOW)
|
||||
if (GPIO.input("XIO-P2") != GPIO.LOW):
|
||||
print(" A low output on CSI0 does not lead to a low input on XIO-P2.")
|
||||
@ -73,70 +71,82 @@ GPIO.output("CSID0", GPIO.LOW)
|
||||
print "LOW", GPIO.input("GPIO1")
|
||||
assert(GPIO.input("GPIO1") == GPIO.LOW)
|
||||
|
||||
print("SWAP GPIO WIRES FOR EDGE DETECTION TESTS AS NEEDED")
|
||||
raw_input("PRESS ENTER WHEN READY TO START EDGE DETECTION TESTS")
|
||||
|
||||
# ==============================================
|
||||
# EDGE DETECTION - AP-EINT1
|
||||
if DO_APEINT1_TEST:
|
||||
print("\nSETTING UP RISING EDGE DETECTION ON AP-EINT1")
|
||||
GPIO.setup("AP-EINT1", GPIO.IN)
|
||||
GPIO.add_event_detect("AP-EINT1", GPIO.RISING)
|
||||
|
||||
print("VERIFYING EDGE DETECT")
|
||||
f = open("/sys/class/gpio/gpio193/edge", "r")
|
||||
edge = f.read()
|
||||
f.close()
|
||||
assert(edge == "rising\n")
|
||||
GPIO.remove_event_detect("AP-EINT1")
|
||||
print("\nSETTING UP RISING EDGE DETECTION ON AP-EINT1")
|
||||
GPIO.setup("AP-EINT1", GPIO.IN)
|
||||
GPIO.add_event_detect("AP-EINT1", GPIO.RISING, myfuncallback)
|
||||
print("VERIFYING EDGE DETECT WAS SET PROPERLY")
|
||||
f = open("/sys/class/gpio/gpio193/edge", "r")
|
||||
edge = f.read()
|
||||
f.close()
|
||||
assert(edge == "rising\n")
|
||||
GPIO.remove_event_detect("AP-EINT1")
|
||||
|
||||
# ==============================================
|
||||
# EDGE DETECTION - AP-EINT3
|
||||
if DO_APEINT3_TEST:
|
||||
print("\nSETTING UP BOTH EDGE DETECTION ON AP-EINT3")
|
||||
GPIO.setup("AP-EINT3", GPIO.IN)
|
||||
GPIO.add_event_detect("AP-EINT3", GPIO.BOTH)
|
||||
|
||||
print("VERIFYING EDGE DETECT")
|
||||
f = open("/sys/class/gpio/gpio35/edge", "r")
|
||||
edge = f.read()
|
||||
f.close()
|
||||
assert(edge == "both\n")
|
||||
GPIO.remove_event_detect("AP-EINT3")
|
||||
print("\nSETTING UP BOTH EDGE DETECTION ON AP-EINT3")
|
||||
GPIO.setup("AP-EINT3", GPIO.IN)
|
||||
GPIO.add_event_detect("AP-EINT3", GPIO.BOTH, myfuncallback)
|
||||
print("VERIFYING EDGE DETECT WAS SET PROPERLY")
|
||||
f = open("/sys/class/gpio/gpio35/edge", "r")
|
||||
edge = f.read()
|
||||
f.close()
|
||||
assert(edge == "both\n")
|
||||
GPIO.remove_event_detect("AP-EINT3")
|
||||
|
||||
# ==============================================
|
||||
# EDGE DETECTION - EXPANDED GPIO
|
||||
if DO_XIOP2_TEST:
|
||||
print("\nSETTING UP FALLING EDGE DETECTION ON XIO-P2")
|
||||
GPIO.add_event_detect("XIO-P2", GPIO.FALLING, myfuncallback)
|
||||
print("\nSETTING UP FALLING EDGE DETECTION ON XIO-P2")
|
||||
# WRITING CSID0 LOW FIRST AS THERE IS A DOUBLE HIT ON HIGH
|
||||
GPIO.output("CSID0", GPIO.LOW)
|
||||
GPIO.add_event_detect("XIO-P2", GPIO.FALLING, myfuncallback)
|
||||
|
||||
print("VERIFYING EDGE DETECT")
|
||||
base = GPIO.get_gpio_base()
|
||||
gfile = "/sys/class/gpio/gpio%d/edge" % (base + 2)
|
||||
f = open(gfile, "r")
|
||||
edge = f.read()
|
||||
f.close()
|
||||
assert(edge == "falling\n")
|
||||
print("VERIFYING EDGE DETECT")
|
||||
base = GPIO.get_gpio_base()
|
||||
gfile = "/sys/class/gpio/gpio%d/edge" % (base + 2)
|
||||
f = open(gfile, "r")
|
||||
edge = f.read()
|
||||
f.close()
|
||||
assert(edge == "falling\n")
|
||||
|
||||
# LOOP WRITING ON CSID0 TO HOPEFULLY GET CALLBACK TO WORK
|
||||
print("WAITING FOR CALLBACKS")
|
||||
print("WAITING FOR CALLBACKS ON XIO-P2")
|
||||
loopfunction()
|
||||
mystr = " num_callbacks = %d" % num_callbacks
|
||||
print(mystr)
|
||||
|
||||
print("PRESS CONTROL-C TO EXIT IF SCRIPT GETS STUCK")
|
||||
GPIO.remove_event_detect("XIO-P2")
|
||||
|
||||
print("\nSETTING UP RISING EDGE DETECTION ON XIO-P2")
|
||||
# WRITING CSID0 LOW FIRST AS THERE IS A DOUBLE HIT ON HIGH
|
||||
GPIO.output("CSID0", GPIO.LOW)
|
||||
num_callbacks = 0
|
||||
GPIO.add_event_detect("XIO-P2", GPIO.RISING, myfuncallback)
|
||||
print("WAITING FOR CALLBACKS ON XIO-P2")
|
||||
loopfunction()
|
||||
mystr = " num_callbacks = %d" % num_callbacks
|
||||
print(mystr)
|
||||
GPIO.remove_event_detect("XIO-P2")
|
||||
|
||||
print("\nSETTING UP BOTH EDGE DETECTION ON XIO-P2")
|
||||
# WRITING CSID0 LOW FIRST AS THERE IS A DOUBLE HIT ON HIGH
|
||||
GPIO.output("CSID0", GPIO.LOW)
|
||||
num_callbacks = 0
|
||||
GPIO.add_event_detect("XIO-P2", GPIO.BOTH, myfuncallback)
|
||||
print("WAITING FOR CALLBACKS ON XIO-P2")
|
||||
loopfunction()
|
||||
mystr = " num_callbacks = %d" % num_callbacks
|
||||
print(mystr)
|
||||
GPIO.remove_event_detect("XIO-P2")
|
||||
|
||||
print("\nWAIT FOR EDGE TESTING, SETUP FOR FALLING EDGE")
|
||||
print("PRESS CONTROL-C TO EXIT IF SCRIPT GETS STUCK")
|
||||
try:
|
||||
# WAIT FOR EDGE
|
||||
t = threading.Thread(target=loopfunction)
|
||||
t.start()
|
||||
print("WAITING FOR EDGE")
|
||||
if DO_APEINT1_TEST:
|
||||
GPIO.wait_for_edge("AP-EINT1", GPIO.FALLING)
|
||||
if DO_APEINT3_TEST:
|
||||
GPIO.wait_for_edge("AP-EINT3", GPIO.FALLING)
|
||||
if DO_XIOP2_TEST:
|
||||
GPIO.wait_for_edge("XIO-P2", GPIO.FALLING)
|
||||
print("WAITING FOR EDGE ON XIO-P2")
|
||||
GPIO.wait_for_edge("XIO-P2", GPIO.FALLING)
|
||||
# THIS SHOULD ONLY PRINT IF WE'VE HIT THE EDGE DETECT
|
||||
print("WE'VE FALLEN LIKE COOLIO'S CAREER")
|
||||
except:
|
65
test/integrations/lradctest.py
Normal file
65
test/integrations/lradctest.py
Normal file
@ -0,0 +1,65 @@
|
||||
import CHIP_IO.LRADC as ADC
|
||||
|
||||
# == ENABLE DEBUG ==
|
||||
print("ENABLING LRADC DEBUG OUTPUT")
|
||||
ADC.toggle_debug()
|
||||
|
||||
# == SETUP ==
|
||||
print("LRADC SETUP WITH SAMPLE RATE OF 125")
|
||||
ADC.setup(125)
|
||||
|
||||
# == SCALE FACTOR ==
|
||||
print("GETTING SCALE FACTOR")
|
||||
scalefactor = ADC.get_scale_factor()
|
||||
print(scalefactor)
|
||||
print("")
|
||||
|
||||
# == ALLOWABLE SAMPLING RATES ==
|
||||
print("GETTING ALLOWABLE SAMPLE RATES")
|
||||
rates = ADC.get_allowable_sample_rates()
|
||||
print(rates)
|
||||
print("IS 32.25 IN RATE TUPLE")
|
||||
print(ADC.SAMPLE_RATE_32P25 in rates)
|
||||
print("")
|
||||
|
||||
# == CURRENT SAMPLE RATE ==
|
||||
print("CURRENT SAMPLING RATE")
|
||||
crate = ADC.get_sample_rate()
|
||||
print(crate)
|
||||
print("")
|
||||
|
||||
# == SET SAMPLE RATE ==
|
||||
print("SETTING SAMPLE RATE TO 62.5")
|
||||
ADC.set_sample_rate(62.5)
|
||||
crate = ADC.get_sample_rate()
|
||||
print(crate)
|
||||
print("")
|
||||
|
||||
# == CHAN 0 RAW ==
|
||||
print("READING LRADC CHAN0 RAW")
|
||||
raw0 = ADC.get_chan0_raw()
|
||||
print(raw0)
|
||||
print("")
|
||||
|
||||
# == CHAN 1 RAW ==
|
||||
print("READING LRADC CHAN1 RAW")
|
||||
raw1 = ADC.get_chan1_raw()
|
||||
print(raw1)
|
||||
print("")
|
||||
|
||||
# == CHAN 0 ==
|
||||
print("READING LRADC CHAN0 WITH SCALE APPLIED")
|
||||
full0 = ADC.get_chan0()
|
||||
print(full0)
|
||||
print("")
|
||||
|
||||
# == CHAN 1 ==
|
||||
print("READING LRADC CHAN1 WITH SCALE APPLIED")
|
||||
full1 = ADC.get_chan1()
|
||||
print(full1)
|
||||
print("")
|
||||
|
||||
# == RESET ==
|
||||
print("RESETING SAMPLE RATE TO 250")
|
||||
ADC.set_sample_rate(250)
|
||||
|
36
test/integrations/omtest.py
Normal file
36
test/integrations/omtest.py
Normal file
@ -0,0 +1,36 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
import CHIP_IO.OverlayManager as OM
|
||||
import os
|
||||
|
||||
# ENABLE DEBUG
|
||||
print("ENABLING OVERLAY MANAGER DEBUG")
|
||||
OM.toggle_debug()
|
||||
|
||||
# **************** PWM *******************
|
||||
print("\nIS PWM ENABLED: {0}".format(OM.get_pwm_loaded()))
|
||||
OM.load("PWM0")
|
||||
print("IS PWM ENABLED: {0}".format(OM.get_pwm_loaded()))
|
||||
# VERIFY PWM0 EXISTS
|
||||
if os.path.exists('/sys/class/pwm/pwmchip0'):
|
||||
print("PWM DEVICE EXISTS")
|
||||
else:
|
||||
print("PWM DEVICE DID NOT LOAD PROPERLY")
|
||||
print("UNLOADING PWM0")
|
||||
OM.unload("PWM0")
|
||||
print("IS PWM ENABLED: {0}".format(OM.get_pwm_loaded()))
|
||||
|
||||
# **************** SPI2 *******************
|
||||
print("\nIS SPI ENABLED: {0}".format(OM.get_spi_loaded()))
|
||||
OM.load("SPI2")
|
||||
print("IS SPI ENABLED: {0}".format(OM.get_spi_loaded()))
|
||||
# VERIFY SPI2 EXISTS
|
||||
if os.listdir('/sys/class/spi_master') != "":
|
||||
print("SPI DEVICE EXISTS")
|
||||
else:
|
||||
print("SPI DEVICE DID NOT LOAD PROPERLY")
|
||||
print("UNLOADING SPI")
|
||||
OM.unload("SPI2")
|
||||
print("IS SPI ENABLED: {0}".format(OM.get_spi_loaded()))
|
||||
|
||||
|
99
test/integrations/pwmtest.py
Normal file
99
test/integrations/pwmtest.py
Normal file
@ -0,0 +1,99 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
import CHIP_IO.PWM as PWM
|
||||
import CHIP_IO.GPIO as GPIO
|
||||
import CHIP_IO.OverlayManager as OM
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
|
||||
class PWMReceiver(threading.Thread):
|
||||
def __init__(self,gpio,key,maxcount=20,sleeptime=0.5):
|
||||
self.gpio = gpio
|
||||
self.key = key
|
||||
self.counter = 0
|
||||
self.maxcount = maxcount
|
||||
self.sleeptime = sleeptime
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
def run(self):
|
||||
print("SETTING UP RECEIVER GPIO")
|
||||
self.gpio.cleanup()
|
||||
self.gpio.setup(self.key, self.gpio.IN)
|
||||
print("STARTING RECEIVE LOOP")
|
||||
try:
|
||||
while self.counter < self.maxcount:
|
||||
pwmval = self.gpio.input(self.key)
|
||||
print("PWM VALUE: {0} @ {1}".format(pwmval, datetime.datetime.now()))
|
||||
time.sleep(self.sleeptime)
|
||||
self.counter += 1
|
||||
except KeyboardInterrupt:
|
||||
self.gpio.cleanup(self.key)
|
||||
|
||||
def PrintPwmData():
|
||||
print("PRINTING PWM SYSFS DATA")
|
||||
f = open("/sys/class/pwm/pwmchip0/pwm0/enable")
|
||||
print("PWM0 ENABLE:\t{}".format(f.readline()))
|
||||
f.close()
|
||||
f = open("/sys/class/pwm/pwmchip0/pwm0/period")
|
||||
print("PWM0 PERIOD:\t{}".format(f.readline()))
|
||||
f.close()
|
||||
f = open("/sys/class/pwm/pwmchip0/pwm0/duty_cycle")
|
||||
print("PWM0 DUTY CYCLE:\t{}".format(f.readline()))
|
||||
f.close()
|
||||
f = open("/sys/class/pwm/pwmchip0/pwm0/polarity")
|
||||
print("PWM0 POLARITY:\t{}".format(f.readline()))
|
||||
f.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# SETUP VARIABLES
|
||||
PWMGPIO = "PWM0"
|
||||
RECEIVERGPIO = "CSID0"
|
||||
COUNT = 150
|
||||
SLEEPTIME = 0.01
|
||||
|
||||
# LOAD THE PWM OVERLAY
|
||||
print("LOADING PWM OVERLAY")
|
||||
OM.load("PWM0")
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
# CLEANUP THE GPIO
|
||||
#GPIO.cleanup()
|
||||
#PWM.cleanup()
|
||||
|
||||
# SETUP PWM
|
||||
try:
|
||||
print("PWM START")
|
||||
PWM.toggle_debug()
|
||||
PWM.start(PWMGPIO, 15, 50, 1)
|
||||
PrintPwmData()
|
||||
|
||||
# UNCOMMENT FOR CRASH
|
||||
#print("PWM SET FREQUENCY")
|
||||
#PWM.set_frequency(PWMGPIO, 200)
|
||||
#PrintPwmData()
|
||||
|
||||
# UNCOMMENT FOR CRASH
|
||||
#print("PWM SET DUTY CYCLE")
|
||||
#PWM.set_duty_cycle(PWMGPIO, 25)
|
||||
#PrintPwmData()
|
||||
|
||||
# SETUP PWM RECEIVER
|
||||
#rcvr = PWMReceiver(GPIO, RECEIVERGPIO, COUNT, SLEEPTIME)
|
||||
#rcvr.start()
|
||||
|
||||
#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()
|
||||
|
||||
|
71
test/integrations/servotest.py
Normal file
71
test/integrations/servotest.py
Normal file
@ -0,0 +1,71 @@
|
||||
import CHIP_IO.SERVO as SERVO
|
||||
import CHIP_IO.GPIO as GPIO
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
|
||||
class ServoTestReceiver(threading.Thread):
|
||||
def __init__(self,gpio,key,maxcount=20,sleeptime=0.005):
|
||||
self.gpio = gpio
|
||||
self.key = key
|
||||
self.counter = 0
|
||||
self.maxcount = maxcount
|
||||
self.sleeptime = sleeptime
|
||||
self.dead = False
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
def kill(self):
|
||||
self.dead = True
|
||||
|
||||
def run(self):
|
||||
print("SETTING UP RECEIVER GPIO")
|
||||
self.gpio.cleanup()
|
||||
self.gpio.setup(self.key, self.gpio.IN)
|
||||
print("STARTING RECEIVE LOOP")
|
||||
try:
|
||||
#while self.counter < self.maxcount:
|
||||
while not self.dead:
|
||||
pwmval = self.gpio.input(self.key)
|
||||
print("SERVO VALUE: {0} @ {1}".format(pwmval, datetime.datetime.now()))
|
||||
time.sleep(self.sleeptime)
|
||||
self.counter += 1
|
||||
except KeyboardInterrupt:
|
||||
self.gpio.cleanup(self.key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# SETUP VARIABLES
|
||||
SERVOGPIO = "CSID1" #"XIO-P7"
|
||||
RECEIVERGPIO = "CSID7"
|
||||
COUNT = 120
|
||||
SLEEPTIME = 0.0001
|
||||
RANGE = 180
|
||||
|
||||
# SETUP PWM
|
||||
try:
|
||||
print("SERVO START")
|
||||
SERVO.toggle_debug()
|
||||
SERVO.start(SERVOGPIO, 0, RANGE)
|
||||
|
||||
# SETUP SERVO RECEIVER
|
||||
#rcvr = ServoTestReceiver(GPIO, RECEIVERGPIO, COUNT, SLEEPTIME)
|
||||
#rcvr.start()
|
||||
|
||||
# LOOP THROUGH RANGE
|
||||
for i in range(-(RANGE/2),(RANGE/2),5):
|
||||
print("SETTING ANGLE: {0}".format(i))
|
||||
SERVO.set_angle(SERVOGPIO, i)
|
||||
time.sleep(1)
|
||||
|
||||
#rcvr.kill()
|
||||
raw_input("PRESS ENTER WHEN DONE")
|
||||
|
||||
except:
|
||||
raise
|
||||
finally:
|
||||
# CLEANUP
|
||||
print("CLEANUP")
|
||||
SERVO.stop(SERVOGPIO)
|
||||
SERVO.cleanup(SERVOGPIO)
|
||||
|
||||
|
70
test/integrations/spwmtest.py
Normal file
70
test/integrations/spwmtest.py
Normal file
@ -0,0 +1,70 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
import CHIP_IO.SOFTPWM as SPWM
|
||||
import CHIP_IO.GPIO as GPIO
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
|
||||
class SPWMReceiver(threading.Thread):
|
||||
def __init__(self,gpio,key,maxcount=20,sleeptime=0.5):
|
||||
self.gpio = gpio
|
||||
self.key = key
|
||||
self.counter = 0
|
||||
self.maxcount = maxcount
|
||||
self.sleeptime = sleeptime
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
def run(self):
|
||||
print("SETTING UP RECEIVER GPIO")
|
||||
self.gpio.cleanup()
|
||||
self.gpio.setup(self.key, self.gpio.IN)
|
||||
print("STARTING RECEIVE LOOP")
|
||||
try:
|
||||
while self.counter < self.maxcount:
|
||||
pwmval = self.gpio.input(self.key)
|
||||
print("SPWM VALUE: {0} @ {1}".format(pwmval, datetime.datetime.now()))
|
||||
time.sleep(self.sleeptime)
|
||||
self.counter += 1
|
||||
except KeyboardInterrupt:
|
||||
self.gpio.cleanup(self.key)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# SETUP VARIABLES
|
||||
SPWMGPIO = "XIO-P7"
|
||||
RECEIVERGPIO = "CSID0"
|
||||
COUNT = 200
|
||||
SLEEPTIME = 0.01
|
||||
|
||||
# CLEANUP THE GPIO
|
||||
GPIO.cleanup()
|
||||
SPWM.cleanup()
|
||||
|
||||
# ISSUE #16 VERIFICATION
|
||||
try:
|
||||
print("VERIFYING FIX FOR ISSUE #16, GPIO CONFIGURED THAT SPWM WANTS TO USE")
|
||||
GPIO.setup(SPWMGPIO, GPIO.OUT)
|
||||
SPWM.start(SPWMGPIO, 50, 1)
|
||||
except Exception as e:
|
||||
print("EXCEPTION: {}".format(e))
|
||||
print("GPIO CLEANUP")
|
||||
GPIO.cleanup()
|
||||
|
||||
# SETUP SOFTPWM
|
||||
print("STARTING SOFTPWM TEST")
|
||||
SPWM.start(SPWMGPIO, 50, 1)
|
||||
SPWM.set_frequency(SPWMGPIO, 2)
|
||||
|
||||
# SETUP SOFTPWM RECEIVER
|
||||
rcvr = SPWMReceiver(GPIO, RECEIVERGPIO, COUNT, SLEEPTIME)
|
||||
rcvr.start()
|
||||
|
||||
time.sleep(COUNT*SLEEPTIME + 1)
|
||||
|
||||
# CLEANUP
|
||||
print("CLEANUP")
|
||||
SPWM.stop(SPWMGPIO)
|
||||
SPWM.cleanup()
|
||||
GPIO.cleanup()
|
||||
|
||||
|
45
test/integrations/spwmtest2.py
Normal file
45
test/integrations/spwmtest2.py
Normal 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()
|
||||
|
||||
|
0
test/test_gpio_input.py
Executable file → Normal file
0
test/test_gpio_input.py
Executable file → Normal file
14
test/test_lradc.py
Normal file
14
test/test_lradc.py
Normal 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
|
@ -1,65 +1,74 @@
|
||||
import pytest
|
||||
import os
|
||||
import time
|
||||
|
||||
import CHIP_IO.PWM as PWM
|
||||
import CHIP_IO.OverlayManager as OM
|
||||
import CHIP_IO.Utilities as UT
|
||||
|
||||
def setup_module(module):
|
||||
if not UT.is_chip_pro():
|
||||
OM.load("PWM0")
|
||||
|
||||
def teardown_module(module):
|
||||
PWM.cleanup()
|
||||
if not UT.is_chip_pro():
|
||||
OM.unload("PWM0")
|
||||
|
||||
class TestPwmSetup:
|
||||
|
||||
def setup_method(self, test_method):
|
||||
time.sleep(0.5)
|
||||
|
||||
def test_start_pwm(self):
|
||||
PWM.start("PWM0", 0)
|
||||
|
||||
pwm_test = '/sys/class/pwm/pwmchip0/pwm0'
|
||||
pwm_test = '/sys/class/pwm/pwmchip0/pwm0/'
|
||||
|
||||
assert os.path.exists(pwm_test)
|
||||
duty = open(pwm_test + '/duty_cycle').read()
|
||||
period = open(pwm_test + '/period').read()
|
||||
assert os.path.exists(pwm_test) == True
|
||||
duty = open(pwm_test + 'duty_cycle').readline().strip()
|
||||
period = open(pwm_test + 'period').readline().strip()
|
||||
assert int(duty) == 0
|
||||
assert int(period) == 500000
|
||||
PWM.cleanup()
|
||||
|
||||
def test_start_pwm_with_polarity_one(self):
|
||||
PWM.cleanup()
|
||||
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)
|
||||
duty = open(pwm_test + '/duty_cycle').read()
|
||||
period = open(pwm_test + '/period').read()
|
||||
polarity = open(pwm_test + '/polarity').read()
|
||||
duty = open(pwm_test + 'duty_cycle').readline().strip()
|
||||
period = open(pwm_test + 'period').readline().strip()
|
||||
polarity = open(pwm_test + 'polarity').readline().strip()
|
||||
assert int(duty) == 0
|
||||
assert int(period) == 500000
|
||||
assert string(polarity) == "inverted"
|
||||
PWM.cleanup()
|
||||
assert str(polarity) == "inversed"
|
||||
|
||||
def test_start_pwm_with_polarity_default(self):
|
||||
PWM.cleanup()
|
||||
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)
|
||||
duty = open(pwm_test + '/duty_cycle').read()
|
||||
period = open(pwm_test + '/period').read()
|
||||
polarity = open(pwm_test + '/polarity').read()
|
||||
duty = open(pwm_test + 'duty_cycle').readline().strip()
|
||||
period = open(pwm_test + 'period').readline().strip()
|
||||
polarity = open(pwm_test + 'polarity').readline().strip()
|
||||
assert int(duty) == 0
|
||||
assert int(period) == 500000
|
||||
assert string(polarity) == "normal"
|
||||
PWM.cleanup()
|
||||
assert str(polarity) == "normal"
|
||||
|
||||
def test_start_pwm_with_polarity_zero(self):
|
||||
PWM.cleanup()
|
||||
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)
|
||||
duty = open(pwm_test + '/duty_cycle').read()
|
||||
period = open(pwm_test + '/period').read()
|
||||
polarity = open(pwm_test + '/polarity').read()
|
||||
duty = open(pwm_test + 'duty_cycle').readline().strip()
|
||||
period = open(pwm_test + 'period').readline().strip()
|
||||
polarity = open(pwm_test + 'polarity').readline().strip()
|
||||
assert int(duty) == 0
|
||||
assert int(period) == 500000
|
||||
assert string(polarity) == "normal"
|
||||
PWM.cleanup()
|
||||
assert str(polarity) == "normal"
|
||||
|
||||
def test_pwm_start_invalid_pwm_key(self):
|
||||
with pytest.raises(ValueError):
|
||||
@ -71,6 +80,7 @@ class TestPwmSetup:
|
||||
|
||||
def test_pwm_start_valid_duty_cycle_min(self):
|
||||
#testing an exception isn't thrown
|
||||
PWM.cleanup()
|
||||
PWM.start("PWM0", 0)
|
||||
PWM.cleanup()
|
||||
|
||||
@ -107,79 +117,68 @@ class TestPwmSetup:
|
||||
with pytest.raises(TypeError):
|
||||
PWM.start("PWM0", 0, 100, "1")
|
||||
|
||||
@pytest.mark.xfail(reason="pwm cleanup is doing weirdness for this test")
|
||||
def test_pwm_duty_modified(self):
|
||||
PWM.start("PWM0", 0)
|
||||
|
||||
pwm_test = '/sys/class/pwm/pwmchip0/pwm0'
|
||||
pwm_test = '/sys/class/pwm/pwmchip0/pwm0/'
|
||||
|
||||
assert os.path.exists(pwm_test)
|
||||
duty = open(pwm_test + '/duty_cycle').read()
|
||||
period = open(pwm_test + '/period').read()
|
||||
assert os.path.exists(pwm_test) == True
|
||||
duty = open(pwm_test + 'duty_cycle').readline().strip()
|
||||
period = open(pwm_test + 'period').readline().strip()
|
||||
assert int(duty) == 0
|
||||
assert int(period) == 500000
|
||||
|
||||
PWM.set_duty_cycle("PWM0", 100)
|
||||
duty = open(pwm_test + '/duty_cycle').read()
|
||||
period = open(pwm_test + '/period').read()
|
||||
duty = open(pwm_test + 'duty_cycle').readline().strip()
|
||||
period = open(pwm_test + 'period').readline().strip()
|
||||
assert int(duty) == 500000
|
||||
assert int(period) == 500000
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_duty_cycle_non_setup_key(self):
|
||||
with pytest.raises(RuntimeError):
|
||||
PWM.set_duty_cycle("PWM0", 100)
|
||||
with pytest.raises(ValueError):
|
||||
PWM.cleanup()
|
||||
PWM.set_duty_cycle("PWM0", 100)
|
||||
|
||||
def test_pwm_duty_cycle_invalid_key(self):
|
||||
with pytest.raises(ValueError):
|
||||
PWM.set_duty_cycle("P9_15", 100)
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_duty_cycle_invalid_value_high(self):
|
||||
PWM.start("PWM0", 0)
|
||||
with pytest.raises(ValueError):
|
||||
PWM.set_duty_cycle("PWM0", 101)
|
||||
PWM.cleanup()
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_duty_cycle_invalid_value_negative(self):
|
||||
PWM.start("PWM0", 0)
|
||||
with pytest.raises(ValueError):
|
||||
PWM.set_duty_cycle("PWM0", -1)
|
||||
PWM.cleanup()
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_duty_cycle_invalid_value_string(self):
|
||||
PWM.start("PWM0", 0)
|
||||
with pytest.raises(TypeError):
|
||||
PWM.set_duty_cycle("PWM0", "a")
|
||||
PWM.cleanup()
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_frequency_invalid_value_negative(self):
|
||||
PWM.start("PWM0", 0)
|
||||
with pytest.raises(ValueError):
|
||||
PWM.set_frequency("PWM0", -1)
|
||||
PWM.cleanup()
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_frequency_invalid_value_string(self):
|
||||
PWM.start("PWM0", 0)
|
||||
with pytest.raises(TypeError):
|
||||
PWM.set_frequency("PWM0", "11")
|
||||
PWM.cleanup()
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_freq_non_setup_key(self):
|
||||
with pytest.raises(RuntimeError):
|
||||
PWM.set_frequency("PWM0", 100)
|
||||
PWM.cleanup()
|
||||
|
||||
def test_pwm_freq_non_setup_key(self):
|
||||
with pytest.raises(ValueError):
|
||||
PWM.set_frequency("P9_15", 100)
|
||||
PWM.cleanup()
|
||||
|
||||
def test_stop_pwm(self):
|
||||
pass
|
||||
#PWM.start("PWM0", 1)
|
||||
#PWM.stop("PWM0")
|
||||
#assert os.path.exists('/sys/class/gpio/gpio68')
|
||||
#direction = open('/sys/class/gpio/gpio68/direction').read()
|
||||
#assert direction == 'out\n'
|
||||
#PWM.cleanup()
|
||||
|
@ -10,6 +10,10 @@ def teardown_module(module):
|
||||
|
||||
|
||||
class TestSoftpwmSetup:
|
||||
|
||||
def setup_method(self, test_method):
|
||||
PWM.cleanup()
|
||||
|
||||
def test_start_pwm(self):
|
||||
PWM.start("XIO-P7", 50, 10)
|
||||
base = GPIO.get_gpio_base() + 7
|
||||
|
11
test/test_utilities.py
Normal file
11
test/test_utilities.py
Normal 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)
|
Reference in New Issue
Block a user