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

14 Commits

Author SHA1 Message Date
3ff79d43e3 version bump to 0.3.3, cleaning up stuff left over in fixing #40, start of implementing #56 2017-01-28 05:41:05 +00:00
40381efa74 fixing issue in the readme where the clone command for the dtc compiler was missing .git 2017-01-28 04:30:48 +00:00
73ae207e16 Copied over 2 new pwm functions from @streamnsight to close #46. these 2 functions are untested, which is why i'm not updating the readme at the moment. 2017-01-28 04:16:12 +00:00
eafcf0bf69 fixing issue related to loading the SPI2 overlay, forcing use of the sample provided by NTC in their chip-dt-overlays deb package. 2017-01-28 02:34:04 +00:00
bf27e2feea final updates in the initial addition of debug printing. this should close #55 2017-01-28 02:09:14 +00:00
8221016c10 More updates to the library to add debug printing 2017-01-26 05:55:30 +00:00
bd7f667041 Start of global debug implementation to match the PWM code 2017-01-25 05:07:00 +00:00
8c3dab1ecc Fix and close #53. Start of implementation for #55 2017-01-24 05:23:04 +00:00
962049299a Merge pull request #52 from tryonlinux/master
Updated rpigpiomodule to chipgpiomodule so python3 compile works
2017-01-10 21:20:16 -06:00
10e7043269 Fix and close #51, I wasn't careful in swapping the module name. I thought the name was changed months ago, but eh, fixed now 2017-01-11 03:17:26 +00:00
3b2e334876 Updated rpigpiomodule to chipgpiomodule so python3 compile works 2017-01-10 21:18:44 -05:00
486cf73860 Fix and close #50, I really don't understand pointers because Python abstracts that all out for me and C does not. 2017-01-10 01:14:16 +00:00
5723bf15b3 Readme updates for callbacks to close #49 2017-01-08 20:45:16 +00:00
6972f352ae Fixes in LRADC.py for debug printing failing when using Python3. Updates to the README to detail running unit tests for either Python version. Ref #42 and #47 2017-01-06 04:11:12 +00:00
21 changed files with 478 additions and 215 deletions

View File

@ -1,3 +1,18 @@
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 0.3.0
---- ----
* Added setmode() function for GPIO to maintain compatibility with Raspberry Pi scripts, this function literally does nothing * Added setmode() function for GPIO to maintain compatibility with Raspberry Pi scripts, this function literally does nothing

View File

@ -42,9 +42,12 @@ CURRENT_SAMPLE_RATE_FILE = "/in_voltage_sampling_frequency"
RAW_VOLTAGE_CHAN0_FILE = "/in_voltage0_raw" RAW_VOLTAGE_CHAN0_FILE = "/in_voltage0_raw"
RAW_VOLTAGE_CHAN1_FILE = "/in_voltage1_raw" RAW_VOLTAGE_CHAN1_FILE = "/in_voltage1_raw"
def enable_debug(): def toggle_debug():
global DEBUG global DEBUG
DEBUG = True if DEBUG:
DEBUG = False
else:
DEBUG = True
def setup(rate=250): def setup(rate=250):
# First we determine if the device exists # First we determine if the device exists
@ -75,7 +78,7 @@ def get_scale_factor():
# Debug # Debug
if DEBUG: if DEBUG:
print("Current LRADC Scaling Factor: {0}").format(SCALE_FACTOR) print("lradc.get_scale_factor: {0}".format(SCALE_FACTOR))
return SCALE_FACTOR return SCALE_FACTOR
@ -91,7 +94,7 @@ def get_allowable_sample_rates():
global SAMPLE_RATES global SAMPLE_RATES
tmp = dat.strip().split(" ") tmp = dat.strip().split(" ")
for i in xrange(len(tmp)): for i in range(len(tmp)):
if "." in tmp[i]: if "." in tmp[i]:
tmp[i] = float(tmp[i]) tmp[i] = float(tmp[i])
else: else:
@ -100,9 +103,9 @@ def get_allowable_sample_rates():
# Debug # Debug
if DEBUG: if DEBUG:
print("Allowable Sampling Rates:") print("lradc.get_allowable_sample_rates:")
for rate in SAMPLE_RATES: for rate in SAMPLE_RATES:
print("{0}").format(rate) print("{0}".format(rate))
return tuple(SAMPLE_RATES) return tuple(SAMPLE_RATES)
@ -111,10 +114,6 @@ def set_sample_rate(rate):
if not DEVICE_EXIST: if not DEVICE_EXIST:
raise Exception("LRADC Device does not exist") raise Exception("LRADC Device does not exist")
# Debug
if DEBUG:
print("Setting Sample Rate to: {0}").format(rate)
# Check to see if the rates were gathered already # Check to see if the rates were gathered already
global SAMPLE_RATES global SAMPLE_RATES
if SAMPLE_RATES == []: if SAMPLE_RATES == []:
@ -124,6 +123,10 @@ def set_sample_rate(rate):
if rate not in SAMPLE_RATES: if rate not in SAMPLE_RATES:
raise ValueError("Input Rate an Acceptable Value") raise ValueError("Input Rate an Acceptable Value")
# Debug
if DEBUG:
print("lradc.set_sample_rate: {0}".format(rate))
# Write the rate # Write the rate
f = open(LRADC_BASE_DEVICE_FILE+CURRENT_SAMPLE_RATE_FILE,"w") f = open(LRADC_BASE_DEVICE_FILE+CURRENT_SAMPLE_RATE_FILE,"w")
mystr = "%.2f" % rate mystr = "%.2f" % rate
@ -153,7 +156,7 @@ def get_sample_rate():
# Debug # Debug
if DEBUG: if DEBUG:
print("Current Sampling Rate: {0}").format(dat) print("lradc.get_sample_rate: {0}".format(dat))
return dat return dat
@ -171,7 +174,7 @@ def get_chan0_raw():
# Debug # Debug
if DEBUG: if DEBUG:
print("CHAN0 RAW: {0}").format(dat) print("lradc.get_chan0_raw: {0}".format(dat))
return dat return dat
@ -189,7 +192,7 @@ def get_chan1_raw():
# Debug # Debug
if DEBUG: if DEBUG:
print("CHAN1 RAW: {0}").format(dat) print("lradc.get_chan1_raw: {0}".format(dat))
return dat return dat
@ -205,7 +208,7 @@ def get_chan0():
# Debug # Debug
if DEBUG: if DEBUG:
print("CHAN0: {0}").format(dat) print("lradc.get_chan0: {0}".format(dat))
return dat return dat
@ -221,7 +224,7 @@ def get_chan1():
# Debug # Debug
if DEBUG: if DEBUG:
print("CHAN1: {0}").format(dat) print("lradc.get_chan1: {0}".format(dat))
return dat return dat

View File

@ -24,6 +24,7 @@ import time
DEBUG = False DEBUG = False
OVERLAYINSTALLPATH = "/lib/firmware/chip_io" OVERLAYINSTALLPATH = "/lib/firmware/chip_io"
SPIINSTALLPATH = "/lib/firmware/nextthingco/chip"
OVERLAYCONFIGPATH = "/sys/kernel/config/device-tree/overlays" OVERLAYCONFIGPATH = "/sys/kernel/config/device-tree/overlays"
CUSTOMOVERLAYFILEPATH = "" CUSTOMOVERLAYFILEPATH = ""
@ -41,7 +42,7 @@ _LOADED = {
} }
_OVERLAYS = { _OVERLAYS = {
"SPI2" : "chip-spi2.dtbo", "SPI2" : "sample-spi.dtbo",
"PWM0" : "chip-pwm0.dtbo", "PWM0" : "chip-pwm0.dtbo",
"CUST" : "" "CUST" : ""
} }
@ -52,9 +53,12 @@ _FOLDERS = {
"CUST" : "chip-cust" "CUST" : "chip-cust"
} }
def enable_debug(): def toggle_debug():
global DEBUG global DEBUG
DEBUG = True if DEBUG:
DEBUG = False
else:
DEBUG = True
def get_spi_loaded(): def get_spi_loaded():
""" """
@ -157,7 +161,11 @@ def load(overlay, path=""):
# SET UP THE OVERLAY PATH FOR OUR USE # SET UP THE OVERLAY PATH FOR OUR USE
if overlay.upper() != "CUST": if overlay.upper() != "CUST":
opath = OVERLAYINSTALLPATH + "/" + _OVERLAYS[overlay.upper()] opath = OVERLAYINSTALLPATH
# IF THE OVERLAY IS SPI, USE THE NTC PATH
if overlay.upper() == "SPI2":
opath = SPIINSTALLPATH
opath += "/" + _OVERLAYS[overlay.upper()]
else: else:
opath = path opath = path
if DEBUG: if DEBUG:

View File

@ -28,6 +28,16 @@ import subprocess
import glob import glob
import re import re
# Global Variables
DEBUG = False
def toggle_debug():
global DEBUG
if DEBUG:
DEBUG = False
else:
DEBUG = True
# Set the 1.8V-pin on the CHIP U13-header to given voltage # Set the 1.8V-pin on the CHIP U13-header to given voltage
# Return False on error # Return False on error
def set_1v8_pin_voltage(voltage): def set_1v8_pin_voltage(voltage):
@ -35,10 +45,16 @@ def set_1v8_pin_voltage(voltage):
return False return False
if voltage < 1.8 or voltage > 3.3: if voltage < 1.8 or voltage > 3.3:
return False return False
if DEBUG:
print("Setting 1.8V Pin voltage: {0}".format(voltage))
voltage=int(round((voltage - 1.8) / 0.1)) << 4 voltage=int(round((voltage - 1.8) / 0.1)) << 4
if subprocess.call(["/usr/sbin/i2cset", "-f", "-y" ,"0", "0x34", "0x90", "0x03"]): if subprocess.call(["/usr/sbin/i2cset", "-f", "-y" ,"0", "0x34", "0x90", "0x03"]):
if DEBUG:
print("Pin enable command failed")
return False return False
if subprocess.call(["/usr/sbin/i2cset", "-f", "-y", "0", "0x34", "0x91", str(voltage)]): if subprocess.call(["/usr/sbin/i2cset", "-f", "-y", "0", "0x34", "0x91", str(voltage)]):
if DEBUG:
print("Pin set voltage command failed")
return False return False
return True return True
@ -49,10 +65,14 @@ def get_1v8_pin_voltage():
output=p.communicate()[0].decode("utf-8").strip() output=p.communicate()[0].decode("utf-8").strip()
#Not configured as an output #Not configured as an output
if output != "0x03": if output != "0x03":
if DEBUG:
print("1.8V Pin is currently disabled")
return False return False
p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x91"], stdout=subprocess.PIPE) p=subprocess.Popen(["/usr/sbin/i2cget", "-f", "-y", "0", "0x34", "0x91"], stdout=subprocess.PIPE)
output=p.communicate()[0].decode("utf-8").strip() output=p.communicate()[0].decode("utf-8").strip()
voltage=round((int(output, 16) >> 4) * 0.1 + 1.8, 1) voltage=round((int(output, 16) >> 4) * 0.1 + 1.8, 1)
if DEBUG:
print("Current 1.8V Pin voltage: {0}".format(voltage))
return voltage return voltage
# Enable 1.8V Pin on CHIP U13 Header # Enable 1.8V Pin on CHIP U13 Header
@ -61,6 +81,8 @@ def enable_1v8_pin():
# Disable 1.8V Pin on CHIP U13 Header # Disable 1.8V Pin on CHIP U13 Header
def disable_1v8_pin(): def disable_1v8_pin():
if 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 # 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 # First we have to write 0x05 to AXP-209 Register 0x91
subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x91 0x05', shell=True) subprocess.call('/usr/sbin/i2cset -f -y 0 0x34 0x91 0x05', shell=True)
@ -69,6 +91,8 @@ def disable_1v8_pin():
# Unexport All # Unexport All
def unexport_all(): def unexport_all():
if DEBUG:
print("Unexporting all the pins")
gpios = glob.glob("/sys/class/gpio/gpio[0-9]*") gpios = glob.glob("/sys/class/gpio/gpio[0-9]*")
for g in gpios: for g in gpios:
tmp = g.split("/") tmp = g.split("/")

View File

@ -9,8 +9,8 @@ Manual::
For Python2.7:: For Python2.7::
sudo apt-get update sudo apt-get update
sudo apt-get install git build-essential python-dev python-pip flex bison -y sudo apt-get install git build-essential python-dev python-pip flex bison chip-dt-overlays -y
git clone https://github.com/atenart/dtc git clone https://github.com/atenart/dtc.git
cd dtc cd dtc
make make
sudo make install PREFIX=/usr sudo make install PREFIX=/usr
@ -24,8 +24,8 @@ For Python2.7::
For Python3:: For Python3::
sudo apt-get update sudo apt-get update
sudo apt-get install git build-essential python3-dev python3-pip flex bison -y sudo apt-get install git build-essential python3-dev python3-pip flex bison chip-dt-overlays -y
git clone https://github.com/atenart/dtc git clone https://github.com/atenart/dtc.git
cd dtc cd dtc
make make
sudo make install PREFIX=/usr sudo make install PREFIX=/usr
@ -169,6 +169,13 @@ You can also refer to the bin based upon its alternate name::
GPIO.setup("GPIO1", GPIO.IN) GPIO.setup("GPIO1", GPIO.IN)
**GPIO Debug**
Debug can be enabled/disabled by the following command::
# Enable Debug
GPIO.toggle_debug()
**GPIO Output** **GPIO Output**
Setup the pin for output, and write GPIO.HIGH or GPIO.LOW. Or you can use 1 or 0.:: Setup the pin for output, and write GPIO.HIGH or GPIO.LOW. Or you can use 1 or 0.::
@ -206,7 +213,21 @@ Detecting events::
if GPIO.event_detected("XIO-P0"): if GPIO.event_detected("XIO-P0"):
print "event detected!" print "event detected!"
CHIP_IO can also handle adding callback functions on any pin that supports edge detection. CHIP_IO can also handle adding callback functions on any pin that supports edge detection.::
def mycallback(channel):
print("we hit the edge we want")
GPIO.setup("GPIO3", GPIO.IN)
# Add Callback: Falling Edge
GPIO.add_event_callback("GPIO3", GPIO.FALLING, mycallback)
# Add Callback: Rising Edge
GPIO.add_event_callback("GPIO3", GPIO.RISING, mycallback)
# Add Callback: Both Edges
GPIO.add_event_callback("GPIO3", GPIO.BOTH, mycallback)
# Remove callback
GPIO.remove_event_detect("GPIO3")
**GPIO Cleanup** **GPIO Cleanup**
@ -222,6 +243,8 @@ To clean up the GPIO when done, do the following::
Hardware PWM requires a DTB Overlay loaded on the CHIP to allow the kernel to know there is a PWM device available to use. Hardware PWM requires a DTB Overlay loaded on the CHIP to allow the kernel to know there is a PWM device available to use.
:: ::
import CHIP_IO.PWM as PWM import CHIP_IO.PWM as PWM
# Enable/Disable Debug
PWM.toggle_debug()
#PWM.start(channel, duty, freq=2000, polarity=0) #PWM.start(channel, duty, freq=2000, polarity=0)
#duty values are valid 0 (off) to 100 (on) #duty values are valid 0 (off) to 100 (on)
PWM.start("PWM0", 50) PWM.start("PWM0", 50)
@ -236,6 +259,8 @@ Hardware PWM requires a DTB Overlay loaded on the CHIP to allow the kernel to kn
**SOFTPWM**:: **SOFTPWM**::
import CHIP_IO.SOFTPWM as SPWM import CHIP_IO.SOFTPWM as SPWM
# Enable/Disable Debug
SPWM.toggle_debug()
#SPWM.start(channel, duty, freq=2000, polarity=0) #SPWM.start(channel, duty, freq=2000, polarity=0)
#duty values are valid 0 (off) to 100 (on) #duty values are valid 0 (off) to 100 (on)
#you can choose any pin #you can choose any pin
@ -261,8 +286,8 @@ The LRADC was enabled in the 4.4.13-ntc-mlc. This is a 6 bit ADC that is 2 Volt
Sample code below details how to talk to the LRADC.:: Sample code below details how to talk to the LRADC.::
import CHIP_IO.LRADC as ADC import CHIP_IO.LRADC as ADC
# Enable Debug # Enable/Disable Debug
ADC.enable_debug() ADC.toggle_debug()
# Check to see if the LRADC Device exists # Check to see if the LRADC Device exists
# Returns True/False # Returns True/False
ADC.get_device_exists() ADC.get_device_exists()
@ -296,8 +321,8 @@ PWM0, SPI2, I2C1, CUST
Only one of each type of overlay can be loaded at a time, but all three options can be loaded simultaneously. So you can have SPI2 and I2C1 without PWM0, but you cannot have SPI2 loaded twice. Only one of each type of overlay can be loaded at a time, but all three options can be loaded simultaneously. So you can have SPI2 and I2C1 without PWM0, but you cannot have SPI2 loaded twice.
:: ::
import CHIP_IO.OverlayManager as OM import CHIP_IO.OverlayManager as OM
# The enable_debug() function turns on debug printing # The toggle_debug() function turns on/off debug printing
#OM.enable_debug() #OM.toggle_debug()
# To load an overlay, feed in the name to load() # To load an overlay, feed in the name to load()
OM.load("PWM0") OM.load("PWM0")
# To verify the overlay was properly loaded, the get_ functions return booleans # To verify the overlay was properly loaded, the get_ functions return booleans
@ -326,6 +351,8 @@ CHIP_IO now supports the ability to enable and disable the 1.8V port on U13. Th
To use the utilities, here is sample code:: To use the utilities, here is sample code::
import CHIP_IO.Utilities as UT import CHIP_IO.Utilities as UT
# Enable/Disable Debug
UT.toggle_debug()
# Enable 1.8V Output # Enable 1.8V Output
UT.enable_1v8_pin() UT.enable_1v8_pin()
# Set 2.0V Output # Set 2.0V Output
@ -345,11 +372,19 @@ To use the utilities, here is sample code::
Install py.test to run the tests. You'll also need the python compiler package for py.test.:: Install py.test to run the tests. You'll also need the python compiler package for py.test.::
# Python 2.7
sudo apt-get install python-pytest 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.::
# If only one version of Python is installed
sudo py.test sudo py.test
# If more than one version of Python
cd test
sudo python2 -m pytest
sudo python3 -m pytest
**Credits** **Credits**

View File

@ -6,7 +6,6 @@ import sys
def compile(): def compile():
print("Compiling DTS Files") print("Compiling DTS Files")
call(["dtc", "-O", "dtb", "-o", "overlays/chip-spi2.dtbo", "-b", "o", "-@", "overlays/chip-spi2.dts"])
call(["dtc", "-O", "dtb", "-o", "overlays/chip-pwm0.dtbo", "-b", "o", "-@", "overlays/chip-pwm0.dts"]) call(["dtc", "-O", "dtb", "-o", "overlays/chip-pwm0.dtbo", "-b", "o", "-@", "overlays/chip-pwm0.dts"])
def copy(): def copy():
@ -20,5 +19,4 @@ def copy():
for fl in glob.glob(overlay_path+"/chip-*-.dtbo"): for fl in glob.glob(overlay_path+"/chip-*-.dtbo"):
os.remove(fl) os.remove(fl)
print("Moving DTBO files to "+overlay_path) print("Moving DTBO files to "+overlay_path)
shutil.move("overlays/chip-spi2.dtbo", overlay_path+"/chip-spi2.dtbo")
shutil.move("overlays/chip-pwm0.dtbo", overlay_path+"/chip-pwm0.dtbo") shutil.move("overlays/chip-pwm0.dtbo", overlay_path+"/chip-pwm0.dtbo")

View File

@ -1,93 +0,0 @@
/*
* Copyright 2016, Robert Wolterman
* This file is an amalgamation of stuff from Kolja Windeler, Maxime Ripard, and Renzo.
*
* This file is dual-licensed: you can use it either under the terms
* of the GPL or the X11 license, at your option. Note that this dual
* licensing only applies to this file, and not this project as a
* whole.
*
* a) This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Or, alternatively,
*
* b) Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/dts-v1/;
/plugin/;
/ {
compatible = "nextthing,chip", "allwinner,sun5i-r8";
/* activate the gpio for interrupt */
fragment@0 {
target-path = <&pio>;
__overlay__ {
chip_spi2_pins: spi2@0 {
allwinner,pins = "PE1", "PE2", "PE3";
allwinner,function = "spi2";
allwinner,drive = "0"; //<SUN4I_PINCTRL_10_MA>;
allwinner,pull = "0"; //<SUN4I_PINCTRL_NO_PULL>;
};
chip_spi2_cs0_pins: spi2_cs0@0 {
allwinner,pins = "PE0";
allwinner,function = "spi2";
allwinner,drive = "0"; //<SUN4I_PINCTRL_10_MA>;
allwinner,pull = "0"; //<SUN4I_PINCTRL_NO_PULL>;
};
};
};
/*
* Enable our SPI device, with an spidev device connected
* to it
*/
fragment@1 {
target = <&spi2>;
__overlay__ {
#address-cells = <1>;
#size-cells = <0>;
pinctrl-names = "default";
pinctrl-0 = <&chip_spi2_pins>, <&chip_spi2_cs0_pins>;
status = "okay";
spi2@0 {
compatible = "rohm,dh2228fv";
reg = <0>;
spi-max-frequency = <24000000>;
};
};
};
};

View File

@ -20,7 +20,7 @@ classifiers = ['Development Status :: 3 - Alpha',
'Topic :: System :: Hardware'] 'Topic :: System :: Hardware']
setup(name = 'CHIP_IO', setup(name = 'CHIP_IO',
version = '0.3.0', version = '0.3.3',
author = 'Robert Wolterman', author = 'Robert Wolterman',
author_email = 'robert.wolterman@gmail.com', author_email = 'robert.wolterman@gmail.com',
description = 'A module to control CHIP IO channels', description = 'A module to control CHIP IO channels',

View File

@ -47,9 +47,6 @@ SOFTWARE.
// Global variables // Global variables
int pwm_initialized = 0; int pwm_initialized = 0;
int DEBUG = 0;
//int ENABLE = 1;
//int DISABLE = 0;
// pwm devices (future chip pro use) // pwm devices (future chip pro use)
struct pwm_dev struct pwm_dev
@ -113,7 +110,7 @@ int initialize_pwm(void)
int gpio = 0; int gpio = 0;
if (DEBUG) if (DEBUG)
printf(" ** EXPORTING PWM0 **\n"); printf(" ** initialize_pwm **\n");
if ((fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY)) < 0) if ((fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY)) < 0)
{ {
return -1; return -1;
@ -121,7 +118,7 @@ int initialize_pwm(void)
len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio); len = snprintf(str_gpio, sizeof(str_gpio), "%d", gpio); BUF2SMALL(str_gpio);
ssize_t s = write(fd, str_gpio, len); ASSRT(s == len); ssize_t s = write(fd, str_gpio, len); ASSRT(s == len);
if (DEBUG) if (DEBUG)
printf(" ** IN initialize_pwm: s = %d, len = %d\n", s, len); printf(" ** initialize_pwm: export pin: s = %d, len = %d\n", s, len);
close(fd); close(fd);
pwm_initialized = 1; pwm_initialized = 1;
@ -150,17 +147,16 @@ int pwm_set_frequency(const char *key, float freq) {
period_ns = (unsigned long)(1e9 / freq); period_ns = (unsigned long)(1e9 / freq);
if (pwm->enable) { if (pwm->enable) {
if (DEBUG)
printf(" ** IN pwm_set_frequency: pwm_initialized = %d\n", pwm_initialized);
if (period_ns != pwm->period_ns) { if (period_ns != pwm->period_ns) {
pwm->period_ns = period_ns; pwm->period_ns = period_ns;
len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%lu", period_ns); BUF2SMALL(buffer);
if (DEBUG)
printf(" ** pwm_set_frequency: buffer: %s\n", buffer);
ssize_t s = write(pwm->period_fd, buffer, len); //ASSRT(s == len); ssize_t s = write(pwm->period_fd, buffer, len); //ASSRT(s == len);
if (DEBUG) if (DEBUG) {
printf(" ** IN pwm_set_frequency: s = %d, len = %d\n", s, len); 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) { if (s != len) {
rtnval = -1; rtnval = -1;
} else { } else {
@ -176,6 +172,66 @@ int pwm_set_frequency(const char *key, float freq) {
return rtnval; return rtnval;
} }
int pwm_set_period_ns(const char *key, unsigned long period_ns) {
int len;
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); //ASSRT(s == len);
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) {
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 pwm_set_polarity(const char *key, int polarity) {
int len; int len;
int rtnval = -1; int rtnval = -1;
@ -193,8 +249,6 @@ int pwm_set_polarity(const char *key, int polarity) {
} }
if (pwm->enable) { if (pwm->enable) {
if (DEBUG)
printf(" ** IN pwm_set_polarity: pwm_initialized = %d\n", pwm_initialized);
if (polarity == 0) { if (polarity == 0) {
len = snprintf(buffer, sizeof(buffer), "%s", "normal"); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%s", "normal"); BUF2SMALL(buffer);
} }
@ -202,11 +256,12 @@ int pwm_set_polarity(const char *key, int polarity) {
{ {
len = snprintf(buffer, sizeof(buffer), "%s", "inverted"); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%s", "inverted"); BUF2SMALL(buffer);
} }
if (DEBUG)
printf(" ** pwm_set_poliarity: buffer: %s\n", buffer);
ssize_t s = write(pwm->polarity_fd, buffer, len); //ASSRT(s == len); ssize_t s = write(pwm->polarity_fd, buffer, len); //ASSRT(s == len);
if (DEBUG) if (DEBUG) {
printf(" ** IN pwm_set_polarity: s = %d, len = %d\n", s, len); 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) { if (s != len) {
rtnval = -1; rtnval = -1;
} else { } else {
@ -237,14 +292,13 @@ int pwm_set_duty_cycle(const char *key, float duty) {
pwm->duty = (unsigned long)(pwm->period_ns * (duty / 100.0)); pwm->duty = (unsigned long)(pwm->period_ns * (duty / 100.0));
if (pwm->enable) { if (pwm->enable) {
if (DEBUG)
printf(" ** IN pwm_set_duty_cycle: pwm_initialized = %d\n", pwm_initialized);
len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%lu", pwm->duty); BUF2SMALL(buffer);
if (DEBUG)
printf(" ** pwm_set_duty_cycle: buffer: %s\n", buffer);
ssize_t s = write(pwm->duty_fd, buffer, len); //ASSRT(s == len); ssize_t s = write(pwm->duty_fd, buffer, len); //ASSRT(s == len);
if (DEBUG) if (DEBUG) {
printf(" ** IN pwm_set_duty_cycle: s = %d, len = %d\n", s, len); 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) { if (s != len) {
rtnval = -1; rtnval = -1;
} else { } else {
@ -257,6 +311,44 @@ int pwm_set_duty_cycle(const char *key, float duty) {
return rtnval; return rtnval;
} }
int pwm_set_pulse_width_ns(const char *key, unsigned long pulse_width_ns) {
int len;
int rtnval = -1;
char buffer[80];
struct pwm_exp *pwm;
pwm = lookup_exported_pwm(key);
if (pwm == NULL) {
return rtnval;
}
if (pulse_width_ns < 0 || pulse_width_ns > pwm->period_ns)
return rtnval;
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); //ASSRT(s == len);
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) {
rtnval = -1;
} else {
rtnval = 1;
}
} else {
rtnval = 0;
}
return rtnval;
}
int pwm_set_enable(const char *key, int enable) int pwm_set_enable(const char *key, int enable)
{ {
int len; int len;
@ -266,7 +358,7 @@ int pwm_set_enable(const char *key, int enable)
if (enable != 0 && enable != 1) { if (enable != 0 && enable != 1) {
if (DEBUG) if (DEBUG)
printf(" ** INVALID ENABLE OPTION, NEEDS TO BE EITHER 0 OR 1! **\n"); printf(" ** pwm_set_enable: enable needs to be 0 or 1! **\n");
return rtnval; return rtnval;
} }
@ -274,7 +366,7 @@ int pwm_set_enable(const char *key, int enable)
if (pwm == NULL) { if (pwm == NULL) {
if (DEBUG) if (DEBUG)
printf(" ** SOMETHING BAD HAPPEND IN pwm_set_enable, WE'RE EXITING WITH -1 NOW! **\n"); printf(" ** pwm_set_enable: pwm struct is null **\n");
return rtnval; return rtnval;
} }
@ -282,15 +374,15 @@ int pwm_set_enable(const char *key, int enable)
len = snprintf(buffer, sizeof(buffer), "%d", enable); BUF2SMALL(buffer); len = snprintf(buffer, sizeof(buffer), "%d", enable); BUF2SMALL(buffer);
ssize_t s = write(pwm->enable_fd, buffer, len); //ASSRT(s == len); ssize_t s = write(pwm->enable_fd, buffer, len); //ASSRT(s == len);
if (DEBUG) { if (DEBUG) {
printf(" ** IN pwm_set_enable: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_set_enable: pwm_initialized = %d\n", pwm_initialized);
printf(" ** pwm_set_enable: buffer: %s\n", buffer); printf(" ** pwm_set_enable: buffer: %s\n", buffer);
printf(" ** IN pwm_set_enable: s = %d, len = %d\n", s, len); printf(" ** pwm_set_enable: s = %d, len = %d\n", s, len);
} }
if (s == len) if (s == len)
{ {
if (DEBUG) if (DEBUG)
printf(" ** SETTING pwm->enable to %d\n", enable); printf(" ** pwm_set_enable: pwm->enable to %d\n", enable);
pwm->enable = enable; pwm->enable = enable;
rtnval = 0; rtnval = 0;
} else { } else {
@ -311,16 +403,16 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
struct pwm_exp *new_pwm, *pwm; struct pwm_exp *new_pwm, *pwm;
if (DEBUG) if (DEBUG)
printf(" ** IN pwm_start: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_start: pwm_initialized = %d\n", pwm_initialized);
if(!pwm_initialized) { if(!pwm_initialized) {
initialize_pwm(); initialize_pwm();
} else { } else {
if (DEBUG) if (DEBUG)
printf(" ** ALREADY INITIALIZED, CALLING CLEANUP TO START FRESH **"); printf(" ** pwm_start: pwm already initialized, cleaning up **");
pwm_cleanup(); pwm_cleanup();
} }
if (DEBUG) if (DEBUG)
printf(" ** IN pwm_start: pwm_initialized = %d\n", pwm_initialized); printf(" ** pwm_start: pwm_initialized = %d\n", pwm_initialized);
//setup the pwm base path, the chip only has one pwm //setup the pwm base path, the chip only has one pwm
snprintf(pwm_base_path, sizeof(pwm_base_path), "/sys/class/pwm/pwmchip0/pwm%d", 0); BUF2SMALL(pwm_base_path); snprintf(pwm_base_path, sizeof(pwm_base_path), "/sys/class/pwm/pwmchip0/pwm%d", 0); BUF2SMALL(pwm_base_path);
@ -332,11 +424,11 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
snprintf(polarity_path, sizeof(polarity_path), "%s/polarity", pwm_base_path); BUF2SMALL(polarity_path); snprintf(polarity_path, sizeof(polarity_path), "%s/polarity", pwm_base_path); BUF2SMALL(polarity_path);
if (DEBUG) { if (DEBUG) {
printf(" ** IN pwm_start: pwm_base_path: %s\n", pwm_base_path); printf(" ** pwm_start: pwm_base_path: %s\n", pwm_base_path);
printf(" ** IN pwm_start: enable_path: %s\n", enable_path); printf(" ** pwm_start: enable_path: %s\n", enable_path);
printf(" ** IN pwm_start: period_path: %s\n", period_path); printf(" ** pwm_start: period_path: %s\n", period_path);
printf(" ** IN pwm_start: duty_path: %s\n", duty_path); printf(" ** pwm_start: duty_path: %s\n", duty_path);
printf(" **IN pwm_start: polarity_path: %s\n", polarity_path); printf(" ** pwm_start: polarity_path: %s\n", polarity_path);
} }
//add period and duty fd to pwm list //add period and duty fd to pwm list
@ -370,7 +462,7 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
} }
if (DEBUG) if (DEBUG)
printf(" ** IN pwm_start: IF WE MAKE IT HERE, THE FILES WERE SUCCESSFULLY OPEN **\n"); printf(" ** pwm_start: sysfs files opened successfully **\n");
strncpy(new_pwm->key, key, KEYLEN); /* can leave string unterminated */ strncpy(new_pwm->key, key, KEYLEN); /* can leave string unterminated */
new_pwm->key[KEYLEN] = '\0'; /* terminate string */ new_pwm->key[KEYLEN] = '\0'; /* terminate string */
new_pwm->period_fd = period_fd; new_pwm->period_fd = period_fd;
@ -393,13 +485,17 @@ int pwm_start(const char *key, float duty, float freq, int polarity)
int rtnval = 0; int rtnval = 0;
rtnval = pwm_set_enable(key, ENABLE); rtnval = pwm_set_enable(key, ENABLE);
rtnval = 0; // Fix for issue #53
rtnval = pwm_set_frequency(key, freq); if (rtnval != -1) {
rtnval = 0; rtnval = 0;
//rtnval = pwm_set_polarity(key, polarity); rtnval = pwm_set_frequency(key, freq);
//rtnval = 0; if (rtnval != -1) {
rtnval = pwm_set_duty_cycle(key, duty); rtnval = 0;
//rtnval = pwm_set_polarity(key, polarity);
//rtnval = 0;
rtnval = pwm_set_duty_cycle(key, duty);
}
}
return rtnval; return rtnval;
} }
@ -433,6 +529,9 @@ int pwm_disable(const char *key)
{ {
if (strcmp(pwm->key, key) == 0) if (strcmp(pwm->key, key) == 0)
{ {
if (DEBUG) {
printf(" ** pwm_disable: freeing memory %s\n", key);
}
//close the fd //close the fd
close(pwm->enable_fd); close(pwm->enable_fd);
close(pwm->period_fd); close(pwm->period_fd);
@ -464,11 +563,3 @@ void pwm_cleanup(void)
} }
} }
void pwm_toggle_debug(void)
{
if (DEBUG) {
DEBUG = 0;
} else {
DEBUG = 1;
}
}

View File

@ -32,7 +32,9 @@ SOFTWARE.
int pwm_start(const char *key, float duty, float freq, int polarity); int pwm_start(const char *key, float duty, float freq, int polarity);
int pwm_disable(const char *key); int pwm_disable(const char *key);
int pwm_set_frequency(const char *key, float freq); 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_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); int pwm_set_enable(const char *key, int enable);
void pwm_cleanup(void); void pwm_cleanup(void);
void pwm_toggle_debug(void);

View File

@ -96,6 +96,8 @@ int softpwm_set_frequency(const char *key, float freq) {
return -1; return -1;
} }
if (DEBUG)
printf(" ** softpwm_set_frequency: %f **\n", freq);
pthread_mutex_lock(pwm->params_lock); pthread_mutex_lock(pwm->params_lock);
pwm->params.freq = freq; pwm->params.freq = freq;
pthread_mutex_unlock(pwm->params_lock); pthread_mutex_unlock(pwm->params_lock);
@ -116,6 +118,8 @@ int softpwm_set_polarity(const char *key, int polarity) {
return -1; return -1;
} }
if (DEBUG)
printf(" ** softpwm_set_polarity: %d **\n", polarity);
pthread_mutex_lock(pwm->params_lock); pthread_mutex_lock(pwm->params_lock);
pwm->params.polarity = polarity; pwm->params.polarity = polarity;
pthread_mutex_unlock(pwm->params_lock); pthread_mutex_unlock(pwm->params_lock);
@ -135,6 +139,8 @@ int softpwm_set_duty_cycle(const char *key, float duty) {;
return -1; return -1;
} }
if (DEBUG)
printf(" ** softpwm_set_duty_cycle: %f **\n", duty);
pthread_mutex_lock(pwm->params_lock); pthread_mutex_lock(pwm->params_lock);
pwm->params.duty = duty; pwm->params.duty = duty;
pthread_mutex_unlock(pwm->params_lock); pthread_mutex_unlock(pwm->params_lock);
@ -194,7 +200,6 @@ void *softpwm_thread_toggle(void *arg)
if (enabled_local) if (enabled_local)
{ {
/* Force 0 duty cycle to be 0 */ /* Force 0 duty cycle to be 0 */
if (duty_local != 0) if (duty_local != 0)
{ {
@ -238,16 +243,27 @@ int softpwm_start(const char *key, float duty, float freq, int polarity)
int gpio; int gpio;
int ret; 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; return -1;
}
if (gpio_export(gpio) < 0) { if (gpio_export(gpio) < 0) {
char err[2000]; char err[2000];
snprintf(err, sizeof(err), "Error setting up softpwm on pin %d, maybe already exported? (%s)", gpio, get_error_msg()); snprintf(err, sizeof(err), "Error setting up softpwm on pin %d, maybe already exported? (%s)", gpio, get_error_msg());
add_error_msg(err); add_error_msg(err);
return -1; return -1;
} }
if (gpio_set_direction(gpio, OUTPUT) < 0)
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; return -1;
}
// add to list // add to list
new_pwm = malloc(sizeof(struct softpwm)); ASSRT(new_pwm != NULL); new_pwm = malloc(sizeof(struct softpwm)); ASSRT(new_pwm != NULL);
@ -279,12 +295,16 @@ int softpwm_start(const char *key, float duty, float freq, int polarity)
} }
pthread_mutex_unlock(new_params_lock); 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_duty_cycle(new_pwm->key, duty) == 0);
ASSRT(softpwm_set_frequency(new_pwm->key, freq) == 0); ASSRT(softpwm_set_frequency(new_pwm->key, freq) == 0);
ASSRT(softpwm_set_polarity(new_pwm->key, polarity) == 0); ASSRT(softpwm_set_polarity(new_pwm->key, polarity) == 0);
pthread_mutex_lock(new_params_lock); pthread_mutex_lock(new_params_lock);
// create thread for pwm // create thread for pwm
if (DEBUG)
printf(" ** softpwm_enable: creating thread **\n");
ret = pthread_create(&new_thread, NULL, softpwm_thread_toggle, (void *)new_pwm); ret = pthread_create(&new_thread, NULL, softpwm_thread_toggle, (void *)new_pwm);
ASSRT(ret == 0); ASSRT(ret == 0);
@ -299,17 +319,23 @@ int softpwm_disable(const char *key)
{ {
struct softpwm *pwm, *temp, *prev_pwm = NULL; struct softpwm *pwm, *temp, *prev_pwm = NULL;
if (DEBUG)
printf(" ** in softpwm_disable **\n");
// remove from list // remove from list
pwm = exported_pwms; pwm = exported_pwms;
while (pwm != NULL) while (pwm != NULL)
{ {
if (strcmp(pwm->key, key) == 0) if (strcmp(pwm->key, key) == 0)
{ {
if (DEBUG)
printf(" ** softpwm_disable: found pin **\n");
pthread_mutex_lock(pwm->params_lock); pthread_mutex_lock(pwm->params_lock);
pwm->params.stop_flag = true; pwm->params.stop_flag = true;
pthread_mutex_unlock(pwm->params_lock); pthread_mutex_unlock(pwm->params_lock);
pthread_join(pwm->thread, NULL); /* wait for thread to exit */ pthread_join(pwm->thread, NULL); /* wait for thread to exit */
if (DEBUG)
printf(" ** softpwm_disable: unexporting %d **\n", pwm->gpio);
gpio_unexport(pwm->gpio); gpio_unexport(pwm->gpio);
if (prev_pwm == NULL) if (prev_pwm == NULL)

View File

@ -49,6 +49,9 @@ SOFTWARE.
int setup_error = 0; int setup_error = 0;
int module_setup = 0; int module_setup = 0;
// Library Debug
int DEBUG = 0;
pins_t pins_info[] = { pins_t pins_info[] = {
{ "GND", "GND", "U13_1", -1, BASE_METHOD_AS_IS, -1, -1, SPWM_DISABLED}, { "GND", "GND", "U13_1", -1, BASE_METHOD_AS_IS, -1, -1, SPWM_DISABLED},
{ "CHG-IN", "CHG-IN", "U13_2", -1, BASE_METHOD_AS_IS, -1, -1, SPWM_DISABLED}, { "CHG-IN", "CHG-IN", "U13_2", -1, BASE_METHOD_AS_IS, -1, -1, SPWM_DISABLED},
@ -214,6 +217,14 @@ int get_xio_base(void)
return xio_base_address; return xio_base_address;
} /* get_xio_base */ } /* get_xio_base */
void toggle_debug(void)
{
if (DEBUG) {
DEBUG = 0;
} else {
DEBUG = 1;
}
}
int gpio_number(pins_t *pin) int gpio_number(pins_t *pin)
{ {
@ -351,12 +362,16 @@ int get_pwm_key_by_name(const char *name, char *key)
pins_t *p; pins_t *p;
for (p = pins_info; p->name != NULL; ++p) { for (p = pins_info; p->name != NULL; ++p) {
if (strcmp(p->name, name) == 0) { if (strcmp(p->name, name) == 0) {
printf("## FOUND PWM KEY, VALIDATING MUX MODE ##\n"); if (DEBUG) {
printf(" ** get_pwm_key_by_name: FOUND PWM KEY, VALIDATING MUX MODE **\n");
}
//validate it's a valid pwm pin //validate it's a valid pwm pin
if (p->pwm_mux_mode == -1) if (p->pwm_mux_mode == -1)
return 0; return 0;
printf("## PWM KEY IS VALID ##\n"); if (DEBUG) {
printf(" ** get_pwm_key_by_name: PWM KEY IS VALID ##\n");
}
strncpy(key, p->key, 7); strncpy(key, p->key, 7);
key[7] = '\0'; key[7] = '\0';
return 1; return 1;

View File

@ -86,6 +86,7 @@ typedef struct dyn_int_array_s dyn_int_array_t;
int setup_error; int setup_error;
int module_setup; int module_setup;
int DEBUG;
int get_xio_base(void); int get_xio_base(void);
int gpio_number(pins_t *pin); int gpio_number(pins_t *pin);
@ -110,3 +111,4 @@ void dyn_int_array_delete(dyn_int_array_t **in_array);
void clear_error_msg(void); void clear_error_msg(void);
char *get_error_msg(void); char *get_error_msg(void);
void add_error_msg(char *msg); void add_error_msg(char *msg);
void toggle_debug(void);

View File

@ -84,7 +84,10 @@ void define_constants(PyObject *module)
bcm = Py_BuildValue("i", BCM); bcm = Py_BuildValue("i", BCM);
PyModule_AddObject(module, "BCM", bcm); PyModule_AddObject(module, "BCM", bcm);
module_debug = Py_BuildValue("i", DEBUG ? Py_True: Py_False);
PyModule_AddObject(module, "DEBUG", module_debug);
version = Py_BuildValue("s", "0.3.0"); version = Py_BuildValue("s", "0.3.3");
PyModule_AddObject(module, "VERSION", version); PyModule_AddObject(module, "VERSION", version);
} }

View File

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

View File

@ -93,6 +93,9 @@ int gpio_export(int gpio)
char str_gpio[80]; char str_gpio[80];
struct gpio_exp *new_gpio, *g; struct gpio_exp *new_gpio, *g;
if (DEBUG)
printf(" ** gpio_export **\n");
snprintf(filename, sizeof(filename), "/sys/class/gpio/export"); BUF2SMALL(filename); snprintf(filename, sizeof(filename), "/sys/class/gpio/export"); BUF2SMALL(filename);
if ((fd = open(filename, O_WRONLY)) < 0) if ((fd = open(filename, O_WRONLY)) < 0)
@ -115,6 +118,8 @@ int gpio_export(int gpio)
} }
// add to list // 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 = malloc(sizeof(struct gpio_exp)); ASSRT(new_gpio != NULL);
new_gpio->gpio = gpio; new_gpio->gpio = gpio;
@ -217,6 +222,8 @@ int open_value_file(int gpio)
// Changed this to open Read/Write to prevent a ton of file open/closes from happening when using // Changed this to open Read/Write to prevent a ton of file open/closes from happening when using
// the GPIO for SOFTPWM // the GPIO for SOFTPWM
if (DEBUG)
printf(" ** open_value_file **\n");
if ((fd = open(filename, O_RDWR | O_NONBLOCK)) < 0) { if ((fd = open(filename, O_RDWR | O_NONBLOCK)) < 0) {
char err[256]; char err[256];
snprintf(err, sizeof(err), "open_value_file: could not open '%s' (%s)", filename, strerror(errno)); snprintf(err, sizeof(err), "open_value_file: could not open '%s' (%s)", filename, strerror(errno));
@ -236,6 +243,8 @@ int open_edge_file(int gpio)
// create file descriptor of value file // create file descriptor of value file
snprintf(filename, sizeof(filename), "/sys/class/gpio/gpio%d/edge", gpio); BUF2SMALL(filename); 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) { if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) < 0) {
char err[256]; char err[256];
snprintf(err, sizeof(err), "open_edge_file: could not open '%s' (%s)", filename, strerror(errno)); snprintf(err, sizeof(err), "open_edge_file: could not open '%s' (%s)", filename, strerror(errno));
@ -253,6 +262,9 @@ int gpio_unexport(int gpio)
char str_gpio[16]; char str_gpio[16];
struct gpio_exp *g, *temp, *prev_g = NULL; struct gpio_exp *g, *temp, *prev_g = NULL;
if (DEBUG)
printf(" ** gpio_unexport **\n");
close_value_fd(gpio); close_value_fd(gpio);
snprintf(filename, sizeof(filename), "/sys/class/gpio/unexport"); BUF2SMALL(filename); snprintf(filename, sizeof(filename), "/sys/class/gpio/unexport"); BUF2SMALL(filename);
@ -274,6 +286,8 @@ int gpio_unexport(int gpio)
return -1; return -1;
} }
if (DEBUG)
printf(" ** gpio_unexport: freeing memory **\n");
// remove from list // remove from list
g = exported_gpios; g = exported_gpios;
while (g != NULL) while (g != NULL)
@ -315,6 +329,9 @@ int gpio_set_direction(int gpio, unsigned int in_flag)
} else { } else {
strncpy(direction, "in", ARRAY_SIZE(direction) - 1); 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; ssize_t s = write(fd, direction, strlen(direction)); e_no = errno;
close(fd); close(fd);
if (s != strlen(direction)) { if (s != strlen(direction)) {
@ -360,6 +377,9 @@ int gpio_get_direction(int gpio, unsigned int *value)
add_error_msg(err); add_error_msg(err);
return -1; return -1;
} }
if (DEBUG)
printf(" ** gpio_get_direction: %s **\n",direction);
if (strcmp(direction, "out") == 0) if (strcmp(direction, "out") == 0)
*value = OUTPUT; *value = OUTPUT;
@ -403,6 +423,9 @@ int gpio_set_value(int gpio, unsigned int value)
strncpy(vstr, "0", ARRAY_SIZE(vstr) - 1); 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; ssize_t s = write(fd, vstr, strlen(vstr)); e_no = errno;
if (s != strlen(vstr)) { if (s != strlen(vstr)) {
@ -444,6 +467,9 @@ int gpio_get_value(int gpio, unsigned int *value)
return -1; return -1;
} }
if (DEBUG)
printf(" ** gpio_get_value: %c **\n", ch);
if (ch == '1') { if (ch == '1') {
*value = 1; *value = 1;
} else if (ch == '0') { } else if (ch == '0') {
@ -472,6 +498,9 @@ int gpio_set_edge(int gpio, unsigned int edge)
return -1; return -1;
} }
if (DEBUG)
printf(" ** gpio_set_edge: %s **\n", stredge[edge]);
ssize_t s = write(fd, stredge[edge], strlen(stredge[edge]) + 1); ssize_t s = write(fd, stredge[edge], strlen(stredge[edge]) + 1);
if (s < 0) { if (s < 0) {
char err[256]; char err[256];
@ -521,6 +550,9 @@ int gpio_get_edge(int gpio)
return -1; return -1;
} }
if (DEBUG)
printf(" ** gpio_get_edge: %s **\n", edge);
if (strcmp(edge, "rising") == 0) if (strcmp(edge, "rising") == 0)
{ {
rtnedge = 1; rtnedge = 1;
@ -553,6 +585,8 @@ int gpio_lookup(int fd)
void exports_cleanup(void) void exports_cleanup(void)
{ {
// unexport everything // unexport everything
if (DEBUG)
printf(" ** exports_cleanup **\n");
while (exported_gpios != NULL) while (exported_gpios != NULL)
gpio_unexport(exported_gpios->gpio); gpio_unexport(exported_gpios->gpio);
} }
@ -562,6 +596,8 @@ int add_edge_callback(int gpio, int edge, void (*func)(int gpio, void* data), vo
struct callback *cb = callbacks; struct callback *cb = callbacks;
struct callback *new_cb; struct callback *new_cb;
if (DEBUG)
printf(" ** add_edge_callback **\n");
new_cb = malloc(sizeof(struct callback)); ASSRT(new_cb != NULL); new_cb = malloc(sizeof(struct callback)); ASSRT(new_cb != NULL);
new_cb->fde = open_edge_file(gpio); new_cb->fde = open_edge_file(gpio);
@ -611,6 +647,8 @@ void run_callbacks(int gpio)
// Only run if we are allowed // Only run if we are allowed
if (canrun) if (canrun)
{ {
if (DEBUG)
printf(" ** run_callbacks: gpio triggered: %d **\n", gpio);
cb->func(cb->gpio, cb->data); cb->func(cb->gpio, cb->data);
} }
@ -629,6 +667,8 @@ void remove_callbacks(int gpio)
{ {
if (cb->gpio == gpio) if (cb->gpio == gpio)
{ {
if (DEBUG)
printf(" ** remove_callbacks: gpio: %d **\n", gpio);
close(cb->fde); close(cb->fde);
if (prev == NULL) if (prev == NULL)
callbacks = cb->next; callbacks = cb->next;
@ -762,6 +802,9 @@ int add_edge_detect(int gpio, unsigned int edge)
struct epoll_event ev; struct epoll_event ev;
long t = 0; long t = 0;
if (DEBUG)
printf(" ** add_edge_detect: gpio: %d **\n", gpio);
// check to see if this gpio has been added already // check to see if this gpio has been added already
if (gpio_event_add(gpio) != 0) if (gpio_event_add(gpio) != 0)
return 1; return 1;
@ -828,6 +871,9 @@ void remove_edge_detect(int gpio)
struct epoll_event ev; struct epoll_event ev;
int fd = fd_lookup(gpio); int fd = fd_lookup(gpio);
if (DEBUG)
printf(" ** remove_edge_detect: gpio : %d **\n", gpio);
// delete callbacks for gpio // delete callbacks for gpio
remove_callbacks(gpio); remove_callbacks(gpio);
@ -871,6 +917,9 @@ int blocking_wait_for_edge(int gpio, unsigned int edge)
struct epoll_event events, ev; struct epoll_event events, ev;
char buf; char buf;
if (DEBUG)
printf(" ** blocking_wait_for_edge: gpio: %d **\n", gpio);
if ((epfd = epoll_create(1)) == -1) { if ((epfd = epoll_create(1)) == -1) {
char err[256]; char err[256];
snprintf(err, sizeof(err), "blocking_wait_for_edge: could not epoll_create GPIO %d (%s)", gpio, strerror(errno)); snprintf(err, sizeof(err), "blocking_wait_for_edge: could not epoll_create GPIO %d (%s)", gpio, strerror(errno));
@ -949,6 +998,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); gpio_event_remove(gpio);
close(epfd); close(epfd);
return 0; return 0;

View File

@ -79,18 +79,21 @@ static PyObject *py_setmode(PyObject *self, PyObject *args)
} }
// python function cleanup(channel=None) // python function cleanup(channel=None)
static PyObject *py_cleanup(PyObject *self, PyObject *args) static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
int gpio; int gpio;
char *channel; char *channel;
static char *kwlist[] = {"channel", NULL};
clear_error_msg(); clear_error_msg();
// Channel is optional
if (!PyArg_ParseTuple(args, "|s", &channel))
return NULL;
if (strcmp(channel, "") == 0) { // Channel is optional
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &channel)) {
return NULL;
}
// The !channel fixes issues #50
if (!channel || strcmp(channel, "") == 0) {
event_cleanup(); event_cleanup();
} else { } else {
if (get_gpio_number(channel, &gpio) < 0) { if (get_gpio_number(channel, &gpio) < 0) {
@ -819,7 +822,7 @@ static PyObject *py_set_direction(PyObject *self, PyObject *args, PyObject *kwar
PyMethodDef gpio_methods[] = { PyMethodDef gpio_methods[] = {
{"setup", (PyCFunction)py_setup_channel, METH_VARARGS | METH_KEYWORDS, "Set up the GPIO channel, direction and (optional) pull/up down control\nchannel - Either: CHIP board pin number (not R8 GPIO 00..nn number). Pins start from 1\n or : CHIP GPIO name\ndirection - INPUT or OUTPUT\n[pull_up_down] - PUD_OFF (default), PUD_UP or PUD_DOWN\n[initial] - Initial value for an output channel"}, {"setup", (PyCFunction)py_setup_channel, METH_VARARGS | METH_KEYWORDS, "Set up the GPIO channel, direction and (optional) pull/up down control\nchannel - Either: CHIP board pin number (not R8 GPIO 00..nn number). Pins start from 1\n or : CHIP GPIO name\ndirection - INPUT or OUTPUT\n[pull_up_down] - PUD_OFF (default), PUD_UP or PUD_DOWN\n[initial] - Initial value for an output channel"},
{"cleanup", py_cleanup, METH_VARARGS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"}, {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"},
{"output", py_output_gpio, METH_VARARGS, "Output to a GPIO channel\ngpio - gpio channel\nvalue - 0/1 or False/True or LOW/HIGH"}, {"output", py_output_gpio, METH_VARARGS, "Output to a GPIO channel\ngpio - gpio channel\nvalue - 0/1 or False/True or LOW/HIGH"},
{"input", py_input_gpio, METH_VARARGS, "Input from a GPIO channel. Returns HIGH=1=True or LOW=0=False\ngpio - gpio channel"}, {"input", py_input_gpio, METH_VARARGS, "Input from a GPIO channel. Returns HIGH=1=True or LOW=0=False\ngpio - gpio channel"},
{"add_event_detect", (PyCFunction)py_add_event_detect, METH_VARARGS | METH_KEYWORDS, "Enable edge detection events for a particular GPIO channel.\nchannel - either board pin number or BCM number depending on which mode is set.\nedge - RISING, FALLING or BOTH\n[callback] - A callback function for the event (optional)\n[bouncetime] - Switch bounce timeout in ms for callback"}, {"add_event_detect", (PyCFunction)py_add_event_detect, METH_VARARGS | METH_KEYWORDS, "Enable edge detection events for a particular GPIO channel.\nchannel - either board pin number or BCM number depending on which mode is set.\nedge - RISING, FALLING or BOTH\n[callback] - A callback function for the event (optional)\n[bouncetime] - Switch bounce timeout in ms for callback"},
@ -831,14 +834,14 @@ PyMethodDef gpio_methods[] = {
{"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"}, {"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
{"get_gpio_base", py_gpio_base, METH_VARARGS, "Get the XIO base number for sysfs"}, {"get_gpio_base", py_gpio_base, METH_VARARGS, "Get the XIO base number for sysfs"},
{"selftest", py_selftest, METH_VARARGS, "Internal unit tests"}, {"selftest", py_selftest, METH_VARARGS, "Internal unit tests"},
{"direction", (PyCFunction)py_set_direction, METH_VARARGS, "Change direction of gpio channel. Either INPUT or OUTPUT\n" }, {"direction", (PyCFunction)py_set_direction, METH_VARARGS | METH_KEYWORDS, "Change direction of gpio channel. Either INPUT or OUTPUT\n" },
{"setmode", (PyCFunction)py_setmode, METH_VARARGS, "Dummy function that does nothing but maintain compatibility with RPi.GPIO\n" }, {"setmode", (PyCFunction)py_setmode, METH_VARARGS, "Dummy function that does nothing but maintain compatibility with RPi.GPIO\n" },
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };
#if PY_MAJOR_VERSION > 2 #if PY_MAJOR_VERSION > 2
static struct PyModuleDef rpigpiomodule = { static struct PyModuleDef chipgpiomodule = {
PyModuleDef_HEAD_INIT, PyModuleDef_HEAD_INIT,
"GPIO", // name of module "GPIO", // name of module
moduledocstring, // module documentation, may be NULL moduledocstring, // module documentation, may be NULL
@ -858,7 +861,7 @@ PyMODINIT_FUNC initGPIO(void)
clear_error_msg(); clear_error_msg();
#if PY_MAJOR_VERSION > 2 #if PY_MAJOR_VERSION > 2
if ((module = PyModule_Create(&rpigpiomodule)) == NULL) if ((module = PyModule_Create(&chipgpiomodule)) == NULL)
return NULL; return NULL;
#else #else
if ((module = Py_InitModule3("GPIO", gpio_methods, moduledocstring)) == NULL) if ((module = Py_InitModule3("GPIO", gpio_methods, moduledocstring)) == NULL)

View File

@ -47,7 +47,7 @@ static PyObject *py_cleanup(PyObject *self, PyObject *args)
static PyObject *py_toggle_debug(PyObject *self, PyObject *args) static PyObject *py_toggle_debug(PyObject *self, PyObject *args)
{ {
// toggle debug printing // toggle debug printing
pwm_toggle_debug(); toggle_debug();
Py_RETURN_NONE; Py_RETURN_NONE;
} }
@ -62,6 +62,8 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
int polarity = 0; int polarity = 0;
static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL}; 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)) { if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ffi", kwlist, &channel, &duty_cycle, &frequency, &polarity)) {
return NULL; return NULL;
} }
@ -100,6 +102,8 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
char key[8]; char key[8];
char *channel; char *channel;
clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) if (!PyArg_ParseTuple(args, "s", &channel))
return NULL; return NULL;
@ -121,6 +125,8 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
float duty_cycle = 0.0; float duty_cycle = 0.0;
static char *kwlist[] = {"channel", "duty_cycle", NULL}; static char *kwlist[] = {"channel", "duty_cycle", NULL};
clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle)) if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle))
return NULL; return NULL;
@ -143,6 +149,47 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
Py_RETURN_NONE; 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;
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;
}
// 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) == -1) {
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
return NULL;
}
Py_RETURN_NONE;
}
// python method PWM.set_frequency(channel, frequency) // python method PWM.set_frequency(channel, frequency)
static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwargs)
{ {
@ -151,6 +198,8 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
float frequency = 1.0; float frequency = 1.0;
static char *kwlist[] = {"channel", "frequency", NULL}; static char *kwlist[] = {"channel", "frequency", NULL};
clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency)) if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency))
return NULL; return NULL;
@ -173,6 +222,37 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
Py_RETURN_NONE; 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;
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;
}
if (pwm_set_period_ns(key, period_ns) == -1) {
PyErr_SetString(PyExc_RuntimeError, "You must start() the PWM channel first");
return NULL;
}
Py_RETURN_NONE;
}
static const char moduledocstring[] = "Hardware PWM functionality of a CHIP using Python"; static const char moduledocstring[] = "Hardware PWM functionality of a CHIP using Python";
@ -181,9 +261,10 @@ PyMethodDef pwm_methods[] = {
{"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop 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_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" },
{"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" }, {"set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
{"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", py_cleanup, METH_VARARGS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"}, {"cleanup", 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"},
{"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"}, {"toggle_debug", py_toggle_debug, METH_VARARGS, "Toggles the enabling/disabling of Debug print output"},
//{"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };

View File

@ -41,11 +41,14 @@ static PyObject *py_cleanup(PyObject *self, PyObject *args)
char key[8]; char key[8];
char *channel = NULL; char *channel = NULL;
clear_error_msg();
// Channel is optional // Channel is optional
if (!PyArg_ParseTuple(args, "|s", &channel)) if (!PyArg_ParseTuple(args, "|s", &channel))
return NULL; return NULL;
if (strcmp(channel, "") == 0) { // The !channel fixes issue #50
if (!channel || strcmp(channel, "") == 0) {
softpwm_cleanup(); softpwm_cleanup();
} else { } else {
if (!get_key(channel, key)) { if (!get_key(channel, key)) {
@ -68,6 +71,8 @@ static PyObject *py_start_channel(PyObject *self, PyObject *args, PyObject *kwar
int polarity = 0; int polarity = 0;
static char *kwlist[] = {"channel", "duty_cycle", "frequency", "polarity", NULL}; 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)) { if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ffi", kwlist, &channel, &duty_cycle, &frequency, &polarity)) {
return NULL; return NULL;
} }
@ -113,6 +118,8 @@ static PyObject *py_stop_channel(PyObject *self, PyObject *args, PyObject *kwarg
char key[8]; char key[8];
char *channel; char *channel;
clear_error_msg();
if (!PyArg_ParseTuple(args, "s", &channel)) if (!PyArg_ParseTuple(args, "s", &channel))
return NULL; return NULL;
@ -134,6 +141,8 @@ static PyObject *py_set_duty_cycle(PyObject *self, PyObject *args, PyObject *kwa
float duty_cycle = 0.0; float duty_cycle = 0.0;
static char *kwlist[] = {"channel", "duty_cycle", NULL}; static char *kwlist[] = {"channel", "duty_cycle", NULL};
clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle)) if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &duty_cycle))
return NULL; return NULL;
@ -164,6 +173,8 @@ static PyObject *py_set_frequency(PyObject *self, PyObject *args, PyObject *kwar
float frequency = 1.0; float frequency = 1.0;
static char *kwlist[] = {"channel", "frequency", NULL}; static char *kwlist[] = {"channel", "frequency", NULL};
clear_error_msg();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency)) if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|f", kwlist, &channel, &frequency))
return NULL; return NULL;
@ -194,12 +205,11 @@ PyMethodDef pwm_methods[] = {
{ "set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" }, { "set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" },
{ "set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" }, { "set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
{ "cleanup", (PyCFunction)py_cleanup, METH_VARARGS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"}, { "cleanup", (PyCFunction)py_cleanup, METH_VARARGS, "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"},
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };
#if PY_MAJOR_VERSION > 2 #if PY_MAJOR_VERSION > 2
static struct PyModuleDef chippwmmodule = { static struct PyModuleDef chipspwmmodule = {
PyModuleDef_HEAD_INIT, PyModuleDef_HEAD_INIT,
"SOFTPWM", // name of module "SOFTPWM", // name of module
moduledocstring, // module documentation, may be NULL moduledocstring, // module documentation, may be NULL
@ -217,7 +227,7 @@ PyMODINIT_FUNC initSOFTPWM(void)
PyObject *module = NULL; PyObject *module = NULL;
#if PY_MAJOR_VERSION > 2 #if PY_MAJOR_VERSION > 2
if ((module = PyModule_Create(&chippwmmodule)) == NULL) if ((module = PyModule_Create(&chipspwmmodule)) == NULL)
return NULL; return NULL;
#else #else
if ((module = Py_InitModule3("SOFTPWM", pwm_methods, moduledocstring)) == NULL) if ((module = Py_InitModule3("SOFTPWM", pwm_methods, moduledocstring)) == NULL)

View File

@ -4,7 +4,7 @@ import CHIP_IO.LRADC as ADC
# == ENABLE DEBUG == # == ENABLE DEBUG ==
print("ENABLING LRADC DEBUG OUTPUT") print("ENABLING LRADC DEBUG OUTPUT")
ADC.enable_debug() ADC.toggle_debug()
# == SETUP == # == SETUP ==
print("LRADC SETUP WITH SAMPLE RATE OF 125") print("LRADC SETUP WITH SAMPLE RATE OF 125")

View File

@ -5,7 +5,7 @@ import os
# ENABLE DEBUG # ENABLE DEBUG
print("ENABLING OVERLAY MANAGER DEBUG") print("ENABLING OVERLAY MANAGER DEBUG")
OM.enable_debug() OM.toggle_debug()
# **************** PWM ******************* # **************** PWM *******************
print("\nIS PWM ENABLED: {0}".format(OM.get_pwm_loaded())) print("\nIS PWM ENABLED: {0}".format(OM.get_pwm_loaded()))
@ -20,19 +20,6 @@ print("UNLOADING PWM0")
OM.unload("PWM0") OM.unload("PWM0")
print("IS PWM ENABLED: {0}".format(OM.get_pwm_loaded())) print("IS PWM ENABLED: {0}".format(OM.get_pwm_loaded()))
# **************** I2C-1 *******************
print("\nIS I2C ENABLED: {0}".format(OM.get_i2c_loaded()))
OM.load("I2C1")
print("IS I2C ENABLED: {0}".format(OM.get_i2c_loaded()))
# VERIFY I2C-1 EXISTS
if os.path.exists('/sys/class/i2c-dev/i2c-1'):
print("I2C1 DEVICE EXISTS")
else:
print("I2C1 DEVICE DID NOT LOAD PROPERLY")
print("UNLOADING I2C1")
OM.unload("I2C1")
print("IS I2C ENABLED: {0}".format(OM.get_i2c_loaded()))
# **************** SPI2 ******************* # **************** SPI2 *******************
print("\nIS SPI ENABLED: {0}".format(OM.get_spi_loaded())) print("\nIS SPI ENABLED: {0}".format(OM.get_spi_loaded()))
OM.load("SPI2") OM.load("SPI2")