python_examples: Reformatted, self-checking, executable

* Moved body of each python example to main.  This allows for basic
      load module testing for CI
    * General cleanup of python modules (crlf/tabs/prints/etc)
    * Chmod'ed to 755 to allow running examples without specifying the
      python interpreter
    * Added ctest for loading python2/3 modules
    * Added jniclasscode pragma for java swig interface files.
    * Updated check_examplenames.py module to check all languages vs. a
      cxx example name
    * Added tests for checking python module and test loading
    * Added 'make test' to travis-ci run (run ctests)
    * Print a more meaningful message when not building cxx docs into
      python modules
    * Updated check_clean.py to only check java wrapper files
    * ENABLED ctests for UPM
    * Deleted using_carrays.py python example - this is covered by other
      examples

Signed-off-by: Noel Eck <noel.eck@intel.com>
This commit is contained in:
Noel Eck 2016-09-29 18:24:19 -07:00
parent 62718daf0b
commit 2f78d9f62b
203 changed files with 5890 additions and 5216 deletions

View File

@ -33,8 +33,10 @@ before_script:
script: script:
- echo "CC=$CC BUILDJAVA=$BUILDJAVA NODE010=$NODE010 NODE012=$NODE012 NODE4=$NODE4 NODE5=$NODE5 NODE_ROOT_DIR=$NODE_ROOT_DIR" - echo "CC=$CC BUILDJAVA=$BUILDJAVA NODE010=$NODE010 NODE012=$NODE012 NODE4=$NODE4 NODE5=$NODE5 NODE_ROOT_DIR=$NODE_ROOT_DIR"
- git clone https://github.com/intel-iot-devkit/mraa.git $MRAA_ROOT - git clone https://github.com/intel-iot-devkit/mraa.git $MRAA_ROOT
- mkdir -p $MRAA_BUILD && cd $_ && cmake -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDSWIGNODE=OFF -DBUILDSWIGPYTHON=OFF -DFIRMATA=ON -DENABLEEXAMPLES=OFF -DCMAKE_INSTALL_PREFIX:PATH=$MRAA_INSTALL $MRAA_ROOT && make install - mkdir -p $MRAA_BUILD && cd $_ && cmake -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDSWIGNODE=OFF -DBUILDSWIGPYTHON=ON -DFIRMATA=ON -DENABLEEXAMPLES=OFF -DCMAKE_INSTALL_PREFIX:PATH=$MRAA_INSTALL $MRAA_ROOT && make install
- cd $UPM_ROOT && mkdir $UPM_BUILD && cd $_ && PKG_CONFIG_PATH=$MRAA_INSTALL/lib/pkgconfig cmake -DNODE_ROOT_DIR:PATH="${NODE_ROOT_DIR}" -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDEXAMPLES=ON -DBUILDJAVAEXAMPLES=$BUILDJAVA -DCMAKE_INSTALL_PREFIX:PATH=$UPM_INSTALL .. && make install - cd $UPM_ROOT && mkdir $UPM_BUILD && cd $_ && PKG_CONFIG_PATH=$MRAA_INSTALL/lib/pkgconfig cmake -DNODE_ROOT_DIR:PATH="${NODE_ROOT_DIR}" -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDEXAMPLES=ON -DBUILDJAVAEXAMPLES=$BUILDJAVA -DBUILDTESTS=ON -DCMAKE_INSTALL_PREFIX:PATH=$UPM_INSTALL ..
- make install
- LD_LIBRARY_PATH=$MRAA_INSTALL/lib:$UPM_INSTALL/lib:$LD_LIBRARY_PATH PYTHONPATH=$UPM_INSTALL/lib/python2.7/site-packages/:$MRAA_INSTALL/lib/python2.7/dist-packages/ ctest --output-on-failure -E examplenames_js
addons: addons:
apt: apt:
sources: sources:

View File

@ -1,73 +1,72 @@
# Mapping C++ sample files to Java sample files # Mapping examples across provided languages
a110x-intr.cxx A110X_intrSample.java a110x.cxx A110XSample.java a110x.js a110x.py
a110x.cxx A110XSample.java a110x-intr.cxx A110X_intrSample.java a110x-intr.js a110x-intr.py
adc121c021.cxx ADC121C021Sample.java adc121c021.cxx ADC121C021Sample.java adc121c021.js adc121c021.py
adxl345.cxx Adxl345Sample.java adxl345.cxx Adxl345Sample.java adxl345.js adxl345.py
biss0001.cxx BISS0001Sample.java biss0001.cxx BISS0001Sample.java biss0001.js biss0001.py
bmpx8x.cxx BMPX8XSample.java bmpx8x.cxx BMPX8XSample.java bmpx8x.js bmpx8x.py
buzzer-sound.cxx Buzzer_soundSample.java button.cxx ButtonSample.java button.js button.py
cjq4435.cxx CJQ4435Sample.java buzzer-sound.cxx Buzzer_soundSample.java buzzer-sound.js buzzer-sound.py
ds1307.cxx DS1307Sample.java cjq4435.cxx CJQ4435Sample.java cjq4435.js cjq4435.py
enc03r.cxx ENC03RSample.java ds1307.cxx DS1307Sample.java ds1307.js ds1307.py
es08a.cxx ES08ASample.java enc03r.cxx ENC03RSample.java enc03r.js enc03r.py
button.cxx ButtonSample.java es08a.cxx ES08ASample.java es08a.js es08a.py
groveehr.cxx GroveEHRSample.java groveehr.cxx GroveEHRSample.java groveehr.js groveehr.py
groveled.cxx GroveLEDSample.java groveledbar.cxx GroveLEDBar.java groveledbar.js groveledbar.py
grovelinefinder.cxx GroveLineFinderSample.java groveled.cxx GroveLEDSample.java groveled.js groveled.py
light.cxx LightSample.java grovelinefinder.cxx GroveLineFinderSample.java grovelinefinder.js grovelinefinder.py
grovemoisture.cxx GroveMoistureSample.java grovemoisture.cxx GroveMoistureSample.java grovemoisture.js grovemoisture.py
relay.cxx RelaySample.java grovescam.cxx GROVESCAMSample.java grovescam.js grovescam.py
rotary.cxx RotarySample.java grovewfs.cxx GroveWFSSample.java grovewfs.js grovewfs.py
grovescam.cxx GROVESCAMSample.java guvas12d.cxx GUVAS12DSample.java guvas12d.js guvas12d.py
slide.cxx SlideSample.java h3lis331dl.cxx H3LIS331DLSample.java h3lis331dl.js h3lis331dl.py
speaker.cxx SpeakerSample.java hcsr04.cxx HCSR04Sample.java hcsr04.js hcsr04.py
vdiv.cxx VDivSample.java hm11.cxx HM11Sample.java hm11.js hm11.py
water.cxx WaterSample.java hmc5883l.cxx Hmc5883lSample.java hmc5883l.js hmc5883l.py
grovewfs.cxx GroveWFSSample.java htu21d.cxx HTU21DSample.java htu21d.js htu21d.py
guvas12d.cxx GUVAS12DSample.java itg3200.cxx Itg3200Sample.java itg3200.js itg3200.py
h3lis331dl.cxx H3LIS331DLSample.java jhd1313m1-lcd.cxx Jhd1313m1_lcdSample.java jhd1313m1-lcd.js jhd1313m1-lcd.py
hcsr04.cxx HCSR04Sample.java joystick12.cxx Joystick12Sample.java joystick12.js joystick12.py
hm11.cxx HM11Sample.java lcm1602-i2c.cxx Lcm1602_i2cSample.java lcm1602-i2c.js lcm1602-i2c.py
hmc5883l.cxx Hmc5883lSample.java ldt0028.cxx LDT0028Sample.java ldt0028.js ldt0028.py
htu21d.cxx HTU21DSample.java light.cxx LightSample.java light.js light.py
itg3200.cxx Itg3200Sample.java lol.cxx LoLSample.java lol.js lol.py
jhd1313m1-lcd.cxx Jhd1313m1_lcdSample.java lsm303.cxx LSM303Sample.java lsm303.js lsm303.py
joystick12.cxx Joystick12Sample.java m24lr64e.cxx M24LR64ESample.java m24lr64e.js m24lr64e.py
lcm1602-i2c.cxx Lcm1602_i2cSample.java max44000.cxx MAX44000Sample.java max44000.js max44000.py
ldt0028.cxx LDT0028Sample.java mic.cxx MicrophoneSample.java mic.js mic.py
lol.cxx LoLSample.java mma7455.cxx MMA7455Sample.java mma7455.js mma7455.py
lsm303.cxx LSM303Sample.java mma7660.cxx MMA7660Sample.java mma7660.js mma7660.py
m24lr64e.cxx M24LR64ESample.java mpl3115a2.cxx MPL3115A2Sample.java mpl3115a2.js mpl3115a2.py
max44000.cxx MAX44000Sample.java mpr121.cxx MPR121Sample.java mpr121.js mpr121.py
mic.cxx MicrophoneSample.java mpu9150.cxx MPU9150Sample.java mpu9150.js mpu9150.py
mma7455.cxx MMA7455Sample.java mq2.cxx MQ2Sample.java mq2.js mq2.py
mma7660.cxx MMA7660Sample.java mq303a.cxx MQ303ASample.java mq303a.js mq303a.py
mpl3115a2.cxx MPL3115A2Sample.java mq5.cxx MQ5Sample.java mq5.js mq5.py
mpr121.cxx MPR121Sample.java nrf24l01-receiver.cxx NRF24L01_receiverSample.java nrf24l01-receiver.js nrf24l01-receiver.py
mpu9150.cxx MPU9150Sample.java nrf24l01-transmitter.cxx NRF24L01_transmitterSample.java nrf24l01-transmitter.js nrf24l01-transmitter.py
mq2.cxx MQ2Sample.java nunchuck.cxx NUNCHUCKSample.java nunchuck.js nunchuck.py
mq303a.cxx MQ303ASample.java otp538u.cxx OTP538USample.java otp538u.js otp538u.py
mq5.cxx MQ5Sample.java ppd42ns.cxx PPD42NSSample.java ppd42ns.js ppd42ns.py
groveledbar GroveLEDBar pulsensor.cxx PulsensorSample.java pulsensor.js pulsensor.py
nrf24l01-receiver.cxx NRF24L01_receiverSample.java relay.cxx RelaySample.java relay.js relay.py
nrf24l01-transmitter.cxx NRF24L01_transmitterSample.java rfr359f.cxx RFR359FSample.java rfr359f.js rfr359f.py
nunchuck.cxx NUNCHUCKSample.java rotary.cxx RotarySample.java rotary.js rotary.py
otp538u.cxx OTP538USample.java rotaryencoder.cxx RotaryEncoderSample.java rotaryencoder.js rotaryencoder.py
ppd42ns.cxx PPD42NSSample.java rpr220.cxx RPR220Sample.java rpr220.js rpr220.py
pulsensor.cxx PulsensorSample.java rpr220-intr.cxx RPR220_intrSample.java rpr220-intr.js rpr220-intr.py
rfr359f.cxx RFR359FSample.java slide.cxx SlideSample.java slide.js slide.py
rotaryencoder.cxx RotaryEncoderSample.java speaker.cxx SpeakerSample.java speaker.js speaker.py
rpr220-intr.cxx RPR220_intrSample.java ssd1308-oled.cxx SSD1308_oledSample.java ssd1308-oled.js ssd1308-oled.py
rpr220.cxx RPR220Sample.java ssd1327-oled.cxx SSD1327_oledSample.java ssd1327-oled.js ssd1327-oled.py
ssd1308-oled.cxx SSD1308_oledSample.java st7735.cxx ST7735Sample.java st7735.js st7735.py
ssd1327-oled.cxx SSD1327_oledSample.java stepmotor.cxx StepMotorSample.java stepmotor.js stepmotor.py
st7735.cxx ST7735Sample.java tm1637.cxx TM1637Sample.java tm1637.js tm1637.py
stepmotor.cxx StepMotorSample.java tp401.cxx TP401Sample.java tp401.js tp401.py
tm1637.cxx TM1637Sample.java tsl2561.cxx TSL2561Sample.java tsl2561.js tsl2561.py
tp401.cxx TP401Sample.java ttp223.cxx TTP223Sample.java ttp223.js ttp223.py
tsl2561.cxx TSL2561Sample.java uln200xa.cxx ULN200XASample.java uln200xa.js uln200xa.py
ttp223.cxx TTP223Sample.java vdiv.cxx VDivSample.java vdiv.js vdiv.py
ublox6.cxx Ublox6Sample.java water.cxx WaterSample.java water.js water.py
uln200xa.cxx ULN200XASample.java wt5001.cxx WT5001Sample.java wt5001.js wt5001.py
wt5001.cxx WT5001Sample.java yg1006.cxx YG1006Sample.java yg1006.js yg1006.py
yg1006.cxx YG1006Sample.java

42
examples/python/a110x.py Normal file → Executable file
View File

@ -24,28 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_a110x as upmA110x import pyupm_a110x as upmA110x
# Instantiate a Hall Effect magnet sensor on digital pin D2 def main():
myHallEffectSensor = upmA110x.A110X(2) # Instantiate a Hall Effect magnet sensor on digital pin D2
myHallEffectSensor = upmA110x.A110X(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myHallEffectSensor
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myHallEffectSensor # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) if (myHallEffectSensor.magnetDetected()):
signal.signal(signal.SIGINT, SIGINTHandler) print "Magnet (south polarity) detected."
else:
print "No magnet detected."
time.sleep(1)
if __name__ == '__main__':
while(1): main()
if (myHallEffectSensor.magnetDetected()):
print "Magnet (south polarity) detected."
else:
print "No magnet detected."
time.sleep(1)

48
examples/python/ad8232.py Normal file → Executable file
View File

@ -24,31 +24,33 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ad8232 as upmAD8232 import pyupm_ad8232 as upmAD8232
# Instantiate a AD8232 sensor on digital pins 10 (LO+), 11 (LO-) def main():
# and an analog pin, 0 (OUTPUT) # Instantiate a AD8232 sensor on digital pins 10 (LO+), 11 (LO-)
myAD8232 = upmAD8232.AD8232(10, 11, 0) # and an analog pin, 0 (OUTPUT)
myAD8232 = upmAD8232.AD8232(10, 11, 0)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myAD8232
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myAD8232 # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers # Output the raw numbers from the ADC, for plotting elsewhere.
atexit.register(exitHandler) # A return of 0 indicates a Lead Off (LO) condition.
signal.signal(signal.SIGINT, SIGINTHandler) # In theory, this data could be fed to software like Processing
# (https://www.processing.org/) to plot the data just like an
# EKG you would see in a hospital.
while(1):
print myAD8232.value()
time.sleep(.001)
if __name__ == '__main__':
# Output the raw numbers from the ADC, for plotting elsewhere. main()
# A return of 0 indicates a Lead Off (LO) condition.
# In theory, this data could be fed to software like Processing
# (https://www.processing.org/) to plot the data just like an
# EKG you would see in a hospital.
while(1):
print myAD8232.value()
time.sleep(.001)

90
examples/python/adafruitms1438-stepper.py Normal file → Executable file
View File

@ -24,65 +24,65 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_adafruitms1438 as upmAdafruitms1438 import pyupm_adafruitms1438 as upmAdafruitms1438
def main():
# Import header values
I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS
I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR
# Import header values M12Motor = upmAdafruitms1438.AdafruitMS1438.STEPMOTOR_M12
I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW
I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW
M12Motor = upmAdafruitms1438.AdafruitMS1438.STEPMOTOR_M12 # Instantiate an Adafruit MS 1438 on I2C bus 0
MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr)
MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# Instantiate an Adafruit MS 1438 on I2C bus 0 # This function lets you run code on exit,
myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr) # including functions from myMotorShield
def exitHandler():
myMotorShield.disableStepper(M12Motor)
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
## Exit handlers ## # Setup for use with a stepper motor connected to the M1 & M2 ports
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit, # set a PWM period of 50Hz
# including functions from myMotorShield
def exitHandler():
myMotorShield.disableStepper(M12Motor)
print "Exiting"
sys.exit(0)
# Register exit handlers # disable first, to be safe
atexit.register(exitHandler) myMotorShield.disableStepper(M12Motor)
signal.signal(signal.SIGINT, SIGINTHandler)
# configure for a NEMA-17, 200 steps per revolution
myMotorShield.stepConfig(M12Motor, 200)
# Setup for use with a stepper motor connected to the M1 & M2 ports # set speed at 10 RPM's
myMotorShield.setStepperSpeed(M12Motor, 10);
myMotorShield.setStepperDirection(M12Motor, MotorDirCW)
# set a PWM period of 50Hz # enable
print "Enabling..."
myMotorShield.enableStepper(M12Motor)
# disable first, to be safe print "Rotating 1 full revolution at 10 RPM speed."
myMotorShield.disableStepper(M12Motor) myMotorShield.stepperSteps(M12Motor, 200)
# configure for a NEMA-17, 200 steps per revolution print "Sleeping for 2 seconds..."
myMotorShield.stepConfig(M12Motor, 200) time.sleep(2)
print "Rotating 1/2 revolution in opposite direction at 10 RPM speed."
# set speed at 10 RPM's myMotorShield.setStepperDirection(M12Motor, MotorDirCCW)
myMotorShield.setStepperSpeed(M12Motor, 10); myMotorShield.stepperSteps(M12Motor, 100)
myMotorShield.setStepperDirection(M12Motor, MotorDirCW)
# enable print "Disabling..."
print "Enabling..."
myMotorShield.enableStepper(M12Motor)
print "Rotating 1 full revolution at 10 RPM speed." # exitHandler runs automatically
myMotorShield.stepperSteps(M12Motor, 200)
print "Sleeping for 2 seconds..." if __name__ == '__main__':
time.sleep(2) main()
print "Rotating 1/2 revolution in opposite direction at 10 RPM speed."
myMotorShield.setStepperDirection(M12Motor, MotorDirCCW)
myMotorShield.stepperSteps(M12Motor, 100)
print "Disabling..."
# exitHandler runs automatically

82
examples/python/adafruitms1438.py Normal file → Executable file
View File

@ -24,60 +24,60 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_adafruitms1438 as upmAdafruitms1438 import pyupm_adafruitms1438 as upmAdafruitms1438
def main():
# Import header values
I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS
I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR
# Import header values M3Motor = upmAdafruitms1438.AdafruitMS1438.MOTOR_M3
I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW
I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW
M3Motor = upmAdafruitms1438.AdafruitMS1438.MOTOR_M3 # Instantiate an Adafruit MS 1438 on I2C bus 0
MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr)
MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# Instantiate an Adafruit MS 1438 on I2C bus 0 # This function lets you run code on exit,
myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr) # including functions from myMotorShield
def exitHandler():
myMotorShield.disableMotor(M3Motor)
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
## Exit handlers ## # Setup for use with a DC motor connected to the M3 port
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit, # set a PWM period of 50Hz
# including functions from myMotorShield myMotorShield.setPWMPeriod(50)
def exitHandler():
myMotorShield.disableMotor(M3Motor)
print "Exiting"
sys.exit(0)
# Register exit handlers # disable first, to be safe
atexit.register(exitHandler) myMotorShield.disableMotor(M3Motor)
signal.signal(signal.SIGINT, SIGINTHandler)
# set speed at 50%
myMotorShield.setMotorSpeed(M3Motor, 50)
myMotorShield.setMotorDirection(M3Motor, MotorDirCW)
# Setup for use with a DC motor connected to the M3 port print ("Spin M3 at half speed for 3 seconds, "
"then reverse for 3 seconds.")
myMotorShield.enableMotor(M3Motor)
# set a PWM period of 50Hz time.sleep(3)
myMotorShield.setPWMPeriod(50)
# disable first, to be safe print "Reversing M3"
myMotorShield.disableMotor(M3Motor) myMotorShield.setMotorDirection(M3Motor, MotorDirCCW)
# set speed at 50% time.sleep(3)
myMotorShield.setMotorSpeed(M3Motor, 50)
myMotorShield.setMotorDirection(M3Motor, MotorDirCW)
print ("Spin M3 at half speed for 3 seconds, " print "Stopping M3"
"then reverse for 3 seconds.")
myMotorShield.enableMotor(M3Motor)
time.sleep(3) # exitHandler runs automatically
print "Reversing M3" if __name__ == '__main__':
myMotorShield.setMotorDirection(M3Motor, MotorDirCCW) main()
time.sleep(3)
print "Stopping M3"
# exitHandler runs automatically

48
examples/python/adc121c021.py Normal file → Executable file
View File

@ -24,32 +24,34 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_adc121c021 as upmAdc121c021 import pyupm_adc121c021 as upmAdc121c021
# Instantiate an ADC121C021 on I2C bus 0 def main():
busID = upmAdc121c021.ADC121C021_I2C_BUS # Instantiate an ADC121C021 on I2C bus 0
I2CAddr = upmAdc121c021.ADC121C021_DEFAULT_I2C_ADDR busID = upmAdc121c021.ADC121C021_I2C_BUS
I2CAddr = upmAdc121c021.ADC121C021_DEFAULT_I2C_ADDR
myAnalogDigitalConv = upmAdc121c021.ADC121C021(busID, I2CAddr) myAnalogDigitalConv = upmAdc121c021.ADC121C021(busID, I2CAddr)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myAnalogDigitalConv
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myAnalogDigitalConv atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers # get the data every 50 milliseconds
atexit.register(exitHandler) while(1):
signal.signal(signal.SIGINT, SIGINTHandler) val = myAnalogDigitalConv.value()
voltsVal = myAnalogDigitalConv.valueToVolts(val)
print "ADC value: %s Volts = %s" % (val, voltsVal)
time.sleep(.05)
if __name__ == '__main__':
# get the data every 50 milliseconds main()
while(1):
val = myAnalogDigitalConv.value()
voltsVal = myAnalogDigitalConv.valueToVolts(val)
print "ADC value: %s Volts = %s" % (val, voltsVal)
time.sleep(.05)

82
examples/python/adxl335.py Normal file → Executable file
View File

@ -24,55 +24,57 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_adxl335 as upmAdxl335 import pyupm_adxl335 as upmAdxl335
myAnalogAccel = upmAdxl335.ADXL335(0, 1, 2) def main():
myAnalogAccel = upmAdxl335.ADXL335(0, 1, 2)
print "Please make sure the sensor is completely still." print "Please make sure the sensor is completely still."
print "Sleeping for 2 seconds" print "Sleeping for 2 seconds"
time.sleep(2) time.sleep(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myAnalogAccel
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This function lets you run code on exit, # Register exit handlers
# including functions from myAnalogAccel atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers print "Calibrating..."
atexit.register(exitHandler) myAnalogAccel.calibrate()
signal.signal(signal.SIGINT, SIGINTHandler)
x = upmAdxl335.new_intPointer()
y = upmAdxl335.new_intPointer()
z = upmAdxl335.new_intPointer()
print "Calibrating..." aX = upmAdxl335.new_floatPointer()
myAnalogAccel.calibrate() aY = upmAdxl335.new_floatPointer()
aZ = upmAdxl335.new_floatPointer()
x = upmAdxl335.new_intPointer() while (1):
y = upmAdxl335.new_intPointer() myAnalogAccel.values(x, y, z)
z = upmAdxl335.new_intPointer() outputStr = "Raw Values: X: {0} Y: {1} Z: {2}".format(
upmAdxl335.intPointer_value(x), upmAdxl335.intPointer_value(y),
upmAdxl335.intPointer_value(z))
print outputStr
aX = upmAdxl335.new_floatPointer() myAnalogAccel.acceleration(aX, aY, aZ)
aY = upmAdxl335.new_floatPointer() outputStr = ("Acceleration: X: {0}g\n"
aZ = upmAdxl335.new_floatPointer() "Acceleration: Y: {1}g\n"
"Acceleration: Z: {2}g").format(upmAdxl335.floatPointer_value(aX),
upmAdxl335.floatPointer_value(aY),
upmAdxl335.floatPointer_value(aZ))
print outputStr
while (1): print " "
myAnalogAccel.values(x, y, z)
outputStr = "Raw Values: X: {0} Y: {1} Z: {2}".format(
upmAdxl335.intPointer_value(x), upmAdxl335.intPointer_value(y),
upmAdxl335.intPointer_value(z))
print outputStr
myAnalogAccel.acceleration(aX, aY, aZ) time.sleep(.2)
outputStr = ("Acceleration: X: {0}g\n"
"Acceleration: Y: {1}g\n"
"Acceleration: Z: {2}g").format(upmAdxl335.floatPointer_value(aX),
upmAdxl335.floatPointer_value(aY),
upmAdxl335.floatPointer_value(aZ))
print outputStr
print " " if __name__ == '__main__':
main()
time.sleep(.2)

29
examples/python/adxl345.py Normal file → Executable file
View File

@ -23,19 +23,22 @@
from time import sleep from time import sleep
import pyupm_adxl345 as adxl345 import pyupm_adxl345 as adxl345
# Create an I2C accelerometer object def main():
adxl = adxl345.Adxl345(0) # Create an I2C accelerometer object
adxl = adxl345.Adxl345(0)
# Loop indefinitely # Loop indefinitely
while True: while True:
adxl.update() # Update the data
raw = adxl.getRawValues() # Read raw sensor data
force = adxl.getAcceleration() # Read acceleration force (g)
print "Raw: %6d %6d %6d" % (raw[0], raw[1], raw[2])
print "ForceX: %5.2f g" % (force[0])
print "ForceY: %5.2f g" % (force[1])
print "ForceZ: %5.2f g\n" % (force[2])
adxl.update() # Update the data # Sleep for 1 s
raw = adxl.getRawValues() # Read raw sensor data sleep(1)
force = adxl.getAcceleration() # Read acceleration force (g)
print "Raw: %6d %6d %6d" % (raw[0], raw[1], raw[2])
print "ForceX: %5.2f g" % (force[0])
print "ForceY: %5.2f g" % (force[1])
print "ForceZ: %5.2f g\n" % (force[2])
# Sleep for 1 s if __name__ == '__main__':
sleep(1) main()

46
examples/python/adxrs610.py Normal file → Executable file
View File

@ -24,32 +24,36 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_adxrs610 as sensorObj import pyupm_adxrs610 as sensorObj
# Instantiate a ADXRS610 sensor on analog pin A0 (dataout), and def main():
# analog A1 (temp out) with an analog reference voltage of # Instantiate a ADXRS610 sensor on analog pin A0 (dataout), and
# 5.0 # analog A1 (temp out) with an analog reference voltage of
sensor = sensorObj.ADXRS610(0, 1, 5.0) # 5.0
sensor = sensorObj.ADXRS610(0, 1, 5.0)
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# set a deadband region around the zero point to report 0.0 (optional) # set a deadband region around the zero point to report 0.0 (optional)
sensor.setDeadband(0.015); sensor.setDeadband(0.015);
# Every tenth of a second, sample the ADXRS610 and output it's # Every tenth of a second, sample the ADXRS610 and output it's
# corresponding temperature and angular velocity # corresponding temperature and angular velocity
while (1): while (1):
print "Vel (deg/s):", sensor.getAngularVelocity() print "Vel (deg/s):", sensor.getAngularVelocity()
print "Temp (C):", sensor.getTemperature() print "Temp (C):", sensor.getTemperature()
time.sleep(.1) time.sleep(.1)
if __name__ == '__main__':
main()

81
examples/python/aeotecdsb09104.py Normal file → Executable file
View File

@ -24,65 +24,50 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ozw as sensorObj import pyupm_ozw as sensorObj
# This function lets you run code on exit def main():
def exitHandler(): # This function lets you run code on exit
print "Exiting" def exitHandler():
sys.exit(0) print "Exiting"
sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
defaultDev = "/dev/ttyACM0" defaultDev = "/dev/ttyACM0"
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
# Instantiate an Aeotec DSB09104 instance, on device node 12. You # Instantiate an Aeotec DSB09104 instance, on device node 12. You
# will almost certainly need to change this to reflect your own # will almost certainly need to change this to reflect your own
# network. Use the ozwdump example to see what nodes are available. # network. Use the ozwdump example to see what nodes are available.
sensor = sensorObj.AeotecDSB09104(12) sensor = sensorObj.AeotecDSB09104(12)
# The first thing to do is create options, then lock them when done. # The first thing to do is create options, then lock them when done.
sensor.optionsCreate() sensor.optionsCreate()
sensor.optionsLock() sensor.optionsLock()
# Next, initialize it. # Next, initialize it.
print "Initializing, this may take awhile depending on your ZWave network" print "Initializing, this may take awhile depending on your ZWave network"
sensor.init(defaultDev) sensor.init(defaultDev)
print "Initialization complete" print "Initialization complete"
print "Querying data..." print "Querying data..."
while (True): while (True):
sensor.update() sensor.update()
print "Watts, Channel 1:", print "Watts, Channel 1: %0.03f W" % sensor.getWattsC1()
print sensor.getWattsC1(), print "Watts, Channel 2: %0.03f W" % sensor.getWattsC2()
print "W" print "Watts, Channel 3: %0.03f W" % sensor.getWattsC3()
print "Watts, Channel 2:", print "Energy, Channel 1: %0.03f kWh" % sensor.getEnergyC1()
print sensor.getWattsC2(), print "Energy, Channel 2: %0.03f kWh" % sensor.getEnergyC2()
print "W" print "Energy, Channel 3: %0.03f kWh" % sensor.getEnergyC3()
print "Watts, Channel 3:", print "Battery Level: %d\n" % sensor.getBatteryLevel()
print sensor.getWattsC3(),
print "W"
print "Energy, Channel 1:",
print sensor.getEnergyC1(),
print "kWh"
print "Energy, Channel 2:",
print sensor.getEnergyC2(),
print "kWh"
print "Energy, Channel 3:",
print sensor.getEnergyC3(),
print "kWh"
print "Battery Level:",
print sensor.getBatteryLevel(),
print "%"
print
time.sleep(3) time.sleep(3)
if __name__ == '__main__':
main()

76
examples/python/aeotecdw2e.py Normal file → Executable file
View File

@ -24,57 +24,59 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ozw as sensorObj import pyupm_ozw as sensorObj
# This function lets you run code on exit def main():
def exitHandler(): # This function lets you run code on exit
print "Exiting" def exitHandler():
sys.exit(0) print "Exiting"
sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
defaultDev = "/dev/ttyACM0" defaultDev = "/dev/ttyACM0"
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
# Instantiate an Aeotec Door/Window 2nd Edition sensor instance, on # Instantiate an Aeotec Door/Window 2nd Edition sensor instance, on
# device node 10. You will almost certainly need to change this to # device node 10. You will almost certainly need to change this to
# reflect your own network. Use the ozwdump example to see what nodes # reflect your own network. Use the ozwdump example to see what nodes
# are available. # are available.
sensor = sensorObj.AeotecDW2E(10) sensor = sensorObj.AeotecDW2E(10)
# The first thing to do is create options, then lock them when done. # The first thing to do is create options, then lock them when done.
sensor.optionsCreate() sensor.optionsCreate()
sensor.optionsLock() sensor.optionsLock()
# Next, initialize it. # Next, initialize it.
print "Initializing, this may take awhile depending on your ZWave network" print "Initializing, this may take awhile depending on your ZWave network"
sensor.init(defaultDev) sensor.init(defaultDev)
print "Initialization complete" print "Initialization complete"
print "Querying data..." print "Querying data..."
while (True):
while (True):
if (sensor.isDeviceAvailable()): if (sensor.isDeviceAvailable()):
print "Alarm status:", print "Alarm status:",
print sensor.isAlarmTripped() print sensor.isAlarmTripped()
print "Tamper Switch status:", print "Tamper Switch status:",
print sensor.isTamperTripped() print sensor.isTamperTripped()
print "Battery Level:", print "Battery Level:",
print sensor.getBatteryLevel(), print sensor.getBatteryLevel(),
print "%" print "%"
print print
else: else:
print "Device has not yet responded to probe." print "Device has not yet responded to probe."
print "Try waking it, or wait until it wakes itself if ", print "Try waking it, or wait until it wakes itself if ",
print "configured to do so." print "configured to do so."
print
print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

64
examples/python/aeotecsdg2.py Normal file → Executable file
View File

@ -24,51 +24,52 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ozw as sensorObj import pyupm_ozw as sensorObj
# This function lets you run code on exit def main():
def exitHandler(): # This function lets you run code on exit
def exitHandler():
print "Turning switch off and sleeping for 5 seconds..." print "Turning switch off and sleeping for 5 seconds..."
sensor.off() sensor.off()
time.sleep(5) time.sleep(5)
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
defaultDev = "/dev/ttyACM0" defaultDev = "/dev/ttyACM0"
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
# Instantiate an Aeotec Smart Dimmer Gen2 instance, on device node # Instantiate an Aeotec Smart Dimmer Gen2 instance, on device node
# 9. You will almost certainly need to change this to reflect your # 9. You will almost certainly need to change this to reflect your
# own network. Use the ozwdump example to see what nodes are # own network. Use the ozwdump example to see what nodes are
# available. # available.
sensor = sensorObj.AeotecSDG2(9) sensor = sensorObj.AeotecSDG2(9)
# The first thing to do is create options, then lock them when done. # The first thing to do is create options, then lock them when done.
sensor.optionsCreate() sensor.optionsCreate()
sensor.optionsLock() sensor.optionsLock()
# Next, initialize it. # Next, initialize it.
print "Initializing, this may take awhile depending on your ZWave network" print "Initializing, this may take awhile depending on your ZWave network"
sensor.init(defaultDev) sensor.init(defaultDev)
print "Initialization complete" print "Initialization complete"
# turn light on # turn light on
print "Turning switch on, then sleeping for 5 secs" print "Turning switch on, then sleeping for 5 secs"
sensor.on(); sensor.on();
time.sleep(5); time.sleep(5);
print "Querying data..." print "Querying data..."
dim = False; dim = False;
while (True): while (True):
# put on a light show... # put on a light show...
if (dim): if (dim):
sensor.setLevel(25) sensor.setLevel(25)
else: else:
sensor.on() sensor.on()
dim = not dim; dim = not dim;
@ -94,3 +95,6 @@ while (True):
print print
time.sleep(5) time.sleep(5)
if __name__ == '__main__':
main()

56
examples/python/aeotecss6.py Normal file → Executable file
View File

@ -24,45 +24,46 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ozw as sensorObj import pyupm_ozw as sensorObj
# This function lets you run code on exit def main():
def exitHandler(): # This function lets you run code on exit
def exitHandler():
print "Turning switch off and sleeping for 5 seconds..." print "Turning switch off and sleeping for 5 seconds..."
sensor.off() sensor.off()
time.sleep(5) time.sleep(5)
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
defaultDev = "/dev/ttyACM0" defaultDev = "/dev/ttyACM0"
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
# Instantiate an Aeotec Smart Switch 6 instance, on device node 11. # Instantiate an Aeotec Smart Switch 6 instance, on device node 11.
# You will almost certainly need to change this to reflect your own # You will almost certainly need to change this to reflect your own
# network. Use the ozwdump example to see what nodes are available. # network. Use the ozwdump example to see what nodes are available.
sensor = sensorObj.AeotecSS6(11) sensor = sensorObj.AeotecSS6(11)
# The first thing to do is create options, then lock them when done. # The first thing to do is create options, then lock them when done.
sensor.optionsCreate() sensor.optionsCreate()
sensor.optionsLock() sensor.optionsLock()
# Next, initialize it. # Next, initialize it.
print "Initializing, this may take awhile depending on your ZWave network" print "Initializing, this may take awhile depending on your ZWave network"
sensor.init(defaultDev) sensor.init(defaultDev)
print "Initialization complete" print "Initialization complete"
# turn light on # turn light on
print "Turning switch on, then sleeping for 5 secs" print "Turning switch on, then sleeping for 5 secs"
sensor.on(); sensor.on();
time.sleep(5); time.sleep(5);
print "Querying data..." print "Querying data..."
while (True): while (True):
sensor.update() sensor.update()
print "Switch status:", print "Switch status:",
@ -85,3 +86,6 @@ while (True):
print print
time.sleep(3) time.sleep(3)
if __name__ == '__main__':
main()

44
examples/python/ak8975.py Normal file → Executable file
View File

@ -24,36 +24,40 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_mpu9150 as sensorObj import pyupm_mpu9150 as sensorObj
# Instantiate an AK8975 on I2C bus 0 def main():
sensor = sensorObj.AK8975() # Instantiate an AK8975 on I2C bus 0
sensor = sensorObj.AK8975()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
sensor.init() sensor.init()
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
while (1): while (1):
sensor.update() sensor.update()
sensor.getMagnetometer(x, y, z) sensor.getMagnetometer(x, y, z)
print "Magnetometer: MX: ", sensorObj.floatp_value(x), print "Magnetometer: MX: ", sensorObj.floatp_value(x),
print " MY: ", sensorObj.floatp_value(y), print " MY: ", sensorObj.floatp_value(y),
print " MZ: ", sensorObj.floatp_value(z) print " MZ: ", sensorObj.floatp_value(z)
print print
time.sleep(.5) time.sleep(.5)
if __name__ == '__main__':
main()

33
examples/python/apa102.py Normal file → Executable file
View File

@ -21,28 +21,29 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_apa102 as mylib import pyupm_apa102 as mylib
# Instantiate a strip of 30 LEDs on SPI bus 0 def main():
ledStrip = mylib.APA102(30, 0, False) # Instantiate a strip of 30 LEDs on SPI bus 0
ledStrip = mylib.APA102(30, 0, False)
## Exit handlers ## ## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C # This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# Register exit handlers # Register exit handlers
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
print "Setting all LEDs to Green" print "Setting all LEDs to Green"
ledStrip.setAllLeds(31, 0, 255, 0) ledStrip.setAllLeds(31, 0, 255, 0)
print "Setting LEDs between 10 and 20 to Red" print "Setting LEDs between 10 and 20 to Red"
ledStrip.setLeds(10, 20, 31, 255, 0, 0) ledStrip.setLeds(10, 20, 31, 255, 0, 0)
print "Setting LED 15 to Blue"
ledStrip.setLed(15, 31, 0, 0, 255)
print "Setting LED 15 to Blue"
ledStrip.setLed(15, 31, 0, 0, 255)
if __name__ == '__main__':
main()

38
examples/python/apds9002.py Normal file → Executable file
View File

@ -24,27 +24,29 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_apds9002 as upmApds9002 import pyupm_apds9002 as upmApds9002
# Instantiate a Grove Luminance sensor on analog pin A0 def main():
myLuminance = upmApds9002.APDS9002(0) # Instantiate a Grove Luminance sensor on analog pin A0
myLuminance = upmApds9002.APDS9002(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit, including functions from myLuminance
# This stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This lets you run code on exit, including functions from myLuminance # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) print "Luminance value is {0}".format(
signal.signal(signal.SIGINT, SIGINTHandler) myLuminance.value())
time.sleep(1)
while(1): if __name__ == '__main__':
print "Luminance value is {0}".format( main()
myLuminance.value())
time.sleep(1)

80
examples/python/at42qt1070.py Normal file → Executable file
View File

@ -24,56 +24,56 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_at42qt1070 as upmAt42qt1070 import pyupm_at42qt1070 as upmAt42qt1070
# functions def main():
def printButtons(touchObj): # functions
buttonPressed = False def printButtons(touchObj):
buttons = touchObj.getButtons() buttonPressed = False
buttons = touchObj.getButtons()
sys.stdout.write("Buttons Pressed: ") sys.stdout.write("Buttons Pressed: ")
for i in range(7): for i in range(7):
if (buttons & (1 << i)): if (buttons & (1 << i)):
sys.stdout.write(str(i) + " ") sys.stdout.write(str(i) + " ")
buttonPressed = True buttonPressed = True
if (not buttonPressed): if (not buttonPressed):
sys.stdout.write("None") sys.stdout.write("None")
print " " print " "
if (touchObj.isCalibrating()): if (touchObj.isCalibrating()):
print "Calibration is occurring." print "Calibration is occurring."
if (touchObj.isOverflowed()): if (touchObj.isOverflowed()):
print "Overflow was detected." print "Overflow was detected."
# Global code that runs on startup
# Global code that runs on startup I2C_BUS = upmAt42qt1070.AT42QT1070_I2C_BUS
DEFAULT_I2C_ADDR = upmAt42qt1070.AT42QT1070_DEFAULT_I2C_ADDR
I2C_BUS = upmAt42qt1070.AT42QT1070_I2C_BUS # Instantiate an AT42QT1070 on I2C bus 0
DEFAULT_I2C_ADDR = upmAt42qt1070.AT42QT1070_DEFAULT_I2C_ADDR myTouchSensor = upmAt42qt1070.AT42QT1070(I2C_BUS,
DEFAULT_I2C_ADDR)
# Instantiate an AT42QT1070 on I2C bus 0 # Exit handlers
myTouchSensor = upmAt42qt1070.AT42QT1070(I2C_BUS, def SIGINTHandler(signum, frame):
DEFAULT_I2C_ADDR) raise SystemExit
def exitHandler():
print "Exiting"
sys.exit(0)
# Exit handlers # This function lets you run code on exit, including functions from myTouchSensor
def SIGINTHandler(signum, frame): atexit.register(exitHandler)
raise SystemExit # This function stops python from printing a stacktrace when you hit control-C
signal.signal(signal.SIGINT, SIGINTHandler)
def exitHandler(): # Print the button being touched every 0.1 seconds
print "Exiting" while(1):
sys.exit(0) myTouchSensor.updateState()
printButtons(myTouchSensor)
time.sleep(.1)
if __name__ == '__main__':
# This function lets you run code on exit, including functions from myTouchSensor main()
atexit.register(exitHandler)
# This function stops python from printing a stacktrace when you hit control-C
signal.signal(signal.SIGINT, SIGINTHandler)
# Print the button being touched every 0.1 seconds
while(1):
myTouchSensor.updateState()
printButtons(myTouchSensor)
time.sleep(.1)

40
examples/python/bh1750.py Normal file → Executable file
View File

@ -24,27 +24,31 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bh1750 as sensorObj import pyupm_bh1750 as sensorObj
# Instantiate a BH1750 sensor using defaults (I2C bus (0), using def main():
# the default I2C address (0x23), and setting the mode to highest # Instantiate a BH1750 sensor using defaults (I2C bus (0), using
# resolution, lowest power mode). # the default I2C address (0x23), and setting the mode to highest
sensor = sensorObj.BH1750() # resolution, lowest power mode).
sensor = sensorObj.BH1750()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Every second, sample the BH1750 and output the measured lux value # Every second, sample the BH1750 and output the measured lux value
while (True): while (True):
print "Detected Light Level (lux):", sensor.getLux() print "Detected Light Level (lux):", sensor.getLux()
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

44
examples/python/biss0001.py Normal file → Executable file
View File

@ -24,29 +24,31 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_biss0001 as upmMotion import pyupm_biss0001 as upmMotion
# Instantiate a Grove Motion sensor on GPIO pin D2 def main():
myMotion = upmMotion.BISS0001(2) # Instantiate a Grove Motion sensor on GPIO pin D2
myMotion = upmMotion.BISS0001(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myMotion
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myMotion # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers # Read the value every second and detect motion
atexit.register(exitHandler) while(1):
signal.signal(signal.SIGINT, SIGINTHandler) if (myMotion.value()):
print "Detecting moving object"
else:
print "No moving objects detected"
time.sleep(1)
if __name__ == '__main__':
# Read the value every second and detect motion main()
while(1):
if (myMotion.value()):
print "Detecting moving object"
else:
print "No moving objects detected"
time.sleep(1)

42
examples/python/bma220.py Normal file → Executable file
View File

@ -24,32 +24,36 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bma220 as sensorObj import pyupm_bma220 as sensorObj
# Instantiate an BMA220 using default parameters (bus 0, addr 0x0a) def main():
sensor = sensorObj.BMA220() # Instantiate an BMA220 using default parameters (bus 0, addr 0x0a)
sensor = sensorObj.BMA220()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
while (1): while (1):
sensor.update() sensor.update()
sensor.getAccelerometer(x, y, z) sensor.getAccelerometer(x, y, z)
print "Accelerometer: AX:", sensorObj.floatp_value(x), print "Accelerometer: AX:", sensorObj.floatp_value(x),
print " AY:", sensorObj.floatp_value(y), print " AY:", sensorObj.floatp_value(y),
print " AZ:", sensorObj.floatp_value(z) print " AZ:", sensorObj.floatp_value(z)
time.sleep(.5) time.sleep(.5)
if __name__ == '__main__':
main()

46
examples/python/bma250e.py Normal file → Executable file
View File

@ -24,32 +24,33 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmx055 as sensorObj import pyupm_bmx055 as sensorObj
# Instantiate a BMP250E instance using default i2c bus and address def main():
sensor = sensorObj.BMA250E() # Instantiate a BMP250E instance using default i2c bus and address
sensor = sensorObj.BMA250E()
# For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS:
# BMA250E(0, -1, 10); # BMA250E(0, -1, 10);
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
# now output data every 250 milliseconds # now output data every 250 milliseconds
while (1): while (1):
sensor.update() sensor.update()
sensor.getAccelerometer(x, y, z) sensor.getAccelerometer(x, y, z)
@ -63,4 +64,7 @@ while (1):
print sensor.getTemperature(True), "F" print sensor.getTemperature(True), "F"
print print
time.sleep(.250) time.sleep(.250)
if __name__ == '__main__':
main()

42
examples/python/bmc150.py Normal file → Executable file
View File

@ -24,29 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmx055 as sensorObj import pyupm_bmx055 as sensorObj
# Instantiate a BMC150 instance using default i2c bus and address def main():
sensor = sensorObj.BMC150() # Instantiate a BMC150 instance using default i2c bus and address
sensor = sensorObj.BMC150()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
# now output data every 250 milliseconds # now output data every 250 milliseconds
while (1): while (1):
sensor.update() sensor.update()
sensor.getAccelerometer(x, y, z) sensor.getAccelerometer(x, y, z)
@ -62,4 +63,7 @@ while (1):
print " uT" print " uT"
print print
time.sleep(.250) time.sleep(.250)
if __name__ == '__main__':
main()

38
examples/python/bme280.py Normal file → Executable file
View File

@ -24,27 +24,28 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmp280 as sensorObj import pyupm_bmp280 as sensorObj
# Instantiate a BME280 instance using default i2c bus and address def main():
sensor = sensorObj.BME280() # Instantiate a BME280 instance using default i2c bus and address
sensor = sensorObj.BME280()
# For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS:
# BME280(0, -1, 10); # BME280(0, -1, 10);
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
while (1): while (1):
sensor.update() sensor.update()
print "Compensation Temperature:", sensor.getTemperature(), "C /", print "Compensation Temperature:", sensor.getTemperature(), "C /",
@ -57,4 +58,7 @@ while (1):
print "Humidity:", sensor.getHumidity(), "%RH" print "Humidity:", sensor.getHumidity(), "%RH"
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

46
examples/python/bmg160.py Normal file → Executable file
View File

@ -24,32 +24,33 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmx055 as sensorObj import pyupm_bmx055 as sensorObj
# Instantiate a BMP250E instance using default i2c bus and address def main():
sensor = sensorObj.BMG160() # Instantiate a BMP250E instance using default i2c bus and address
sensor = sensorObj.BMG160()
# For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS:
# BMG160(0, -1, 10); # BMG160(0, -1, 10);
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
# now output data every 250 milliseconds # now output data every 250 milliseconds
while (1): while (1):
sensor.update() sensor.update()
sensor.getGyroscope(x, y, z) sensor.getGyroscope(x, y, z)
@ -63,4 +64,7 @@ while (1):
print sensor.getTemperature(True), "F" print sensor.getTemperature(True), "F"
print print
time.sleep(.250) time.sleep(.250)
if __name__ == '__main__':
main()

42
examples/python/bmi055.py Normal file → Executable file
View File

@ -24,29 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmx055 as sensorObj import pyupm_bmx055 as sensorObj
# Instantiate a BMI055 instance using default i2c bus and address def main():
sensor = sensorObj.BMI055() # Instantiate a BMI055 instance using default i2c bus and address
sensor = sensorObj.BMI055()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
# now output data every 250 milliseconds # now output data every 250 milliseconds
while (1): while (1):
sensor.update() sensor.update()
sensor.getAccelerometer(x, y, z) sensor.getAccelerometer(x, y, z)
@ -62,4 +63,7 @@ while (1):
print " degrees/s" print " degrees/s"
print print
time.sleep(.250) time.sleep(.250)
if __name__ == '__main__':
main()

40
examples/python/bmi160.py Normal file → Executable file
View File

@ -24,28 +24,29 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmi160 as sensorObj import pyupm_bmi160 as sensorObj
# Instantiate a BMI160 instance using default i2c bus and address def main():
sensor = sensorObj.BMI160() # Instantiate a BMI160 instance using default i2c bus and address
sensor = sensorObj.BMI160()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
while (1): while (1):
sensor.update() sensor.update()
sensor.getAccelerometer(x, y, z) sensor.getAccelerometer(x, y, z)
print "Accelerometer: AX: ", sensorObj.floatp_value(x), print "Accelerometer: AX: ", sensorObj.floatp_value(x),
@ -63,4 +64,7 @@ while (1):
print " MZ: ", sensorObj.floatp_value(z) print " MZ: ", sensorObj.floatp_value(z)
print print
time.sleep(.5) time.sleep(.5)
if __name__ == '__main__':
main()

46
examples/python/bmm150.py Normal file → Executable file
View File

@ -24,32 +24,33 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmx055 as sensorObj import pyupm_bmx055 as sensorObj
# Instantiate a BMP250E instance using default i2c bus and address def main():
sensor = sensorObj.BMM150() # Instantiate a BMP250E instance using default i2c bus and address
sensor = sensorObj.BMM150()
# For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS:
# BMM150(0, -1, 10); # BMM150(0, -1, 10);
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
# now output data every 250 milliseconds # now output data every 250 milliseconds
while (1): while (1):
sensor.update() sensor.update()
sensor.getMagnetometer(x, y, z) sensor.getMagnetometer(x, y, z)
@ -59,4 +60,7 @@ while (1):
print " uT" print " uT"
print print
time.sleep(.250) time.sleep(.250)
if __name__ == '__main__':
main()

38
examples/python/bmp280.py Normal file → Executable file
View File

@ -24,27 +24,28 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmp280 as sensorObj import pyupm_bmp280 as sensorObj
# Instantiate a BMP280 instance using default i2c bus and address def main():
sensor = sensorObj.BMP280() # Instantiate a BMP280 instance using default i2c bus and address
sensor = sensorObj.BMP280()
# For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS:
# BMP280(0, -1, 10); # BMP280(0, -1, 10);
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
while (1): while (1):
sensor.update() sensor.update()
print "Compensation Temperature:", sensor.getTemperature(), "C /", print "Compensation Temperature:", sensor.getTemperature(), "C /",
@ -55,4 +56,7 @@ while (1):
print "Computed Altitude:", sensor.getAltitude(), "m" print "Computed Altitude:", sensor.getAltitude(), "m"
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

56
examples/python/bmpx8x.py Normal file → Executable file
View File

@ -24,36 +24,38 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmpx8x as upmBmpx8x import pyupm_bmpx8x as upmBmpx8x
# Load Barometer module on i2c def main():
myBarometer = upmBmpx8x.BMPX8X(0, upmBmpx8x.ADDR); # Load Barometer module on i2c
myBarometer = upmBmpx8x.BMPX8X(0, upmBmpx8x.ADDR);
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myBarometer
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myBarometer # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers # Print the pressure, altitude, sea level, and
atexit.register(exitHandler) # temperature values every 0.1 seconds
signal.signal(signal.SIGINT, SIGINTHandler) while(1):
outputStr = ("pressure value = {0}"
", altitude value = {1}"
", sealevel value = {2}"
", temperature = {3}".format(
myBarometer.getPressure(),
myBarometer.getTemperature(),
myBarometer.getAltitude(),
myBarometer.getSealevelPressure()))
print outputStr
time.sleep(.1)
# Print the pressure, altitude, sea level, and if __name__ == '__main__':
# temperature values every 0.1 seconds main()
while(1):
outputStr = ("pressure value = {0}"
", altitude value = {1}"
", sealevel value = {2}"
", temperature = {3}".format(
myBarometer.getPressure(),
myBarometer.getTemperature(),
myBarometer.getAltitude(),
myBarometer.getSealevelPressure()))
print outputStr
time.sleep(.1)

42
examples/python/bmx055.py Normal file → Executable file
View File

@ -24,29 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bmx055 as sensorObj import pyupm_bmx055 as sensorObj
# Instantiate a BMX055 instance using default i2c bus and address def main():
sensor = sensorObj.BMX055() # Instantiate a BMX055 instance using default i2c bus and address
sensor = sensorObj.BMX055()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
# now output data every 250 milliseconds # now output data every 250 milliseconds
while (1): while (1):
sensor.update() sensor.update()
sensor.getAccelerometer(x, y, z) sensor.getAccelerometer(x, y, z)
@ -68,4 +69,7 @@ while (1):
print " uT" print " uT"
print print
time.sleep(.250) time.sleep(.250)
if __name__ == '__main__':
main()

76
examples/python/bno055.py Normal file → Executable file
View File

@ -24,57 +24,58 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_bno055 as sensorObj import pyupm_bno055 as sensorObj
# Instantiate an BNO055 using default parameters (bus 0, addr def main():
# 0x28). The default running mode is NDOF absolute orientation # Instantiate an BNO055 using default parameters (bus 0, addr
# mode. # 0x28). The default running mode is NDOF absolute orientation
sensor = sensorObj.BNO055() # mode.
sensor = sensorObj.BNO055()
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting..." print "Exiting..."
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
mag = sensorObj.new_intp() mag = sensorObj.new_intp()
acc = sensorObj.new_intp() acc = sensorObj.new_intp()
gyr = sensorObj.new_intp() gyr = sensorObj.new_intp()
syst = sensorObj.new_intp() syst = sensorObj.new_intp()
w = sensorObj.new_floatp() w = sensorObj.new_floatp()
x = sensorObj.new_floatp() x = sensorObj.new_floatp()
y = sensorObj.new_floatp() y = sensorObj.new_floatp()
z = sensorObj.new_floatp() z = sensorObj.new_floatp()
print "First we need to calibrate. 4 numbers will be output every" print "First we need to calibrate. 4 numbers will be output every"
print "second for each sensor. 0 means uncalibrated, and 3 means" print "second for each sensor. 0 means uncalibrated, and 3 means"
print "fully calibrated." print "fully calibrated."
print "See the UPM documentation on this sensor for instructions on" print "See the UPM documentation on this sensor for instructions on"
print "what actions are required to calibrate." print "what actions are required to calibrate."
print print
while (not sensor.isFullyCalibrated()): while (not sensor.isFullyCalibrated()):
sensor.getCalibrationStatus(mag, acc, gyr, syst) sensor.getCalibrationStatus(mag, acc, gyr, syst)
print "Magnetometer:", sensorObj.intp_value(mag), print "Magnetometer:", sensorObj.intp_value(mag),
print " Accelerometer:", sensorObj.intp_value(acc), print " Accelerometer:", sensorObj.intp_value(acc),
print " Gyroscope:", sensorObj.intp_value(gyr), print " Gyroscope:", sensorObj.intp_value(gyr),
print " System:", sensorObj.intp_value(syst), print " System:", sensorObj.intp_value(syst),
time.sleep(1) time.sleep(1)
print print
print "Calibration complete." print "Calibration complete."
print print
# now output various fusion data every 250 milliseconds # now output various fusion data every 250 milliseconds
while (True): while (True):
sensor.update() sensor.update()
sensor.getEulerAngles(x, y, z) sensor.getEulerAngles(x, y, z)
@ -103,3 +104,6 @@ while (True):
print print
time.sleep(.25); time.sleep(.25);
if __name__ == '__main__':
main()

20
examples/python/button.py Normal file → Executable file
View File

@ -23,13 +23,17 @@
import time import time
import pyupm_grove as grove import pyupm_grove as grove
# Create the button object using GPIO pin 0 def main():
button = grove.Button(0) # Create the button object using GPIO pin 0
button = grove.Button(0)
# Read the input and print, waiting one second between readings # Read the input and print, waiting one second between readings
while 1: while 1:
print button.name(), ' value is ', button.value() print button.name(), ' value is ', button.value()
time.sleep(1) time.sleep(1)
# Delete the button object # Delete the button object
del button del button
if __name__ == '__main__':
main()

34
examples/python/buzzer.py Normal file → Executable file
View File

@ -23,23 +23,27 @@
import time import time
import pyupm_buzzer as upmBuzzer import pyupm_buzzer as upmBuzzer
# Create the buzzer object using GPIO pin 5 def main():
buzzer = upmBuzzer.Buzzer(5) # Create the buzzer object using GPIO pin 5
buzzer = upmBuzzer.Buzzer(5)
chords = [upmBuzzer.DO, upmBuzzer.RE, upmBuzzer.MI, upmBuzzer.FA, chords = [upmBuzzer.DO, upmBuzzer.RE, upmBuzzer.MI, upmBuzzer.FA,
upmBuzzer.SOL, upmBuzzer.LA, upmBuzzer.SI, upmBuzzer.DO, upmBuzzer.SOL, upmBuzzer.LA, upmBuzzer.SI, upmBuzzer.DO,
upmBuzzer.SI]; upmBuzzer.SI];
# Print sensor name # Print sensor name
print buzzer.name() print buzzer.name()
# Play sound (DO, RE, MI, etc.), pausing for 0.1 seconds between notes # Play sound (DO, RE, MI, etc.), pausing for 0.1 seconds between notes
for chord_ind in range (0,7): for chord_ind in range (0,7):
# play each note for one second # play each note for one second
print buzzer.playSound(chords[chord_ind], 1000000) print buzzer.playSound(chords[chord_ind], 1000000)
time.sleep(0.1) time.sleep(0.1)
print "exiting application" print "exiting application"
# Delete the buzzer object # Delete the buzzer object
del buzzer del buzzer
if __name__ == '__main__':
main()

33
examples/python/cjq4435.py Normal file → Executable file
View File

@ -25,22 +25,25 @@ from __future__ import division
import time import time
import pyupm_cjq4435 as upmCjq4435 import pyupm_cjq4435 as upmCjq4435
# Instantiate a CJQ4435 MOSFET on a PWM capable digital pin D3 def main():
myMOSFETsensor = upmCjq4435.CJQ4435(3) # Instantiate a CJQ4435 MOSFET on a PWM capable digital pin D3
myMOSFETsensor = upmCjq4435.CJQ4435(3)
myMOSFETsensor.setPeriodMS(10)
myMOSFETsensor.enable(True)
myMOSFETsensor.setPeriodMS(10) # start with a duty cycle of 0.0 (off) and increment to 1.0 (on)
myMOSFETsensor.enable(True) for i in range(11):
myMOSFETsensor.setDutyCycle(i / 10)
time.sleep(.1)
time.sleep(1)
# start with a duty cycle of 0.0 (off) and increment to 1.0 (on) # Now take it back down
for i in range(11): # start with a duty cycle of 1.0 (on) and decrement to 0.0 (off)
myMOSFETsensor.setDutyCycle(i / 10) for i in range(10, -1, -1):
time.sleep(.1) myMOSFETsensor.setDutyCycle(i / 10)
time.sleep(1) time.sleep(.1)
time.sleep(1)
# Now take it back down if __name__ == '__main__':
# start with a duty cycle of 1.0 (on) and decrement to 0.0 (off) main()
for i in range(10, -1, -1):
myMOSFETsensor.setDutyCycle(i / 10)
time.sleep(.1)
time.sleep(1)

52
examples/python/collision.py Normal file → Executable file
View File

@ -24,34 +24,36 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_collision as upmcollision import pyupm_collision as upmcollision
# The was tested with the Collision Sensor def main():
# Instantiate a Collision on digital pin D2 # The was tested with the Collision Sensor
mycollision = upmcollision.Collision(2) # Instantiate a Collision on digital pin D2
mycollision = upmcollision.Collision(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myGrovecollision
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myGrovecollision atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers collisionState = False
atexit.register(exitHandler) print "No collision"
signal.signal(signal.SIGINT, SIGINTHandler)
while(1):
if (mycollision.isColliding() and not collisionState):
print "Collision!"
collisionState = True
elif (not mycollision.isColliding() and collisionState):
print "No collision"
collisionState = False
collisionState = False if __name__ == '__main__':
print "No collision" main()
while(1):
if (mycollision.isColliding() and not collisionState):
print "Collision!"
collisionState = True
elif (not mycollision.isColliding() and collisionState):
print "No collision"
collisionState = False

38
examples/python/curieimu.py Normal file → Executable file
View File

@ -30,27 +30,31 @@ mraa.addSubplatform(mraa.GENERIC_FIRMATA, "/dev/ttyACM0")
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_curieimu as curieimu import pyupm_curieimu as curieimu
sensor = curieimu.CurieImu()
## Exit handlers ## def main():
def SIGINTHandler(signum, frame): sensor = curieimu.CurieImu()
raise SystemExit
def exitHandler(): ## Exit handlers ##
print "Exiting" def SIGINTHandler(signum, frame):
sys.exit(0) raise SystemExit
# Register exit handlers def exitHandler():
atexit.register(exitHandler) print "Exiting"
signal.signal(signal.SIGINT, SIGINTHandler) sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
while(1): while(1):
sensor.updateAccel(); sensor.updateAccel();
outputStr = "acc: gX {0} - gY {1} - gZ {2}".format( outputStr = "acc: gX {0} - gY {1} - gZ {2}".format(
sensor.getAccelX(), sensor.getAccelY(), sensor.getAccelX(), sensor.getAccelY(),
sensor.getAccelZ()) sensor.getAccelZ())
print outputStr print outputStr
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

40
examples/python/cwlsxxa.py Normal file → Executable file
View File

@ -24,28 +24,29 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_cwlsxxa as sensorObj import pyupm_cwlsxxa as sensorObj
## Exit handlers ## def main():
# This function stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This function stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..." print "Initializing..."
# Instantiate an CWLSXXA instance, using A0 for CO2, A1 for # Instantiate an CWLSXXA instance, using A0 for CO2, A1 for
# humidity and A2 for temperature # humidity and A2 for temperature
sensor = sensorObj.CWLSXXA(0, 1, 2) sensor = sensorObj.CWLSXXA(0, 1, 2)
# update and print available values every second # update and print available values every second
while (1): while (1):
# update our values from the sensor # update our values from the sensor
sensor.update() sensor.update()
@ -58,4 +59,7 @@ while (1):
print "CO2:", sensor.getCO2(), "ppm" print "CO2:", sensor.getCO2(), "ppm"
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

42
examples/python/dfrec.py Normal file → Executable file
View File

@ -24,28 +24,29 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_dfrec as sensorObj import pyupm_dfrec as sensorObj
# Instantiate a DFRobot EC sensor on analog pin A0, with a ds18b20 def main():
# temperature sensor connected to UART 0, and a device index (for # Instantiate a DFRobot EC sensor on analog pin A0, with a ds18b20
# the ds1820b uart bus) of 0, and an analog reference voltage of # temperature sensor connected to UART 0, and a device index (for
# 5.0. # the ds1820b uart bus) of 0, and an analog reference voltage of
sensor = sensorObj.DFREC(0, 0, 0, 5.0) # 5.0.
sensor = sensorObj.DFREC(0, 0, 0, 5.0)
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Every 2 seconds, update and print values # Every 2 seconds, update and print values
while (True): while (True):
sensor.update() sensor.update()
print "EC =", sensor.getEC(), "ms/cm" print "EC =", sensor.getEC(), "ms/cm"
@ -53,4 +54,7 @@ while (True):
print ", Temperature = ", sensor.getTemperature(), "C" print ", Temperature = ", sensor.getTemperature(), "C"
print print
time.sleep(2) time.sleep(2)
if __name__ == '__main__':
main()

66
examples/python/dfrorp.py Normal file → Executable file
View File

@ -24,45 +24,49 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_dfrorp as sensorObj import pyupm_dfrorp as sensorObj
# Instantiate a DFRobot ORP sensor on analog pin A0 with an analog def main():
# reference voltage of 5.0. # Instantiate a DFRobot ORP sensor on analog pin A0 with an analog
sensor = sensorObj.DFRORP(0, 5.0) # reference voltage of 5.0.
sensor = sensorObj.DFRORP(0, 5.0)
# To calibrate: # To calibrate:
# #
# Disconnect the sensor probe (but leave the sensor interface board # Disconnect the sensor probe (but leave the sensor interface board
# connected). Then run one of the examples while holding down the # connected). Then run one of the examples while holding down the
# 'calibrate' button on the device. Read the ORP value reported # 'calibrate' button on the device. Read the ORP value reported
# (it should be fairly small). # (it should be fairly small).
# #
# This value is what you should supply to setCalibrationOffset(). # This value is what you should supply to setCalibrationOffset().
# Then reconnect the probe to the interface board and you should be # Then reconnect the probe to the interface board and you should be
# ready to go. # ready to go.
# #
# DO NOT press the calibrate button on the interface board while # DO NOT press the calibrate button on the interface board while
# the probe is attached or you can permanently damage the probe. # the probe is attached or you can permanently damage the probe.
sensor.setCalibrationOffset(0.97); sensor.setCalibrationOffset(0.97);
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Every second, update and print values # Every second, update and print values
while (True): while (True):
sensor.update() sensor.update()
print "ORP:", sensor.getORP(), "mV" print "ORP:", sensor.getORP(), "mV"
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

48
examples/python/dfrph.py Normal file → Executable file
View File

@ -24,33 +24,37 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_dfrph as sensorObj import pyupm_dfrph as sensorObj
# Instantiate a DFRPH sensor on analog pin A0, with an analog def main():
# reference voltage of 5.0 # Instantiate a DFRPH sensor on analog pin A0, with an analog
sensor = sensorObj.DFRPH(0, 5.0) # reference voltage of 5.0
sensor = sensorObj.DFRPH(0, 5.0)
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# After calibration, set the offset (based on calibration with a pH # After calibration, set the offset (based on calibration with a pH
# 7.0 buffer solution). See the UPM sensor documentation for # 7.0 buffer solution). See the UPM sensor documentation for
# calibrations instructions. # calibrations instructions.
sensor.setOffset(0.065); sensor.setOffset(0.065);
# Every second, sample the pH and output it's corresponding # Every second, sample the pH and output it's corresponding
# analog voltage. # analog voltage.
while (1): while (1):
print "Detected volts: ", sensor.volts() print "Detected volts: ", sensor.volts()
print "pH value: ", sensor.pH() print "pH value: ", sensor.pH()
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

53
examples/python/ds1307.py Normal file → Executable file
View File

@ -24,37 +24,40 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ds1307 as upmDs1307 import pyupm_ds1307 as upmDs1307
# load RTC clock on i2c bus 0 def main():
myRTCClock = upmDs1307.DS1307(0) # load RTC clock on i2c bus 0
myRTCClock = upmDs1307.DS1307(0)
def printTime(RTCObj): def printTime(RTCObj):
timeStr = "The time is: {0}/{1}/{2} {3}:{4}:{5}".format( timeStr = "The time is: {0}/{1}/{2} {3}:{4}:{5}".format(
RTCObj.month, RTCObj.dayOfMonth, RTCObj.year, RTCObj.month, RTCObj.dayOfMonth, RTCObj.year,
RTCObj.hours, RTCObj.minutes, RTCObj.seconds) RTCObj.hours, RTCObj.minutes, RTCObj.seconds)
if (RTCObj.amPmMode): if (RTCObj.amPmMode):
timeStr += (" PM " if RTCObj.pm else " AM ") timeStr += (" PM " if RTCObj.pm else " AM ")
print timeStr print timeStr
print "Clock is in", ("AM/PM mode" print "Clock is in", ("AM/PM mode"
if RTCObj.amPmMode else "24hr mode") if RTCObj.amPmMode else "24hr mode")
# always do this first
print "Loading the current time... "
result = myRTCClock.loadTime()
if (not result):
print "myRTCClock.loadTime() failed."
sys.exit(0)
# always do this first printTime(myRTCClock);
print "Loading the current time... "
result = myRTCClock.loadTime()
if (not result):
print "myRTCClock.loadTime() failed."
sys.exit(0)
printTime(myRTCClock); # set the year as an example
print "setting the year to 50"
myRTCClock.year = 50
myRTCClock.setTime()
# set the year as an example # reload the time and print it
print "setting the year to 50" myRTCClock.loadTime()
myRTCClock.year = 50 printTime(myRTCClock)
myRTCClock.setTime()
# reload the time and print it if __name__ == '__main__':
myRTCClock.loadTime() main()
printTime(myRTCClock)

48
examples/python/ds18b20.py Normal file → Executable file
View File

@ -24,36 +24,37 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ds18b20 as sensorObj import pyupm_ds18b20 as sensorObj
## Exit handlers ## def main():
# This function stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This function stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting..." print "Exiting..."
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..." print "Initializing..."
# Instantiate an DS18B20 instance using the default values (uart 0) # Instantiate an DS18B20 instance using the default values (uart 0)
sensor = sensorObj.DS18B20(0) sensor = sensorObj.DS18B20(0)
# locate and setup our devices # locate and setup our devices
sensor.init() sensor.init()
print "Found", sensor.devicesFound(), "device(s)" print "Found", sensor.devicesFound(), "device(s)"
print print
if (not sensor.devicesFound()): if (not sensor.devicesFound()):
sys.exit(1); sys.exit(1);
# update and print available values every second # update and print available values every second
while (1): while (1):
# update our values for the first sensor # update our values for the first sensor
sensor.update(0) sensor.update(0)
@ -61,4 +62,7 @@ while (1):
print "Temperature:", sensor.getTemperature(0), "C /", print "Temperature:", sensor.getTemperature(0), "C /",
print sensor.getTemperature(0, True), "F" print sensor.getTemperature(0, True), "F"
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

52
examples/python/ds2413.py Normal file → Executable file
View File

@ -24,34 +24,38 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ds2413 as sensorObj import pyupm_ds2413 as sensorObj
# Instantiate a DS2413 Module on a Dallas 1-wire bus connected to UART 0 def main():
sensor = sensorObj.DS2413(0) # Instantiate a DS2413 Module on a Dallas 1-wire bus connected to UART 0
sensor = sensorObj.DS2413(0)
## Exit handlers ## ## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C # This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting..." print "Exiting..."
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# find all of the DS2413 devices present on the bus # find all of the DS2413 devices present on the bus
sensor.init(); sensor.init();
# how many devices were found? # how many devices were found?
print "Found", sensor.devicesFound(), "device(s)" print "Found", sensor.devicesFound(), "device(s)"
# read the gpio and latch values from the first device # read the gpio and latch values from the first device
# the lower 4 bits are of the form: # the lower 4 bits are of the form:
# <gpioB latch> <gpioB value> <gpioA latch> <gpioA value> # <gpioB latch> <gpioB value> <gpioA latch> <gpioA value>
print "GPIO device 0 values:", sensor.readGpios(0) print "GPIO device 0 values:", sensor.readGpios(0)
# set the gpio latch values of the first device # set the gpio latch values of the first device
print "Setting GPIO latches to on" print "Setting GPIO latches to on"
sensor.writeGpios(0, 0x03); sensor.writeGpios(0, 0x03);
if __name__ == '__main__':
main()

84
examples/python/e50hx.py Normal file → Executable file
View File

@ -24,57 +24,58 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_e50hx as sensorObj import pyupm_e50hx as sensorObj
## Exit handlers ## def main():
# This function stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This function stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting..." print "Exiting..."
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# You will need to edit this example to conform to your site and your # You will need to edit this example to conform to your site and your
# devices, specifically the Device Object Instance ID passed to the # devices, specifically the Device Object Instance ID passed to the
# constructor, and the arguments to initMaster() that are # constructor, and the arguments to initMaster() that are
# appropriate for your BACnet network. # appropriate for your BACnet network.
defaultDev = "/dev/ttyUSB0" defaultDev = "/dev/ttyUSB0"
# if an argument was specified, use it as the device instead # if an argument was specified, use it as the device instead
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
print "Initializing..." print "Initializing..."
# Instantiate an E50HX object for an E50HX device that has 1075425 # Instantiate an E50HX object for an E50HX device that has 1075425
# as it's unique Device Object Instance ID. NOTE: You will # as it's unique Device Object Instance ID. NOTE: You will
# certainly want to change this to the correct value for your # certainly want to change this to the correct value for your
# device(s). # device(s).
sensor = sensorObj.E50HX(1075425) sensor = sensorObj.E50HX(1075425)
# Initialize our BACnet master, if it has not already been # Initialize our BACnet master, if it has not already been
# initialized, with the device and baudrate, choosing 1000001 as # initialized, with the device and baudrate, choosing 1000001 as
# our unique Device Object Instance ID, 2 as our MAC address and # our unique Device Object Instance ID, 2 as our MAC address and
# using default values for maxMaster and maxInfoFrames # using default values for maxMaster and maxInfoFrames
sensor.initMaster(defaultDev, 38400, 1000001, 2) sensor.initMaster(defaultDev, 38400, 1000001, 2)
# Uncomment to enable debugging output # Uncomment to enable debugging output
# sensor.setDebug(True); # sensor.setDebug(True);
# output the serial number and firmware revision # output the serial number and firmware revision
print print
print "Device Description:", sensor.getDeviceDescription() print "Device Description:", sensor.getDeviceDescription()
print "Device Location:", sensor.getDeviceLocation() print "Device Location:", sensor.getDeviceLocation()
print print
# update and print available values every second # update and print available values every second
while (1): while (1):
print "System Voltage:", print "System Voltage:",
print sensor.getAnalogValue(sensorObj.E50HX.AV_System_Voltage), print sensor.getAnalogValue(sensorObj.E50HX.AV_System_Voltage),
print " ", print " ",
@ -92,4 +93,7 @@ while (1):
print sensor.getAnalogInput(sensorObj.E50HX.AI_Power_Up_Count) print sensor.getAnalogInput(sensorObj.E50HX.AI_Power_Up_Count)
print print
time.sleep(5) time.sleep(5)
if __name__ == '__main__':
main()

25
examples/python/eboled.py Normal file → Executable file
View File

@ -25,17 +25,18 @@ import time, sys
import pyupm_i2clcd as lcdObj import pyupm_i2clcd as lcdObj
# setup with default values def main():
lcd = lcdObj.EBOLED(); # setup with default values
lcd = lcdObj.EBOLED();
lcd.clear();
lcd.setCursor(10, 15);
lcd.write("Hello");
lcd.setCursor(30, 15);
lcd.write("World!");
lcd.refresh();
print "Sleeping for 5 seconds..."
time.sleep(5)
lcd.clear();
lcd.setCursor(10, 15);
lcd.write("Hello");
lcd.setCursor(30, 15);
lcd.write("World!");
lcd.refresh();
print "Sleeping for 5 seconds..."
time.sleep(5)
if __name__ == '__main__':
main()

69
examples/python/ehr.py Normal file → Executable file
View File

@ -21,48 +21,49 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ehr as upmehr import pyupm_ehr as upmehr
# Instantiate a Ear-clip Heart Rate sensor on digital pin D2 def main():
myHeartRateSensor = upmehr.EHR(2) # Instantiate a Ear-clip Heart Rate sensor on digital pin D2
myHeartRateSensor = upmehr.EHR(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myHeartRateSensor
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit myHeartRateSensor.stopBeatCounter()
print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myHeartRateSensor atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
myHeartRateSensor.stopBeatCounter()
print "Exiting"
sys.exit(0)
# Register exit handlers # set the beat counter to 0, init the clock and start counting beats
atexit.register(exitHandler) myHeartRateSensor.clearBeatCounter()
signal.signal(signal.SIGINT, SIGINTHandler) myHeartRateSensor.initClock()
myHeartRateSensor.startBeatCounter()
while(1):
# we grab these (millis and flowCount) just for display
# purposes in this example
millis = myHeartRateSensor.getMillis()
beats = myHeartRateSensor.beatCounter()
# set the beat counter to 0, init the clock and start counting beats # heartRate() requires that at least 5 seconds pass before
myHeartRateSensor.clearBeatCounter() # returning anything other than 0
myHeartRateSensor.initClock() fr = myHeartRateSensor.heartRate()
myHeartRateSensor.startBeatCounter()
while(1): # output milliseconds passed, beat count, and computed heart rate
# we grab these (millis and flowCount) just for display outputStr = "Millis: {0} Beats: {1} Heart Rate: {2}".format(
# purposes in this example millis, beats, fr)
millis = myHeartRateSensor.getMillis() print outputStr
beats = myHeartRateSensor.beatCounter() time.sleep(1)
# heartRate() requires that at least 5 seconds pass before if __name__ == '__main__':
# returning anything other than 0 main()
fr = myHeartRateSensor.heartRate()
# output milliseconds passed, beat count, and computed heart rate
outputStr = "Millis: {0} Beats: {1} Heart Rate: {2}".format(
millis, beats, fr)
print outputStr
time.sleep(1)

50
examples/python/eldriver.py Normal file → Executable file
View File

@ -24,34 +24,36 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_eldriver as upmeldriver import pyupm_eldriver as upmeldriver
# The was tested with the El Driver Module def main():
# Instantiate a El Driver on digital pin D2 # The was tested with the El Driver Module
myEldriver = upmeldriver.ElDriver(2) # Instantiate a El Driver on digital pin D2
myEldriver = upmeldriver.ElDriver(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myEldriver
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit myEldriver.off()
sys.exit(0)
# This function lets you run code on exit, including functions from myEldriver # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
myEldriver.off()
sys.exit(0)
# Register exit handlers lightState = True
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
while(1):
if (lightState):
myEldriver.on()
else:
myEldriver.off()
lightState = not lightState
lightState = True time.sleep(1)
while(1): if __name__ == '__main__':
if (lightState): main()
myEldriver.on()
else:
myEldriver.off()
lightState = not lightState
time.sleep(1)

56
examples/python/electromagnet.py Normal file → Executable file
View File

@ -24,37 +24,39 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_electromagnet as upmelectromagnet import pyupm_electromagnet as upmelectromagnet
# This was tested with the Electromagnetic Module def main():
# Instantiate a Electromagnet on digital pin D2 # This was tested with the Electromagnetic Module
myElectromagnet = upmelectromagnet.Electromagnet(2) # Instantiate a Electromagnet on digital pin D2
myElectromagnet = upmelectromagnet.Electromagnet(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myElectromagnet
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
myElectromagnet.off()
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myElectromagnet atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
myElectromagnet.off()
sys.exit(0)
# Register exit handlers magnetState = False
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# Turn magnet on and off every 5 seconds
while(1):
magnetState = not magnetState
if (magnetState):
myElectromagnet.on()
else:
myElectromagnet.off()
print "Turning magnet", ("on" if magnetState else "off")
magnetState = False time.sleep(5)
# Turn magnet on and off every 5 seconds if __name__ == '__main__':
while(1): main()
magnetState = not magnetState
if (magnetState):
myElectromagnet.on()
else:
myElectromagnet.off()
print "Turning magnet", ("on" if magnetState else "off")
time.sleep(5)

42
examples/python/emg.py Normal file → Executable file
View File

@ -24,29 +24,31 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_emg as upmEmg import pyupm_emg as upmEmg
# Tested with the EMG Muscle Signal Reader Sensor Module def main():
# Instantiate a EMG on analog pin A0 # Tested with the EMG Muscle Signal Reader Sensor Module
myEMG = upmEmg.EMG(0) # Instantiate a EMG on analog pin A0
myEMG = upmEmg.EMG(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit, including functions from myEMG
# This stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This lets you run code on exit, including functions from myEMG # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers print "Calibrating...."
atexit.register(exitHandler) myEMG.calibrate()
signal.signal(signal.SIGINT, SIGINTHandler)
while (1):
print myEMG.value()
time.sleep(.1)
print "Calibrating...." if __name__ == '__main__':
myEMG.calibrate() main()
while (1):
print myEMG.value()
time.sleep(.1)

60
examples/python/enc03r.py Normal file → Executable file
View File

@ -24,41 +24,43 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_enc03r as upmEnc03r import pyupm_enc03r as upmEnc03r
# Instantiate an ENC03R on analog pin A0 def main():
myAnalogGyro = upmEnc03r.ENC03R(0) # Instantiate an ENC03R on analog pin A0
myAnalogGyro = upmEnc03r.ENC03R(0)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit,
# This function stops python from printing a stacktrace when you hit control-C # including functions from myAnalogGyro
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This function lets you run code on exit, # Register exit handlers
# including functions from myAnalogGyro atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers CALIBRATION_SAMPLES = 1000
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
print ("Please place the sensor in a stable location,\n"
"and do not move it while calibration takes place.\n"
"This may take a couple of minutes.")
CALIBRATION_SAMPLES = 1000 myAnalogGyro.calibrate(CALIBRATION_SAMPLES)
print "Calibration complete. "
print "Reference value: ", myAnalogGyro.calibrationValue()
print ("Please place the sensor in a stable location,\n" while(1):
"and do not move it while calibration takes place.\n" gyroVal = myAnalogGyro.value();
"This may take a couple of minutes.") outputStr = ("Raw value: {0}, "
"angular velocity: {1}"
" deg/s".format(gyroVal, myAnalogGyro.angularVelocity(gyroVal)))
print outputStr
myAnalogGyro.calibrate(CALIBRATION_SAMPLES) time.sleep(.1)
print "Calibration complete. "
print "Reference value: ", myAnalogGyro.calibrationValue()
while(1): if __name__ == '__main__':
gyroVal = myAnalogGyro.value(); main()
outputStr = ("Raw value: {0}, "
"angular velocity: {1}"
" deg/s".format(gyroVal, myAnalogGyro.angularVelocity(gyroVal)))
print outputStr
time.sleep(.1)

42
examples/python/es08a.py Normal file → Executable file
View File

@ -1,4 +1,4 @@
# Author: John Van Drasek <john.r.van.drasek@intel.com> # Author: John Van Drasek <john.r.van.drasek@intel.com>
# Copyright (c) 2015 Intel Corporation. # Copyright (c) 2015 Intel Corporation.
# #
# Permission is hereby granted, free of charge, to any person obtaining # Permission is hereby granted, free of charge, to any person obtaining
@ -21,26 +21,30 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time import time
import pyupm_servo as servo import pyupm_servo as servo
# Create the servo object using D5 def main():
gServo = servo.ES08A(5) # Create the servo object using D5
gServo = servo.ES08A(5)
for i in range(0,10): for i in range(0,10):
# Set the servo arm to 0 degrees # Set the servo arm to 0 degrees
gServo.setAngle(0) gServo.setAngle(0)
print 'Set angle to 0' print 'Set angle to 0'
time.sleep(1) time.sleep(1)
# Set the servo arm to 90 degrees # Set the servo arm to 90 degrees
gServo.setAngle(90) gServo.setAngle(90)
print 'Set angle to 90' print 'Set angle to 90'
time.sleep(1) time.sleep(1)
# Set the servo arm to 180 degrees # Set the servo arm to 180 degrees
gServo.setAngle(180) gServo.setAngle(180)
print 'Set angle to 180' print 'Set angle to 180'
time.sleep(1) time.sleep(1)
# Delete the servo object # Delete the servo object
del gServo del gServo
if __name__ == '__main__':
main()

62
examples/python/gp2y0a.py Normal file → Executable file
View File

@ -24,39 +24,41 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_gp2y0a as upmGp2y0a import pyupm_gp2y0a as upmGp2y0a
# Note, for the Grove 80cm version of this sensor, due to the way it is wired, def main():
# you need to plug this into the A0 port, where it will use the available # Note, for the Grove 80cm version of this sensor, due to the way it is wired,
# A1 pin for data. # you need to plug this into the A0 port, where it will use the available
# Instantiate a GP2Y0A on analog pin A1 # A1 pin for data.
myIRProximity = upmGp2y0a.GP2Y0A(1) # Instantiate a GP2Y0A on analog pin A1
myIRProximity = upmGp2y0a.GP2Y0A(1)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myIRProximity
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myIRProximity atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers # analog voltage, usually 3.3 or 5.0
atexit.register(exitHandler) GP2Y0A_AREF = 5.0;
signal.signal(signal.SIGINT, SIGINTHandler) SAMPLES_PER_QUERY = 20;
# The higher the voltage (closer to AREF) the closer the object is.
# NOTE: The measured voltage will probably not exceed 3.3 volts.
# Every second, print the averaged voltage value
# (averaged over 20 samples).
while (1):
print "AREF: {0}, Voltage value (higher means closer): {1}".format(
GP2Y0A_AREF,
myIRProximity.value(GP2Y0A_AREF, SAMPLES_PER_QUERY))
time.sleep(1)
# analog voltage, usually 3.3 or 5.0 if __name__ == '__main__':
GP2Y0A_AREF = 5.0; main()
SAMPLES_PER_QUERY = 20;
# The higher the voltage (closer to AREF) the closer the object is.
# NOTE: The measured voltage will probably not exceed 3.3 volts.
# Every second, print the averaged voltage value
# (averaged over 20 samples).
while (1):
print "AREF: {0}, Voltage value (higher means closer): {1}".format(
GP2Y0A_AREF,
myIRProximity.value(GP2Y0A_AREF, SAMPLES_PER_QUERY))
time.sleep(1)

78
examples/python/gprs.py Normal file → Executable file
View File

@ -24,54 +24,53 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_gprs as sensorObj import pyupm_gprs as sensorObj
# Instantiate a GPRS Module on UART 0 def main():
sensor = sensorObj.GPRS(0) # Instantiate a GPRS Module on UART 0
sensor = sensorObj.GPRS(0)
## Exit handlers ## ## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C # This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Set the baud rate, 19200 baud is the default. # Set the baud rate, 19200 baud is the default.
if (sensor.setBaudRate(19200)): if (sensor.setBaudRate(19200)):
print "Failed to set baud rate" print "Failed to set baud rate"
sys.exit(0) sys.exit(0)
usageStr = ("Usage:\n"
"If an argument is supplied on the command line, that argument is\n"
"sent to the module and the response is printed out.\n\n"
"If no argument is used, then the manufacturer and the current\n"
"saved profiles are queried and the results printed out.\n\n")
print usageStr
usageStr = ("Usage:\n" # simple helper function to send a command and wait for a response
"If an argument is supplied on the command line, that argument is\n" def sendCommand(sensor, cmd):
"sent to the module and the response is printed out.\n\n"
"If no argument is used, then the manufacturer and the current\n"
"saved profiles are queried and the results printed out.\n\n")
print usageStr
# simple helper function to send a command and wait for a response
def sendCommand(sensor, cmd):
# commands need to be terminated with a carriage return # commands need to be terminated with a carriage return
cmd += "\r"; cmd += "\r";
sensor.writeDataStr(cmd) sensor.writeDataStr(cmd)
# wait up to 1 second # wait up to 1 second
if (sensor.dataAvailable(1000)): if (sensor.dataAvailable(1000)):
print "Returned: ", print "Returned: ",
print sensor.readDataStr(1024) print sensor.readDataStr(1024)
else: else:
print "Timed out waiting for response" print "Timed out waiting for response"
if (len(sys.argv) > 1):
if (len(sys.argv) > 1): print "Sending command line argument (" + sys.argv[1] + ")..."
print "Sending command line argument (" + sys.argv[1] + ")..." sendCommand(sensor, sys.argv[1])
sendCommand(sensor, sys.argv[1]) else:
else:
# query the module manufacturer # query the module manufacturer
print "Querying module manufacturer (AT+CGMI)..." print "Querying module manufacturer (AT+CGMI)..."
sendCommand(sensor, "AT+CGMI"); sendCommand(sensor, "AT+CGMI");
@ -84,3 +83,6 @@ else:
# A comprehensive list is available from the datasheet at: # A comprehensive list is available from the datasheet at:
# http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf # http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf
if __name__ == '__main__':
main()

20
examples/python/grovebutton.py Normal file → Executable file
View File

@ -23,13 +23,17 @@
import time import time
import pyupm_grove as grove import pyupm_grove as grove
# Create the button object using GPIO pin 0 def main():
button = grove.GroveButton(0) # Create the button object using GPIO pin 0
button = grove.GroveButton(0)
# Read the input and print, waiting one second between readings # Read the input and print, waiting one second between readings
while 1: while 1:
print button.name(), ' value is ', button.value() print button.name(), ' value is ', button.value()
time.sleep(1) time.sleep(1)
# Delete the button object # Delete the button object
del button del button
if __name__ == '__main__':
main()

36
examples/python/grovecircularled.py Normal file → Executable file
View File

@ -25,26 +25,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_my9221 as upmGroveCircularLED import pyupm_my9221 as upmGroveCircularLED
# Exit handlers def main():
def SIGINTHandler(signum, frame): # Exit handlers
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
def exitHandler(): def exitHandler():
circle.setLevel(0, True) circle.setLevel(0, True)
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# This function lets you run code on exit # This function lets you run code on exit
atexit.register(exitHandler) atexit.register(exitHandler)
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Instantiate a Grove Circular LED on gpio pins 9 and 8 # Instantiate a Grove Circular LED on gpio pins 9 and 8
circle = upmGroveCircularLED.GroveCircularLED(9, 8) circle = upmGroveCircularLED.GroveCircularLED(9, 8)
level = 0 level = 0
while(1): while(1):
circle.setSpinner(level) circle.setSpinner(level)
level = (level + 1) % 24 level = (level + 1) % 24
time.sleep(.1) time.sleep(.1)
if __name__ == '__main__':
main()

52
examples/python/grovecollision.py Normal file → Executable file
View File

@ -24,34 +24,36 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovecollision as upmGrovecollision import pyupm_grovecollision as upmGrovecollision
# The was tested with the Grove Collision Sensor def main():
# Instantiate a Grove Collision on digital pin D2 # The was tested with the Grove Collision Sensor
myGrovecollision = upmGrovecollision.GroveCollision(2) # Instantiate a Grove Collision on digital pin D2
myGrovecollision = upmGrovecollision.GroveCollision(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myGrovecollision
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myGrovecollision atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers collisionState = False
atexit.register(exitHandler) print "No collision"
signal.signal(signal.SIGINT, SIGINTHandler)
while(1):
if (myGrovecollision.isColliding() and not collisionState):
print "Collision!"
collisionState = True
elif (not myGrovecollision.isColliding() and collisionState):
print "No collision"
collisionState = False
collisionState = False if __name__ == '__main__':
print "No collision" main()
while(1):
if (myGrovecollision.isColliding() and not collisionState):
print "Collision!"
collisionState = True
elif (not myGrovecollision.isColliding() and collisionState):
print "No collision"
collisionState = False

69
examples/python/groveehr.py Normal file → Executable file
View File

@ -21,48 +21,49 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_groveehr as upmGroveehr import pyupm_groveehr as upmGroveehr
# Instantiate a Grove Ear-clip Heart Rate sensor on digital pin D2 def main():
myHeartRateSensor = upmGroveehr.GroveEHR(2) # Instantiate a Grove Ear-clip Heart Rate sensor on digital pin D2
myHeartRateSensor = upmGroveehr.GroveEHR(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myHeartRateSensor
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit myHeartRateSensor.stopBeatCounter()
print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myHeartRateSensor atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
myHeartRateSensor.stopBeatCounter()
print "Exiting"
sys.exit(0)
# Register exit handlers # set the beat counter to 0, init the clock and start counting beats
atexit.register(exitHandler) myHeartRateSensor.clearBeatCounter()
signal.signal(signal.SIGINT, SIGINTHandler) myHeartRateSensor.initClock()
myHeartRateSensor.startBeatCounter()
while(1):
# we grab these (millis and flowCount) just for display
# purposes in this example
millis = myHeartRateSensor.getMillis()
beats = myHeartRateSensor.beatCounter()
# set the beat counter to 0, init the clock and start counting beats # heartRate() requires that at least 5 seconds pass before
myHeartRateSensor.clearBeatCounter() # returning anything other than 0
myHeartRateSensor.initClock() fr = myHeartRateSensor.heartRate()
myHeartRateSensor.startBeatCounter()
while(1): # output milliseconds passed, beat count, and computed heart rate
# we grab these (millis and flowCount) just for display outputStr = "Millis: {0} Beats: {1} Heart Rate: {2}".format(
# purposes in this example millis, beats, fr)
millis = myHeartRateSensor.getMillis() print outputStr
beats = myHeartRateSensor.beatCounter() time.sleep(1)
# heartRate() requires that at least 5 seconds pass before if __name__ == '__main__':
# returning anything other than 0 main()
fr = myHeartRateSensor.heartRate()
# output milliseconds passed, beat count, and computed heart rate
outputStr = "Millis: {0} Beats: {1} Heart Rate: {2}".format(
millis, beats, fr)
print outputStr
time.sleep(1)

50
examples/python/groveeldriver.py Normal file → Executable file
View File

@ -24,34 +24,36 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_groveeldriver as upmGroveeldriver import pyupm_groveeldriver as upmGroveeldriver
# The was tested with the Grove El Driver Module def main():
# Instantiate a Grove El Driver on digital pin D2 # The was tested with the Grove El Driver Module
myEldriver = upmGroveeldriver.GroveElDriver(2) # Instantiate a Grove El Driver on digital pin D2
myEldriver = upmGroveeldriver.GroveElDriver(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myEldriver
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit myEldriver.off()
sys.exit(0)
# This function lets you run code on exit, including functions from myEldriver # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
myEldriver.off()
sys.exit(0)
# Register exit handlers lightState = True
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
while(1):
if (lightState):
myEldriver.on()
else:
myEldriver.off()
lightState = not lightState
lightState = True time.sleep(1)
while(1): if __name__ == '__main__':
if (lightState): main()
myEldriver.on()
else:
myEldriver.off()
lightState = not lightState
time.sleep(1)

56
examples/python/groveelectromagnet.py Normal file → Executable file
View File

@ -24,37 +24,39 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_groveelectromagnet as upmGroveelectromagnet import pyupm_groveelectromagnet as upmGroveelectromagnet
# This was tested with the Grove Electromagnetic Module def main():
# Instantiate a Grove Electromagnet on digital pin D2 # This was tested with the Grove Electromagnetic Module
myElectromagnet = upmGroveelectromagnet.GroveElectromagnet(2) # Instantiate a Grove Electromagnet on digital pin D2
myElectromagnet = upmGroveelectromagnet.GroveElectromagnet(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myElectromagnet
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
myElectromagnet.off()
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myElectromagnet atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
myElectromagnet.off()
sys.exit(0)
# Register exit handlers magnetState = False
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# Turn magnet on and off every 5 seconds
while(1):
magnetState = not magnetState
if (magnetState):
myElectromagnet.on()
else:
myElectromagnet.off()
print "Turning magnet", ("on" if magnetState else "off")
magnetState = False time.sleep(5)
# Turn magnet on and off every 5 seconds if __name__ == '__main__':
while(1): main()
magnetState = not magnetState
if (magnetState):
myElectromagnet.on()
else:
myElectromagnet.off()
print "Turning magnet", ("on" if magnetState else "off")
time.sleep(5)

42
examples/python/groveemg.py Normal file → Executable file
View File

@ -24,29 +24,31 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_groveemg as upmGroveemg import pyupm_groveemg as upmGroveemg
# Tested with the GroveEMG Muscle Signal Reader Sensor Module def main():
# Instantiate a GroveEMG on analog pin A0 # Tested with the GroveEMG Muscle Signal Reader Sensor Module
myEMG = upmGroveemg.GroveEMG(0) # Instantiate a GroveEMG on analog pin A0
myEMG = upmGroveemg.GroveEMG(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit, including functions from myEMG
# This stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This lets you run code on exit, including functions from myEMG # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers print "Calibrating...."
atexit.register(exitHandler) myEMG.calibrate()
signal.signal(signal.SIGINT, SIGINTHandler)
while (1):
print myEMG.value()
time.sleep(.1)
print "Calibrating...." if __name__ == '__main__':
myEMG.calibrate() main()
while (1):
print myEMG.value()
time.sleep(.1)

78
examples/python/grovegprs.py Normal file → Executable file
View File

@ -24,54 +24,53 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovegprs as sensorObj import pyupm_grovegprs as sensorObj
# Instantiate a GroveGPRS Module on UART 0 def main():
sensor = sensorObj.GroveGPRS(0) # Instantiate a GroveGPRS Module on UART 0
sensor = sensorObj.GroveGPRS(0)
## Exit handlers ## ## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C # This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Set the baud rate, 19200 baud is the default. # Set the baud rate, 19200 baud is the default.
if (sensor.setBaudRate(19200)): if (sensor.setBaudRate(19200)):
print "Failed to set baud rate" print "Failed to set baud rate"
sys.exit(0) sys.exit(0)
usageStr = ("Usage:\n"
"If an argument is supplied on the command line, that argument is\n"
"sent to the module and the response is printed out.\n\n"
"If no argument is used, then the manufacturer and the current\n"
"saved profiles are queried and the results printed out.\n\n")
print usageStr
usageStr = ("Usage:\n" # simple helper function to send a command and wait for a response
"If an argument is supplied on the command line, that argument is\n" def sendCommand(sensor, cmd):
"sent to the module and the response is printed out.\n\n"
"If no argument is used, then the manufacturer and the current\n"
"saved profiles are queried and the results printed out.\n\n")
print usageStr
# simple helper function to send a command and wait for a response
def sendCommand(sensor, cmd):
# commands need to be terminated with a carriage return # commands need to be terminated with a carriage return
cmd += "\r"; cmd += "\r";
sensor.writeDataStr(cmd) sensor.writeDataStr(cmd)
# wait up to 1 second # wait up to 1 second
if (sensor.dataAvailable(1000)): if (sensor.dataAvailable(1000)):
print "Returned: ", print "Returned: ",
print sensor.readDataStr(1024) print sensor.readDataStr(1024)
else: else:
print "Timed out waiting for response" print "Timed out waiting for response"
if (len(sys.argv) > 1):
if (len(sys.argv) > 1): print "Sending command line argument (" + sys.argv[1] + ")..."
print "Sending command line argument (" + sys.argv[1] + ")..." sendCommand(sensor, sys.argv[1])
sendCommand(sensor, sys.argv[1]) else:
else:
# query the module manufacturer # query the module manufacturer
print "Querying module manufacturer (AT+CGMI)..." print "Querying module manufacturer (AT+CGMI)..."
sendCommand(sensor, "AT+CGMI"); sendCommand(sensor, "AT+CGMI");
@ -84,3 +83,6 @@ else:
# A comprehensive list is available from the datasheet at: # A comprehensive list is available from the datasheet at:
# http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf # http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf
if __name__ == '__main__':
main()

42
examples/python/grovegsr.py Normal file → Executable file
View File

@ -24,30 +24,32 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovegsr as upmGrovegsr import pyupm_grovegsr as upmGrovegsr
# Tested with the GroveGSR Galvanic Skin Response Sensor module. def main():
# Tested with the GroveGSR Galvanic Skin Response Sensor module.
# Instantiate a GroveGSR on analog pin A0 # Instantiate a GroveGSR on analog pin A0
myGSR = upmGrovegsr.GroveGSR(0) myGSR = upmGrovegsr.GroveGSR(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit, including functions from myGSR
# This stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This lets you run code on exit, including functions from myGSR # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers print "Calibrating...."
atexit.register(exitHandler) myGSR.calibrate()
signal.signal(signal.SIGINT, SIGINTHandler)
while (1):
print myGSR.value()
time.sleep(.5)
print "Calibrating...." if __name__ == '__main__':
myGSR.calibrate() main()
while (1):
print myGSR.value()
time.sleep(.5)

30
examples/python/groveled.py Normal file → Executable file
View File

@ -23,19 +23,23 @@
import time import time
import pyupm_grove as grove import pyupm_grove as grove
# Create the Grove LED object using GPIO pin 2 def main():
led = grove.GroveLed(2) # Create the Grove LED object using GPIO pin 2
led = grove.GroveLed(2)
# Print the name # Print the name
print led.name() print led.name()
# Turn the LED on and off 10 times, pausing one second # Turn the LED on and off 10 times, pausing one second
# between transitions # between transitions
for i in range (0,10): for i in range (0,10):
led.on() led.on()
time.sleep(1) time.sleep(1)
led.off() led.off()
time.sleep(1) time.sleep(1)
# Delete the Grove LED object # Delete the Grove LED object
del led del led
if __name__ == '__main__':
main()

66
examples/python/groveledbar.py Normal file → Executable file
View File

@ -24,41 +24,43 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_my9221 as upmMy9221 import pyupm_my9221 as upmMy9221
# Instantiate a MY9221, we use D8 for the data, and D9 for the def main():
# data clock. This was tested with a Grove LED bar. # Instantiate a MY9221, we use D8 for the data, and D9 for the
myLEDBar = upmMy9221.GroveLEDBar(8, 9) # data clock. This was tested with a Grove LED bar.
myLEDBar = upmMy9221.GroveLEDBar(8, 9)
# Exit handlers
def SIGINTHandler(signum, frame):
raise SystemExit
# Exit handlers def exitHandler():
def SIGINTHandler(signum, frame): myLEDBar.setBarLevel(0, True)
raise SystemExit print "Exiting"
sys.exit(0)
def exitHandler(): # This function lets you run code on exit
myLEDBar.setBarLevel(0, True) atexit.register(exitHandler)
print "Exiting" # This function stops python from printing a stacktrace when you hit control-C
sys.exit(0) signal.signal(signal.SIGINT, SIGINTHandler)
# This function lets you run code on exit directionBool = True
atexit.register(exitHandler) level = 1
# This function stops python from printing a stacktrace when you hit control-C
signal.signal(signal.SIGINT, SIGINTHandler)
x = 0
while(1):
# If it's less than 10
# light up the LED now
# call show_LED again in 50 ms
if (level <= 10):
myLEDBar.setBarLevel(level, directionBool)
level += 1
# Switch LED lighting directions between lighting cycles
else:
directionBool = not directionBool
level = 1
time.sleep(1)
time.sleep(.05)
x += 1
directionBool = True if __name__ == '__main__':
level = 1 main()
x = 0
while(1):
# If it's less than 10
# light up the LED now
# call show_LED again in 50 ms
if (level <= 10):
myLEDBar.setBarLevel(level, directionBool)
level += 1
# Switch LED lighting directions between lighting cycles
else:
directionBool = not directionBool
level = 1
time.sleep(1)
time.sleep(.05)
x += 1

24
examples/python/grovelight.py Normal file → Executable file
View File

@ -23,15 +23,19 @@
import time import time
import pyupm_grove as grove import pyupm_grove as grove
# Create the light sensor object using AIO pin 0 def main():
light = grove.GroveLight(0) # Create the light sensor object using AIO pin 0
light = grove.GroveLight(0)
# Read the input and print both the raw value and a rough lux value, # Read the input and print both the raw value and a rough lux value,
# waiting one second between readings # waiting one second between readings
while 1: while 1:
print light.name() + " raw value is %d" % light.raw_value() + \ print light.name() + " raw value is %d" % light.raw_value() + \
", which is roughly %d" % light.value() + " lux"; ", which is roughly %d" % light.value() + " lux";
time.sleep(1) time.sleep(1)
# Delete the light sensor object # Delete the light sensor object
del light del light
if __name__ == '__main__':
main()

42
examples/python/grovelinefinder.py Normal file → Executable file
View File

@ -24,28 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovelinefinder as upmGrovelinefinder import pyupm_grovelinefinder as upmGrovelinefinder
# Instantiate a Grove line finder sensor on digital pin D2 def main():
myLineFinder = upmGrovelinefinder.GroveLineFinder(2) # Instantiate a Grove line finder sensor on digital pin D2
myLineFinder = upmGrovelinefinder.GroveLineFinder(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myLineFinder
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myLineFinder # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) if (myLineFinder.whiteDetected()):
signal.signal(signal.SIGINT, SIGINTHandler) print "White detected."
else:
print "Black detected."
time.sleep(1)
if __name__ == '__main__':
while(1): main()
if (myLineFinder.whiteDetected()):
print "White detected."
else:
print "Black detected."
time.sleep(1)

37
examples/python/grovemd-stepper.py Normal file → Executable file
View File

@ -24,29 +24,32 @@
import time import time
import pyupm_grovemd as upmGrovemd import pyupm_grovemd as upmGrovemd
I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS def main():
I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS
I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR
# Instantiate an I2C Grove Motor Driver on I2C bus 0 # Instantiate an I2C Grove Motor Driver on I2C bus 0
myMotorDriver = upmGrovemd.GroveMD(I2C_BUS, I2C_ADDR) myMotorDriver = upmGrovemd.GroveMD(I2C_BUS, I2C_ADDR)
# This example demonstrates using the GroveMD to drive a stepper motor # This example demonstrates using the GroveMD to drive a stepper motor
# configure it, for this example, we'll assume 200 steps per rev # configure it, for this example, we'll assume 200 steps per rev
myMotorDriver.configStepper(200) myMotorDriver.configStepper(200)
# set for half a rotation # set for half a rotation
myMotorDriver.setStepperSteps(100) myMotorDriver.setStepperSteps(100)
# let it go - clockwise rotation, 10 RPM speed # let it go - clockwise rotation, 10 RPM speed
myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CW, 10) myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CW, 10)
time.sleep(3) time.sleep(3)
# Now do it backwards... # Now do it backwards...
myMotorDriver.setStepperSteps(100) myMotorDriver.setStepperSteps(100)
myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CCW, 10) myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CCW, 10)
# now disable # now disable
myMotorDriver.disableStepper() myMotorDriver.disableStepper()
if __name__ == '__main__':
main()

35
examples/python/grovemd.py Normal file → Executable file
View File

@ -24,24 +24,27 @@
import time import time
import pyupm_grovemd as upmGrovemd import pyupm_grovemd as upmGrovemd
I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS def main():
I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS
I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR
# Instantiate an I2C Grove Motor Driver on I2C bus 0 # Instantiate an I2C Grove Motor Driver on I2C bus 0
myMotorDriver = upmGrovemd.GroveMD(I2C_BUS, I2C_ADDR) myMotorDriver = upmGrovemd.GroveMD(I2C_BUS, I2C_ADDR)
# set direction to CW and set speed to 50%
print "Spin M1 and M2 at half speed for 3 seconds"
myMotorDriver.setMotorDirections(upmGrovemd.GroveMD.DIR_CW, upmGrovemd.GroveMD.DIR_CW)
myMotorDriver.setMotorSpeeds(127, 127)
# set direction to CW and set speed to 50% time.sleep(3)
print "Spin M1 and M2 at half speed for 3 seconds" # counter clockwise
myMotorDriver.setMotorDirections(upmGrovemd.GroveMD.DIR_CW, upmGrovemd.GroveMD.DIR_CW) print "Reversing M1 and M2 for 3 seconds"
myMotorDriver.setMotorSpeeds(127, 127) myMotorDriver.setMotorDirections(upmGrovemd.GroveMD.DIR_CCW,
upmGrovemd.GroveMD.DIR_CCW)
time.sleep(3)
time.sleep(3) print "Stopping motors"
# counter clockwise myMotorDriver.setMotorSpeeds(0, 0)
print "Reversing M1 and M2 for 3 seconds"
myMotorDriver.setMotorDirections(upmGrovemd.GroveMD.DIR_CCW,
upmGrovemd.GroveMD.DIR_CCW)
time.sleep(3)
print "Stopping motors" if __name__ == '__main__':
myMotorDriver.setMotorSpeeds(0, 0) main()

60
examples/python/grovemoisture.py Normal file → Executable file
View File

@ -24,38 +24,40 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovemoisture as upmMoisture import pyupm_grovemoisture as upmMoisture
# Instantiate a Grove Moisture sensor on analog pin A0 def main():
myMoisture = upmMoisture.GroveMoisture(0) # Instantiate a Grove Moisture sensor on analog pin A0
myMoisture = upmMoisture.GroveMoisture(0)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myMoisture
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myMoisture # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers # Values (approximate):
atexit.register(exitHandler) # 0-300, sensor in air or dry soil
signal.signal(signal.SIGINT, SIGINTHandler) # 300-600, sensor in humid soil
# 600+, sensor in wet soil or submerged in water
# Read the value every second and print the corresponding moisture level
while(1):
moisture_val = myMoisture.value()
if (moisture_val >= 0 and moisture_val < 300):
result = "Dry"
elif (moisture_val >= 300 and moisture_val < 600):
result = "Moist"
else:
result = "Wet"
print "Moisture value: {0}, {1}".format(moisture_val, result)
time.sleep(1)
# Values (approximate): if __name__ == '__main__':
# 0-300, sensor in air or dry soil main()
# 300-600, sensor in humid soil
# 600+, sensor in wet soil or submerged in water
# Read the value every second and print the corresponding moisture level
while(1):
moisture_val = myMoisture.value()
if (moisture_val >= 0 and moisture_val < 300):
result = "Dry"
elif (moisture_val >= 300 and moisture_val < 600):
result = "Moist"
else:
result = "Wet"
print "Moisture value: {0}, {1}".format(moisture_val, result)
time.sleep(1)

40
examples/python/groveo2.py Normal file → Executable file
View File

@ -24,28 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_groveo2 as upmGroveo2 import pyupm_groveo2 as upmGroveo2
# This was tested with the O2 Oxygen Concentration Sensor Module def main():
# Instantiate a GroveO2 on analog pin A0 # This was tested with the O2 Oxygen Concentration Sensor Module
myGroveO2 = upmGroveo2.GroveO2(0) # Instantiate a GroveO2 on analog pin A0
myGroveO2 = upmGroveo2.GroveO2(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit, including functions from myGroveO2
# This stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This lets you run code on exit, including functions from myGroveO2 # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) print "The output voltage is: {0}mV".format(
signal.signal(signal.SIGINT, SIGINTHandler) myGroveO2.voltageValue())
time.sleep(.1)
while(1): if __name__ == '__main__':
print "The output voltage is: {0}mV".format( main()
myGroveO2.voltageValue())
time.sleep(.1)

38
examples/python/groverelay.py Normal file → Executable file
View File

@ -23,22 +23,26 @@
import time import time
import pyupm_grove as grove import pyupm_grove as grove
# Create the relay switch object using GPIO pin 0 def main():
relay = grove.GroveRelay(0) # Create the relay switch object using GPIO pin 0
relay = grove.GroveRelay(0)
# Close and then open the relay switch 3 times, # Close and then open the relay switch 3 times,
# waiting one second each time. The LED on the relay switch # waiting one second each time. The LED on the relay switch
# will light up when the switch is on (closed). # will light up when the switch is on (closed).
# The switch will also make a noise between transitions. # The switch will also make a noise between transitions.
for i in range (0,3): for i in range (0,3):
relay.on() relay.on()
if relay.isOn(): if relay.isOn():
print relay.name(), 'is on' print relay.name(), 'is on'
time.sleep(1) time.sleep(1)
relay.off() relay.off()
if relay.isOff(): if relay.isOff():
print relay.name(), 'is off' print relay.name(), 'is off'
time.sleep(1) time.sleep(1)
# Delete the relay switch object # Delete the relay switch object
del relay del relay
if __name__ == '__main__':
main()

33
examples/python/groverotary.py Normal file → Executable file
View File

@ -23,23 +23,26 @@
from time import sleep from time import sleep
import pyupm_grove as grove import pyupm_grove as grove
# New knob on AIO pin 0 def main():
knob = grove.GroveRotary(0) # New knob on AIO pin 0
knob = grove.GroveRotary(0)
# Loop indefinitely # Loop indefinitely
while True: while True:
# Read values
abs = knob.abs_value()
absdeg = knob.abs_deg()
absrad = knob.abs_rad()
# Read values rel = knob.rel_value()
abs = knob.abs_value() reldeg = knob.rel_deg()
absdeg = knob.abs_deg() relrad = knob.rel_rad()
absrad = knob.abs_rad()
rel = knob.rel_value() print "Abs values: %4d" % int(abs) , " raw %4d" % int(absdeg), "deg = %5.2f" % absrad , " rad ",
reldeg = knob.rel_deg() print "Rel values: %4d" % int(rel) , " raw %4d" % int(reldeg), "deg = %5.2f" % relrad , " rad"
relrad = knob.rel_rad()
print "Abs values: %4d" % int(abs) , " raw %4d" % int(absdeg), "deg = %5.2f" % absrad , " rad ", # Sleep for 2.5 s
print "Rel values: %4d" % int(rel) , " raw %4d" % int(reldeg), "deg = %5.2f" % relrad , " rad" sleep(2.5)
# Sleep for 2.5 s if __name__ == '__main__':
sleep(2.5) main()

40
examples/python/grovescam.py Normal file → Executable file
View File

@ -25,37 +25,41 @@
import sys import sys
import pyupm_grovescam as upmGrovescam import pyupm_grovescam as upmGrovescam
# Instantiate a Grove Serial Camera on UART 0 def main():
camera = upmGrovescam.GROVESCAM(0) # Instantiate a Grove Serial Camera on UART 0
camera = upmGrovescam.GROVESCAM(0)
# make sure port is initialized properly. 115200 baud is the default. # make sure port is initialized properly. 115200 baud is the default.
if (not camera.setupTty()): if (not camera.setupTty()):
print "Failed to setup tty port parameters" print "Failed to setup tty port parameters"
sys.exit(1) sys.exit(1)
if (camera.init()): if (camera.init()):
print "Initialized..." print "Initialized..."
else: else:
print "init() failed" print "init() failed"
if (camera.preCapture()): if (camera.preCapture()):
print "preCapture succeeded..." print "preCapture succeeded..."
else: else:
print "preCapture failed." print "preCapture failed."
if (camera.doCapture()): if (camera.doCapture()):
print "doCapture succeeded..." print "doCapture succeeded..."
else: else:
print "doCapture failed." print "doCapture failed."
print "Image size is", camera.getImageSize(), "bytes" print "Image size is", camera.getImageSize(), "bytes"
if (camera.getImageSize() > 0): if (camera.getImageSize() > 0):
print "Storing image.jpg..." print "Storing image.jpg..."
if (camera.storeImage("image.jpg")): if (camera.storeImage("image.jpg")):
print "storeImage succeeded..." print "storeImage succeeded..."
else: else:
print "storeImage failed." print "storeImage failed."
print "Exiting." print "Exiting."
sys.exit(0) sys.exit(0)
if __name__ == '__main__':
main()

23
examples/python/groveslide.py Normal file → Executable file
View File

@ -23,17 +23,20 @@
from time import sleep from time import sleep
import pyupm_grove as grove import pyupm_grove as grove
# New Grove Slider on AIO pin 0 def main():
slider = grove.GroveSlide(0) # New Grove Slider on AIO pin 0
slider = grove.GroveSlide(0)
# Loop indefinitely # Loop indefinitely
while True: while True:
# Read values
raw = slider.raw_value()
volts = slider.voltage_value()
# Read values print "Slider value: ", raw , " = %.2f" % volts , " V"
raw = slider.raw_value()
volts = slider.voltage_value()
print "Slider value: ", raw , " = %.2f" % volts , " V" # Sleep for 2.5 s
sleep(2.5)
# Sleep for 2.5 s if __name__ == '__main__':
sleep(2.5) main()

16
examples/python/grovespeaker.py Normal file → Executable file
View File

@ -24,11 +24,15 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovespeaker as upmGrovespeaker import pyupm_grovespeaker as upmGrovespeaker
# Instantiate a Grove Speaker on digital pin D2 def main():
mySpeaker = upmGrovespeaker.GroveSpeaker(2) # Instantiate a Grove Speaker on digital pin D2
mySpeaker = upmGrovespeaker.GroveSpeaker(2)
# Play all 7 of the lowest notes # Play all 7 of the lowest notes
mySpeaker.playAll() mySpeaker.playAll()
# Play a medium C-sharp # Play a medium C-sharp
mySpeaker.playSound('c', True, "med") mySpeaker.playSound('c', True, "med")
if __name__ == '__main__':
main()

30
examples/python/grovetemp.py Normal file → Executable file
View File

@ -24,18 +24,22 @@
import time import time
import pyupm_grove as grove import pyupm_grove as grove
# Create the temperature sensor object using AIO pin 0 def main():
temp = grove.GroveTemp(0) # Create the temperature sensor object using AIO pin 0
print temp.name() temp = grove.GroveTemp(0)
print temp.name()
# Read the temperature ten times, printing both the Celsius and # Read the temperature ten times, printing both the Celsius and
# equivalent Fahrenheit temperature, waiting one second between readings # equivalent Fahrenheit temperature, waiting one second between readings
for i in range(0, 10): for i in range(0, 10):
celsius = temp.value() celsius = temp.value()
fahrenheit = celsius * 9.0/5.0 + 32.0; fahrenheit = celsius * 9.0/5.0 + 32.0;
print "%d degrees Celsius, or %d degrees Fahrenheit" \ print "%d degrees Celsius, or %d degrees Fahrenheit" \
% (celsius, fahrenheit) % (celsius, fahrenheit)
time.sleep(1) time.sleep(1)
# Delete the temperature sensor object # Delete the temperature sensor object
del temp del temp
if __name__ == '__main__':
main()

46
examples/python/grovevdiv.py Normal file → Executable file
View File

@ -24,31 +24,33 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovevdiv as upmGrovevdiv import pyupm_grovevdiv as upmGrovevdiv
# Instantiate a Grove Voltage Divider sensor on analog pin A0 def main():
myVoltageDivider = upmGrovevdiv.GroveVDiv(0) # Instantiate a Grove Voltage Divider sensor on analog pin A0
myVoltageDivider = upmGrovevdiv.GroveVDiv(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myVoltageDivider
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This function lets you run code on exit, # Register exit handlers
# including functions from myVoltageDivider atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) val = myVoltageDivider.value(100)
signal.signal(signal.SIGINT, SIGINTHandler) gain3val = myVoltageDivider.computedValue(3, val)
gain10val = myVoltageDivider.computedValue(10, val)
print "ADC value: {0} Gain 3: {1}v Gain 10: {2}v".format(
val, gain3val, gain10val)
time.sleep(1)
while(1): if __name__ == '__main__':
val = myVoltageDivider.value(100) main()
gain3val = myVoltageDivider.computedValue(3, val)
gain10val = myVoltageDivider.computedValue(10, val)
print "ADC value: {0} Gain 3: {1}v Gain 10: {2}v".format(
val, gain3val, gain10val)
time.sleep(1)

42
examples/python/grovewater.py Normal file → Executable file
View File

@ -24,28 +24,30 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovewater as upmGrovewater import pyupm_grovewater as upmGrovewater
# Instantiate a Grove Water sensor on digital pin D2 def main():
myWaterSensor = upmGrovewater.GroveWater(2) # Instantiate a Grove Water sensor on digital pin D2
myWaterSensor = upmGrovewater.GroveWater(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myWaterSensor
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myWaterSensor # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) if (myWaterSensor.isWet()):
signal.signal(signal.SIGINT, SIGINTHandler) print "Sensor is wet"
else:
print "Sensor is dry"
time.sleep(1)
if __name__ == '__main__':
while(1): main()
if (myWaterSensor.isWet()):
print "Sensor is wet"
else:
print "Sensor is dry"
time.sleep(1)

62
examples/python/grovewfs.py Normal file → Executable file
View File

@ -24,41 +24,43 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_grovewfs as upmGrovewfs import pyupm_grovewfs as upmGrovewfs
# Instantiate a Grove Water Flow Sensor on digital pin D2 def main():
myWaterFlow = upmGrovewfs.GroveWFS(2) # Instantiate a Grove Water Flow Sensor on digital pin D2
myWaterFlow = upmGrovewfs.GroveWFS(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myWaterFlow
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit myWaterFlow.stopFlowCounter()
print "Exiting"
sys.exit(0)
# This function lets you run code on exit, # Register exit handlers
# including functions from myWaterFlow atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
myWaterFlow.stopFlowCounter()
print "Exiting"
sys.exit(0)
# Register exit handlers # set the flow counter to 0 and start counting
atexit.register(exitHandler) myWaterFlow.clearFlowCounter()
signal.signal(signal.SIGINT, SIGINTHandler) myWaterFlow.startFlowCounter()
while (1):
# we grab these (millis and flowCount) just for display
# purposes in this example
millis = myWaterFlow.getMillis()
flowCount = myWaterFlow.flowCounter()
# set the flow counter to 0 and start counting fr = myWaterFlow.flowRate()
myWaterFlow.clearFlowCounter()
myWaterFlow.startFlowCounter()
while (1): # output milliseconds passed, flow count, and computed flow rate
# we grab these (millis and flowCount) just for display outputStr = "Millis: {0} Flow Count: {1} Flow Rate: {2} LPM".format(
# purposes in this example millis, flowCount, fr)
millis = myWaterFlow.getMillis() print outputStr
flowCount = myWaterFlow.flowCounter() time.sleep(2)
fr = myWaterFlow.flowRate() if __name__ == '__main__':
main()
# output milliseconds passed, flow count, and computed flow rate
outputStr = "Millis: {0} Flow Count: {1} Flow Rate: {2} LPM".format(
millis, flowCount, fr)
print outputStr
time.sleep(2)

42
examples/python/gsr.py Normal file → Executable file
View File

@ -24,30 +24,32 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_gsr as upmGsr import pyupm_gsr as upmGsr
# Tested with the GSR Galvanic Skin Response Sensor module. def main():
# Tested with the GSR Galvanic Skin Response Sensor module.
# Instantiate a GSR on analog pin A0 # Instantiate a GSR on analog pin A0
myGSR = upmGsr.GSR(0) myGSR = upmGsr.GSR(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit, including functions from myGSR
# This stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This lets you run code on exit, including functions from myGSR # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers print "Calibrating...."
atexit.register(exitHandler) myGSR.calibrate()
signal.signal(signal.SIGINT, SIGINTHandler)
while (1):
print myGSR.value()
time.sleep(.5)
print "Calibrating...." if __name__ == '__main__':
myGSR.calibrate() main()
while (1):
print myGSR.value()
time.sleep(.5)

50
examples/python/guvas12d.py Normal file → Executable file
View File

@ -24,33 +24,35 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_guvas12d as upmUV import pyupm_guvas12d as upmUV
# Instantiate a UV sensor on analog pin A0 def main():
myUVSensor = upmUV.GUVAS12D(0); # Instantiate a UV sensor on analog pin A0
myUVSensor = upmUV.GUVAS12D(0);
# analog voltage, usually 3.3 or 5.0 # analog voltage, usually 3.3 or 5.0
GUVAS12D_AREF = 5.0; GUVAS12D_AREF = 5.0;
SAMPLES_PER_QUERY = 1024; SAMPLES_PER_QUERY = 1024;
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myUVSensor
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myUVSensor # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) s = ("AREF: {0}, "
signal.signal(signal.SIGINT, SIGINTHandler) "Voltage value (higher means more UV): "
"{1}".format(GUVAS12D_AREF,
myUVSensor.value(GUVAS12D_AREF, SAMPLES_PER_QUERY)))
print s
time.sleep(1)
if __name__ == '__main__':
while(1): main()
s = ("AREF: {0}, "
"Voltage value (higher means more UV): "
"{1}".format(GUVAS12D_AREF,
myUVSensor.value(GUVAS12D_AREF, SAMPLES_PER_QUERY)))
print s
time.sleep(1)

84
examples/python/h3lis331dl.py Normal file → Executable file
View File

@ -24,53 +24,55 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_h3lis331dl as upmH3LIS331DL import pyupm_h3lis331dl as upmH3LIS331DL
# Instantiate an H3LIS331DL on I2C bus 0 def main():
myDigitalAccelerometer = upmH3LIS331DL.H3LIS331DL( # Instantiate an H3LIS331DL on I2C bus 0
upmH3LIS331DL.H3LIS331DL_I2C_BUS, myDigitalAccelerometer = upmH3LIS331DL.H3LIS331DL(
upmH3LIS331DL.H3LIS331DL_DEFAULT_I2C_ADDR); upmH3LIS331DL.H3LIS331DL_I2C_BUS,
upmH3LIS331DL.H3LIS331DL_DEFAULT_I2C_ADDR);
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myDigitalAccelerometer
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myDigitalAccelerometer # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers # Initialize the device with default values
atexit.register(exitHandler) myDigitalAccelerometer.init()
signal.signal(signal.SIGINT, SIGINTHandler)
x = upmH3LIS331DL.new_intp()
y = upmH3LIS331DL.new_intp()
z = upmH3LIS331DL.new_intp()
# Initialize the device with default values ax = upmH3LIS331DL.new_floatp()
myDigitalAccelerometer.init() ay = upmH3LIS331DL.new_floatp()
az = upmH3LIS331DL.new_floatp()
x = upmH3LIS331DL.new_intp() while (1):
y = upmH3LIS331DL.new_intp() myDigitalAccelerometer.update()
z = upmH3LIS331DL.new_intp() myDigitalAccelerometer.getRawXYZ(x, y, z)
outputStr = ("Raw: X = {0}"
" Y = {1}"
" Z = {2}").format(upmH3LIS331DL.intp_value(x),
upmH3LIS331DL.intp_value(y),
upmH3LIS331DL.intp_value(z))
print outputStr
ax = upmH3LIS331DL.new_floatp() myDigitalAccelerometer.getAcceleration(ax, ay, az)
ay = upmH3LIS331DL.new_floatp() outputStr = ("Acceleration: AX = {0}"
az = upmH3LIS331DL.new_floatp() " AY = {1}"
" AZ = {2}").format(upmH3LIS331DL.floatp_value(ax),
upmH3LIS331DL.floatp_value(ay),
upmH3LIS331DL.floatp_value(az))
print outputStr
time.sleep(.5)
while (1): if __name__ == '__main__':
myDigitalAccelerometer.update() main()
myDigitalAccelerometer.getRawXYZ(x, y, z)
outputStr = ("Raw: X = {0}"
" Y = {1}"
" Z = {2}").format(upmH3LIS331DL.intp_value(x),
upmH3LIS331DL.intp_value(y),
upmH3LIS331DL.intp_value(z))
print outputStr
myDigitalAccelerometer.getAcceleration(ax, ay, az)
outputStr = ("Acceleration: AX = {0}"
" AY = {1}"
" AZ = {2}").format(upmH3LIS331DL.floatp_value(ax),
upmH3LIS331DL.floatp_value(ay),
upmH3LIS331DL.floatp_value(az))
print outputStr
time.sleep(.5)

110
examples/python/h803x.py Normal file → Executable file
View File

@ -24,40 +24,41 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_h803x as sensorObj import pyupm_h803x as sensorObj
## Exit handlers ## def main():
# This function stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This function stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting..." print "Exiting..."
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
defaultDev = "/dev/ttyUSB0" defaultDev = "/dev/ttyUSB0"
# if an argument was specified, use it as the device instead # if an argument was specified, use it as the device instead
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
print "Initializing..." print "Initializing..."
# Instantiate an H803X instance, using MODBUS slave address 1, and # Instantiate an H803X instance, using MODBUS slave address 1, and
# default comm parameters (9600, 8, N, 2) # default comm parameters (9600, 8, N, 2)
sensor = sensorObj.H803X(defaultDev, 1) sensor = sensorObj.H803X(defaultDev, 1)
# output the serial number and firmware revision # output the serial number and firmware revision
print "Slave ID:", sensor.getSlaveID() print "Slave ID:", sensor.getSlaveID()
print print
# update and print available values every second # update and print available values every second
while (1): while (1):
# update our values from the sensor # update our values from the sensor
sensor.update() sensor.update()
@ -66,41 +67,44 @@ while (1):
print "Real Power (kW):", sensor.getRealPower() print "Real Power (kW):", sensor.getRealPower()
if (sensor.isH8036()): if (sensor.isH8036()):
# The H8036 has much more data available... # The H8036 has much more data available...
print "Reactive Power (kVAR):", sensor.getReactivePower() print "Reactive Power (kVAR):", sensor.getReactivePower()
print "Apparent Power (kVA):", sensor.getApparentPower() print "Apparent Power (kVA):", sensor.getApparentPower()
print "Power Factor:", sensor.getPowerFactor() print "Power Factor:", sensor.getPowerFactor()
print "Volts Line to Line:", sensor.getVoltsLineToLine() print "Volts Line to Line:", sensor.getVoltsLineToLine()
print "Volts Line to Neutral:", sensor.getVoltsLineToNeutral() print "Volts Line to Neutral:", sensor.getVoltsLineToNeutral()
print "Current:", sensor.getCurrent() print "Current:", sensor.getCurrent()
print "Real Power Phase A (kW):", sensor.getRealPowerPhaseA() print "Real Power Phase A (kW):", sensor.getRealPowerPhaseA()
print "Real Power Phase B (kW):", sensor.getRealPowerPhaseB() print "Real Power Phase B (kW):", sensor.getRealPowerPhaseB()
print "Real Power Phase C (kW):", sensor.getRealPowerPhaseC() print "Real Power Phase C (kW):", sensor.getRealPowerPhaseC()
print "Power Factor Phase A:", sensor.getPowerFactorPhaseA() print "Power Factor Phase A:", sensor.getPowerFactorPhaseA()
print "Power Factor Phase B:", sensor.getPowerFactorPhaseB() print "Power Factor Phase B:", sensor.getPowerFactorPhaseB()
print "Power Factor Phase C:", sensor.getPowerFactorPhaseC() print "Power Factor Phase C:", sensor.getPowerFactorPhaseC()
print "Volts Phase A to B:", sensor.getVoltsPhaseAToB() print "Volts Phase A to B:", sensor.getVoltsPhaseAToB()
print "Volts Phase B to C:", sensor.getVoltsPhaseBToC() print "Volts Phase B to C:", sensor.getVoltsPhaseBToC()
print "Volts Phase A to C:", sensor.getVoltsPhaseAToC() print "Volts Phase A to C:", sensor.getVoltsPhaseAToC()
print "Volts Phase A to Neutral: ", print "Volts Phase A to Neutral: ",
print sensor.getVoltsPhaseAToNeutral() print sensor.getVoltsPhaseAToNeutral()
print "Volts Phase B to Neutral: ", print "Volts Phase B to Neutral: ",
print sensor.getVoltsPhaseBToNeutral() print sensor.getVoltsPhaseBToNeutral()
print "Volts Phase C to Neutral: ", print "Volts Phase C to Neutral: ",
print sensor.getVoltsPhaseCToNeutral() print sensor.getVoltsPhaseCToNeutral()
print "Current Phase A:", sensor.getCurrentPhaseA() print "Current Phase A:", sensor.getCurrentPhaseA()
print "Current Phase B:", sensor.getCurrentPhaseB() print "Current Phase B:", sensor.getCurrentPhaseB()
print "Current Phase C:", sensor.getCurrentPhaseC() print "Current Phase C:", sensor.getCurrentPhaseC()
print "Avg Real Power (kW):", sensor.getAvgRealPower() print "Avg Real Power (kW):", sensor.getAvgRealPower()
print "Min Real Power (kW):", sensor.getMinRealPower() print "Min Real Power (kW):", sensor.getMinRealPower()
print "Max Real Power (kW):", sensor.getMaxRealPower() print "Max Real Power (kW):", sensor.getMaxRealPower()
print print
time.sleep(2) time.sleep(2)
if __name__ == '__main__':
main()

40
examples/python/hdxxvxta.py Normal file → Executable file
View File

@ -24,28 +24,29 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_hdxxvxta as sensorObj import pyupm_hdxxvxta as sensorObj
## Exit handlers ## def main():
# This function stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This function stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..." print "Initializing..."
# Instantiate an HDXXVXTA instance, using A1 for humidity and A0 # Instantiate an HDXXVXTA instance, using A1 for humidity and A0
# for temperature # for temperature
sensor = sensorObj.HDXXVXTA(1, 0) sensor = sensorObj.HDXXVXTA(1, 0)
# update and print available values every second # update and print available values every second
while (1): while (1):
# update our values from the sensor # update our values from the sensor
sensor.update() sensor.update()
@ -56,4 +57,7 @@ while (1):
print "Humidity:", sensor.getHumidity(), "%" print "Humidity:", sensor.getHumidity(), "%"
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

36
examples/python/hka5.py Normal file → Executable file
View File

@ -24,26 +24,27 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_hka5 as sensorObj import pyupm_hka5 as sensorObj
# Instantiate a HKA5 sensor on uart 0. We don't use the set or def main():
# reset pins, so we pass -1 for them. # Instantiate a HKA5 sensor on uart 0. We don't use the set or
sensor = sensorObj.HKA5(0, -1, -1) # reset pins, so we pass -1 for them.
sensor = sensorObj.HKA5(0, -1, -1)
## Exit handlers ## ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C # This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# update once every 2 seconds and output data # update once every 2 seconds and output data
while (True): while (True):
sensor.update() sensor.update()
print "PM 1 :", print "PM 1 :",
@ -60,3 +61,6 @@ while (True):
print print
time.sleep(2) time.sleep(2)
if __name__ == '__main__':
main()

143
examples/python/hm11.py Normal file → Executable file
View File

@ -24,87 +24,86 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_hm11 as upmHm11 import pyupm_hm11 as upmHm11
# Instantiate a HM11 BLE Module on UART 0 def main():
my_ble_obj = upmHm11.HM11(0) # Instantiate a HM11 BLE Module on UART 0
my_ble_obj = upmHm11.HM11(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from my_ble_obj
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This function lets you run code on exit, # Register exit handlers
# including functions from my_ble_obj atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers bufferLength = 256
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# make sure port is initialized properly. 9600 baud is the default.
if (not my_ble_obj.setupTty(upmHm11.cvar.int_B9600)):
print "Failed to setup tty port parameters"
sys.exit(0)
bufferLength = 256 usageStr = ("Usage:\n"
"Pass a commandline argument (any argument) to this program\n"
"to query the radio configuration and output it. NOTE: the\n"
"radio must be in CONFIG mode for this to work.\n\n"
"Running this program without arguments will simply transmit\n"
"'Hello World!' every second, and output any data received from\n"
"another radio.\n\n")
print usageStr
# make sure port is initialized properly. 9600 baud is the default. # simple helper function to send a command and wait for a response
if (not my_ble_obj.setupTty(upmHm11.cvar.int_B9600)): def sendCommand(bleObj, cmd):
print "Failed to setup tty port parameters" bleBuffer = upmHm11.charArray(bufferLength)
sys.exit(0) bleObj.writeData(cmd, len(cmd))
# wait up to 1 second
if (bleObj.dataAvailable(1000)):
bleObj.readData(bleBuffer, bufferLength)
bleData = ""
# read only the number of characters
# specified by myGPSSensor.readData
for x in range(0, bufferLength):
if (bleBuffer.__getitem__(x) == '\0'):
break
else:
bleData += bleBuffer.__getitem__(x)
print bleData
else:
print "Timed out waiting for response"
usageStr = ("Usage:\n" if (len(sys.argv) > 1):
"Pass a commandline argument (any argument) to this program\n" print "Sending command line argument (" + sys.argv[1] + ")..."
"to query the radio configuration and output it. NOTE: the\n" sendCommand(my_ble_obj, sys.argv[1])
"radio must be in CONFIG mode for this to work.\n\n" else:
"Running this program without arguments will simply transmit\n" # query the module address
"'Hello World!' every second, and output any data received from\n" addr = "AT+ADDR?";
"another radio.\n\n") print "Querying module address (" + addr + ")..."
print usageStr
# simple helper function to send a command and wait for a response sendCommand(my_ble_obj, addr)
def sendCommand(bleObj, cmd): time.sleep(1)
bleBuffer = upmHm11.charArray(bufferLength) # query the module address
bleObj.writeData(cmd, len(cmd)) pin = "AT+PASS?";
print "Querying module PIN (" + pin + ")..."
sendCommand(my_ble_obj, pin)
# wait up to 1 second # Other potentially useful commands are:
if (bleObj.dataAvailable(1000)): #
bleObj.readData(bleBuffer, bufferLength) # AT+VERS? - query module version
bleData = "" # AT+ROLE0 - set as slave
# read only the number of characters # AT+ROLE1 - set as master
# specified by myGPSSensor.readData # AT+CLEAR - clear all previous settings
for x in range(0, bufferLength): # AT+RESET - restart the device
if (bleBuffer.__getitem__(x) == '\0'): #
break # A comprehensive list is available from the datasheet at:
else: # http://www.seeedstudio.com/wiki/images/c/cd/Bluetooth4_en.pdf
bleData += bleBuffer.__getitem__(x)
print bleData
else:
print "Timed out waiting for response"
if (len(sys.argv) > 1):
print "Sending command line argument (" + sys.argv[1] + ")..."
sendCommand(my_ble_obj, sys.argv[1])
else:
# query the module address
addr = "AT+ADDR?";
print "Querying module address (" + addr + ")..."
sendCommand(my_ble_obj, addr)
time.sleep(1)
# query the module address
pin = "AT+PASS?";
print "Querying module PIN (" + pin + ")..."
sendCommand(my_ble_obj, pin)
# Other potentially useful commands are:
#
# AT+VERS? - query module version
# AT+ROLE0 - set as slave
# AT+ROLE1 - set as master
# AT+CLEAR - clear all previous settings
# AT+RESET - restart the device
#
# A comprehensive list is available from the datasheet at:
# http://www.seeedstudio.com/wiki/images/c/cd/Bluetooth4_en.pdf
if __name__ == '__main__':
main()

33
examples/python/hmc5883l.py Normal file → Executable file
View File

@ -23,22 +23,25 @@
from time import sleep from time import sleep
import pyupm_hmc5883l as hmc5883l import pyupm_hmc5883l as hmc5883l
# Create an I2C compass object and set declination def main():
hmc = hmc5883l.Hmc5883l(0) # Create an I2C compass object and set declination
hmc.set_declination(0.2749) hmc = hmc5883l.Hmc5883l(0)
hmc.set_declination(0.2749)
# Loop indefinitely # Loop indefinitely
while True: while True:
hmc.update() # Update the data
pos = hmc.coordinates() # Read raw coordinates
hdg = hmc.heading() # Read heading
dir = hmc.direction() # Read direction
hmc.update() # Update the data # Print values
pos = hmc.coordinates() # Read raw coordinates print "Coor: %5d %5d %5d" % (pos[0], pos[1], pos[2])
hdg = hmc.heading() # Read heading print "Heading: %5.2f" % (hdg)
dir = hmc.direction() # Read direction print "Direction: %3.2f\n" % (dir)
# Print values # Sleep for 1 s
print "Coor: %5d %5d %5d" % (pos[0], pos[1], pos[2]) sleep(1)
print "Heading: %5.2f" % (hdg)
print "Direction: %3.2f\n" % (dir)
# Sleep for 1 s if __name__ == '__main__':
sleep(1) main()

198
examples/python/hmtrp.py Normal file → Executable file
View File

@ -24,120 +24,120 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_hmtrp as upmHmtrp import pyupm_hmtrp as upmHmtrp
# Instantiate a HMTRP radio device on uart 0 def main():
my_HMTRP_Radio = upmHmtrp.HMTRP(0) # Instantiate a HMTRP radio device on uart 0
my_HMTRP_Radio = upmHmtrp.HMTRP(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from my_HMTRP_Radio
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This function lets you run code on exit, # Register exit handlers
# including functions from my_HMTRP_Radio atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers myCounter = 0
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# normal read/write mode
bufferLength = 256
radioBuffer = upmHmtrp.charArray(bufferLength)
myCounter = 0 # make sure port is initialized properly. 9600 baud is the default.
if (not my_HMTRP_Radio.setupTty(upmHmtrp.cvar.int_B9600)):
print "Failed to setup tty port parameters"
sys.exit(0)
# normal read/write mode usageStr = ("Usage:\n"
bufferLength = 256 "Pass a commandline argument (any argument) to this program\n"
radioBuffer = upmHmtrp.charArray(bufferLength) "to query the radio configuration and output it. NOTE: the\n"
"radio must be in CONFIG mode for this to work.\n\n"
"Running this program without arguments will simply transmit\n"
"'Hello World!' every second, and output any data received from\n"
"another radio.\n\n")
print usageStr
# make sure port is initialized properly. 9600 baud is the default. '''
if (not my_HMTRP_Radio.setupTty(upmHmtrp.cvar.int_B9600)): By default, this radio simply transmits data sent via writeData()
print "Failed to setup tty port parameters" and reads any available data via readData().
sys.exit(0)
It can be placed into a configuration mode by grounding the
CONFIG pin on the module. When this is done, the various
configuration query and config methods can be used. In this
example, by default, we just read any data available fom the
device, and periodically transmit "Hello World".
usageStr = ("Usage:\n" If any argument was specified on the command line, do a simple
"Pass a commandline argument (any argument) to this program\n" configuration query and output the results. The radio must be in
"to query the radio configuration and output it. NOTE: the\n" CONFIG mode for this to work.
"radio must be in CONFIG mode for this to work.\n\n"
"Running this program without arguments will simply transmit\n"
"'Hello World!' every second, and output any data received from\n"
"another radio.\n\n")
print usageStr
''' Note that the first command-line argument should be "hmtry.py"
By default, this radio simply transmits data sent via writeData() The data we want would be the second... if it exists
and reads any available data via readData(). '''
if (len(sys.argv) > 1):
# config mode
freq = upmHmtrp.uint32Array(0)
dataRate = upmHmtrp.uint32Array(0)
rxBandwidth = upmHmtrp.uint16Array(0)
modulation = upmHmtrp.uint8Array(0)
txPower = upmHmtrp.uint8Array(0)
uartBaud = upmHmtrp.uint32Array(0)
It can be placed into a configuration mode by grounding the if (my_HMTRP_Radio.getConfig(freq, dataRate, rxBandwidth,
CONFIG pin on the module. When this is done, the various modulation, txPower, uartBaud)):
configuration query and config methods can be used. In this print "Radio configuration:"
example, by default, we just read any data available fom the outputStr = ("freq: {0} dataRate: {1} "
device, and periodically transmit "Hello World". "rxBandwidth: {2}Khz").format(freq.__getitem__(0),
dataRate.__getitem__(0),
rxBandwidth.__getitem__(0))
print outputStr
If any argument was specified on the command line, do a simple outputStr = "modulation: %d Khz txPower: %d uartBaud: %d" % (
configuration query and output the results. The radio must be in modulation.__getitem__(0), txPower.__getitem__(0),
CONFIG mode for this to work. uartBaud.__getitem__(0))
print outputStr
else:
errString = ("getConfig() failed. Make sure the radio "
"is in CONFIG mode.")
print errString
else:
print "Running in normal read/write mode."
while (1):
# we don't want the read to block in this example, so always
# check to see if data is available first.
if (my_HMTRP_Radio.dataAvailable()):
rv = my_HMTRP_Radio.readData(radioBuffer, bufferLength)
if (rv > 0):
resultStr = "";
for x in range(rv):
resultStr += radioBuffer.__getitem__(x)
print "Received:", resultStr
Note that the first command-line argument should be "hmtry.py" if (rv < 0): # some sort of read error occurred
The data we want would be the second... if it exists print "Port read error."
''' sys.exit(0)
if (len(sys.argv) > 1): myCounter += 1
# config mode # every second, transmit "Hello World"
freq = upmHmtrp.uint32Array(0) if (myCounter > 10):
dataRate = upmHmtrp.uint32Array(0) msg = "Hello World!"
rxBandwidth = upmHmtrp.uint16Array(0)
modulation = upmHmtrp.uint8Array(0)
txPower = upmHmtrp.uint8Array(0)
uartBaud = upmHmtrp.uint32Array(0)
if (my_HMTRP_Radio.getConfig(freq, dataRate, rxBandwidth, print "Transmitting %s..." % msg
modulation, txPower, uartBaud)):
print "Radio configuration:"
outputStr = ("freq: {0} dataRate: {1} "
"rxBandwidth: {2}Khz").format(freq.__getitem__(0),
dataRate.__getitem__(0),
rxBandwidth.__getitem__(0))
print outputStr
outputStr = "modulation: %d Khz txPower: %d uartBaud: %d" % ( # Adding 1 for NULL terminator.
modulation.__getitem__(0), txPower.__getitem__(0), # Note that SWIG automatically adds a NULL terminator,
uartBaud.__getitem__(0)) # so no need to NULL-terminate ourselves.
print outputStr # Just increment the message length to include
else: # the NULL that's already there
errString = ("getConfig() failed. Make sure the radio " my_HMTRP_Radio.writeData(msg, (len(msg) + 1))
"is in CONFIG mode.") myCounter = 0
print errString time.sleep(.1)
else:
print "Running in normal read/write mode."
while (1):
# we don't want the read to block in this example, so always
# check to see if data is available first.
if (my_HMTRP_Radio.dataAvailable()):
rv = my_HMTRP_Radio.readData(radioBuffer, bufferLength)
if (rv > 0): if __name__ == '__main__':
resultStr = ""; main()
for x in range(rv):
resultStr += radioBuffer.__getitem__(x)
print "Received:", resultStr
if (rv < 0): # some sort of read error occurred
print "Port read error."
sys.exit(0)
myCounter += 1
# every second, transmit "Hello World"
if (myCounter > 10):
msg = "Hello World!"
print "Transmitting %s..." % msg
# Adding 1 for NULL terminator.
# Note that SWIG automatically adds a NULL terminator,
# so no need to NULL-terminate ourselves.
# Just increment the message length to include
# the NULL that's already there
my_HMTRP_Radio.writeData(msg, (len(msg) + 1))
myCounter = 0
time.sleep(.1)

47
examples/python/hp20x.py Normal file → Executable file
View File

@ -24,31 +24,34 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_hp20x as barometerObj import pyupm_hp20x as barometerObj
## Exit handlers ## def main():
# This stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit, # This function lets you run code on exit,
# including functions from ringCoder # including functions from ringCoder
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Instantiate an HP20X on default I2C bus and address # Instantiate an HP20X on default I2C bus and address
bar = barometerObj.HP20X() bar = barometerObj.HP20X()
# Initialize the device with default values # Initialize the device with default values
bar.init() bar.init()
while(1): while(1):
print "Temperature:", bar.getTemperature(), "Celsius" print "Temperature:", bar.getTemperature(), "Celsius"
print "Pressure: ", bar.getPressure(), "Millibars" print "Pressure: ", bar.getPressure(), "Millibars"
print "Altitude: ", bar.getAltitude(), "Meters" print "Altitude: ", bar.getAltitude(), "Meters"
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

49
examples/python/ht9170.py Normal file → Executable file
View File

@ -24,31 +24,34 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ht9170 as upmHt9170 import pyupm_ht9170 as upmHt9170
# Instantiate a DTMF decoder def main():
myDTMF = upmHt9170.HT9170(12, 11, 10, 9, 8) # Instantiate a DTMF decoder
myDTMF = upmHt9170.HT9170(12, 11, 10, 9, 8)
## Exit handlers ## ## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C # This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame): def SIGINTHandler(signum, frame):
raise SystemExit raise SystemExit
# This lets you run code on exit, including functions from myDTMF # This lets you run code on exit, including functions from myDTMF
def exitHandler(): def exitHandler():
print "Exiting" print "Exiting"
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
# Now we just spin in a loop, sleeping every 100ms, checking to see
# if a digit is available. If so, we decode and print the digit,
# and continue looping.
while (1):
if (dtmf_obj.digitReady()):
print "Got DTMF code:", dtmf_obj.decodeDigit()
# now spin until digitReady() goes false again
while (dtmf.digitReady()):
pass
time.sleep(.1)
# Now we just spin in a loop, sleeping every 100ms, checking to see if __name__ == '__main__':
# if a digit is available. If so, we decode and print the digit, main()
# and continue looping.
while (1):
if (dtmf_obj.digitReady()):
print "Got DTMF code:", dtmf_obj.decodeDigit()
# now spin until digitReady() goes false again
while (dtmf.digitReady()):
pass
time.sleep(.1)

60
examples/python/hwxpxx.py Normal file → Executable file
View File

@ -24,44 +24,45 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_hwxpxx as sensorObj import pyupm_hwxpxx as sensorObj
## Exit handlers ## def main():
# This function stops python from printing a stacktrace when you hit control-C ## Exit handlers ##
def SIGINTHandler(signum, frame): # This function stops python from printing a stacktrace when you hit control-C
raise SystemExit def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit # This function lets you run code on exit
def exitHandler(): def exitHandler():
print "Exiting..." print "Exiting..."
sys.exit(0) sys.exit(0)
# Register exit handlers # Register exit handlers
atexit.register(exitHandler) atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler) signal.signal(signal.SIGINT, SIGINTHandler)
defaultDev = "/dev/ttyUSB0" defaultDev = "/dev/ttyUSB0"
# if an argument was specified, use it as the device instead # if an argument was specified, use it as the device instead
if (len(sys.argv) > 1): if (len(sys.argv) > 1):
defaultDev = sys.argv[1] defaultDev = sys.argv[1]
print "Using device", defaultDev print "Using device", defaultDev
print "Initializing..." print "Initializing..."
# Instantiate an HWXPXX instance, using MODBUS slave address 3, and # Instantiate an HWXPXX instance, using MODBUS slave address 3, and
# default comm parameters (19200, 8, N, 2) # default comm parameters (19200, 8, N, 2)
sensor = sensorObj.HWXPXX(defaultDev, 3) sensor = sensorObj.HWXPXX(defaultDev, 3)
# output the serial number and firmware revision # output the serial number and firmware revision
print "Slave ID:", sensor.getSlaveID() print "Slave ID:", sensor.getSlaveID()
# stored temperature and humidity offsets # stored temperature and humidity offsets
print "Temperature Offset:", sensor.getTemperatureOffset() print "Temperature Offset:", sensor.getTemperatureOffset()
print "Humidity Offset:", sensor.getHumidityOffset() print "Humidity Offset:", sensor.getHumidityOffset()
print print
# update and print available values every second # update and print available values every second
while (1): while (1):
# update our values from the sensor # update our values from the sensor
sensor.update() sensor.update()
@ -76,4 +77,7 @@ while (1):
print "Override Switch Status:", sensor.getOverrideSwitchStatus() print "Override Switch Status:", sensor.getOverrideSwitchStatus()
print print
time.sleep(1) time.sleep(1)
if __name__ == '__main__':
main()

92
examples/python/ili9341.py Normal file → Executable file
View File

@ -24,52 +24,56 @@
import time import time
import pyupm_ili9341 as ili9341 import pyupm_ili9341 as ili9341
# Pins (Edison) def main():
# CS_LCD GP44 (MRAA 31) # Pins (Edison)
# CS_SD GP43 (MRAA 38) unused # CS_LCD GP44 (MRAA 31)
# DC GP12 (MRAA 20) # CS_SD GP43 (MRAA 38) unused
# RESEST GP13 (MRAA 14) # DC GP12 (MRAA 20)
lcd = ili9341.ILI9341(31, 38, 20, 14) # RESEST GP13 (MRAA 14)
lcd = ili9341.ILI9341(31, 38, 20, 14)
# Fill the screen with a solid color # Fill the screen with a solid color
lcd.fillScreen(lcd.color565(0, 40, 16)) lcd.fillScreen(lcd.color565(0, 40, 16))
# Draw some shapes # Draw some shapes
lcd.drawFastVLine(10, 10, 100, ili9341.ILI9341_RED) lcd.drawFastVLine(10, 10, 100, ili9341.ILI9341_RED)
lcd.drawFastHLine(20, 10, 50, ili9341.ILI9341_CYAN) lcd.drawFastHLine(20, 10, 50, ili9341.ILI9341_CYAN)
lcd.drawLine(160, 30, 200, 60, ili9341.ILI9341_GREEN) lcd.drawLine(160, 30, 200, 60, ili9341.ILI9341_GREEN)
lcd.fillRect(20, 30, 75, 60, ili9341.ILI9341_ORANGE) lcd.fillRect(20, 30, 75, 60, ili9341.ILI9341_ORANGE)
lcd.drawCircle(70, 50, 20, ili9341.ILI9341_PURPLE) lcd.drawCircle(70, 50, 20, ili9341.ILI9341_PURPLE)
lcd.fillCircle(120, 50, 20, ili9341.ILI9341_PURPLE) lcd.fillCircle(120, 50, 20, ili9341.ILI9341_PURPLE)
lcd.drawTriangle(50, 100, 10, 140, 90, 140, ili9341.ILI9341_YELLOW) lcd.drawTriangle(50, 100, 10, 140, 90, 140, ili9341.ILI9341_YELLOW)
lcd.fillTriangle(150, 100, 110, 140, 190, 140, ili9341.ILI9341_YELLOW) lcd.fillTriangle(150, 100, 110, 140, 190, 140, ili9341.ILI9341_YELLOW)
lcd.drawRoundRect(20, 150, 50, 30, 10, ili9341.ILI9341_RED) lcd.drawRoundRect(20, 150, 50, 30, 10, ili9341.ILI9341_RED)
lcd.drawRoundRect(130, 150, 50, 30, 10, ili9341.ILI9341_RED) lcd.drawRoundRect(130, 150, 50, 30, 10, ili9341.ILI9341_RED)
lcd.fillRoundRect(75, 150, 50, 30, 10, ili9341.ILI9341_RED) lcd.fillRoundRect(75, 150, 50, 30, 10, ili9341.ILI9341_RED)
# Write some text # Write some text
lcd.setCursor(0, 200) lcd.setCursor(0, 200)
lcd.setTextColor(ili9341.ILI9341_LIGHTGREY) lcd.setTextColor(ili9341.ILI9341_LIGHTGREY)
lcd.setTextWrap(True) lcd.setTextWrap(True)
lcd.setTextSize(1) lcd.setTextSize(1)
lcd._print("Text 1\n") lcd._print("Text 1\n")
lcd.setTextSize(2) lcd.setTextSize(2)
lcd._print("Text 2\n") lcd._print("Text 2\n")
lcd.setTextSize(3) lcd.setTextSize(3)
lcd._print("Text 3\n") lcd._print("Text 3\n")
lcd.setTextSize(4) lcd.setTextSize(4)
lcd._print("Text 4\n") lcd._print("Text 4\n")
# Test screen rotation # Test screen rotation
for r in range(0, 4): for r in range(0, 4):
lcd.setRotation(r) lcd.setRotation(r)
lcd.fillRect(0, 0, 5, 5, ili9341.ILI9341_WHITE) lcd.fillRect(0, 0, 5, 5, ili9341.ILI9341_WHITE)
time.sleep(1) time.sleep(1)
# Invert colors, wait, then revert back
lcd.invertDisplay(True)
time.sleep(2)
lcd.invertDisplay(False)
# Don't forget to free up that memory! # Invert colors, wait, then revert back
del lcd lcd.invertDisplay(True)
time.sleep(2)
lcd.invertDisplay(False)
# Don't forget to free up that memory!
del lcd
if __name__ == '__main__':
main()

41
examples/python/ina132.py Normal file → Executable file
View File

@ -21,31 +21,32 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_ina132 as upmIna132 import pyupm_ina132 as upmIna132
# Tested with the INA132 Differential Amplifier Sensor module. def main():
# Instantiate an INA132 on analog pin A0 # Tested with the INA132 Differential Amplifier Sensor module.
myDifferentialAmplifier = upmIna132.INA132(0) # Instantiate an INA132 on analog pin A0
myDifferentialAmplifier = upmIna132.INA132(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myDifferentialAmplifier
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myDifferentialAmplifier atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers while(1):
atexit.register(exitHandler) print myDifferentialAmplifier.value()
signal.signal(signal.SIGINT, SIGINTHandler) time.sleep(1)
if __name__ == '__main__':
while(1): main()
print myDifferentialAmplifier.value()
time.sleep(1)

75
examples/python/isd1820.py Normal file → Executable file
View File

@ -24,51 +24,50 @@
import time, sys, atexit import time, sys, atexit
import pyupm_isd1820 as upmIsd1820 import pyupm_isd1820 as upmIsd1820
# Instantiate a ISD1820 on digital pins 2 (play) and 3 (record) def main():
# This example was tested on the Grove Recorder. # Instantiate a ISD1820 on digital pins 2 (play) and 3 (record)
myRecorder = upmIsd1820.ISD1820(2, 3) # This example was tested on the Grove Recorder.
myRecorder = upmIsd1820.ISD1820(2, 3)
doRecord = False
doRecord = False if len(sys.argv) > 1:
doRecord = True
if len(sys.argv) > 1: # This lets you run code on exit,
doRecord = True # including functions from myRecorder
def exitHandler():
# turn off whatever we were doing.
if (doRecord):
myRecorder.record(False)
else:
myRecorder.play(False)
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
# This lets you run code on exit, # if an argument was specified (any argument), go into record mode,
# including functions from myRecorder # else playback a previously recorded sample
def exitHandler():
# turn off whatever we were doing.
if (doRecord):
myRecorder.record(False)
else:
myRecorder.play(False)
print "Exiting"
sys.exit(0)
# Register exit handlers print "Supply any argument to the command line to record."
atexit.register(exitHandler) print "Running this example without arguments will play back any "
print "previously recorded sound."
print "There is approximately 10 seconds of recording time.\n"
# depending on what was selected, do it, and sleep for 15 seconds
if (doRecord):
myRecorder.record(True)
else:
myRecorder.play(True)
# if an argument was specified (any argument), go into record mode, # There are about 10 seconds of recording/playback time, so we will
# else playback a previously recorded sample # sleep for a little extra time.
print "Sleeping for 15 seconds..."
time.sleep(15)
print "Supply any argument to the command line to record." # exitHandler runs automatically
print "Running this example without arguments will play back any "
print "previously recorded sound."
print "There is approximately 10 seconds of recording time.\n"
if __name__ == '__main__':
# depending on what was selected, do it, and sleep for 15 seconds main()
if (doRecord):
myRecorder.record(True)
else:
myRecorder.play(True)
# There are about 10 seconds of recording/playback time, so we will
# sleep for a little extra time.
print "Sleeping for 15 seconds..."
time.sleep(15)
# exitHandler runs automatically

34
examples/python/itg3200.py Normal file → Executable file
View File

@ -23,20 +23,24 @@
import time import time
import pyupm_itg3200 as itg3200 import pyupm_itg3200 as itg3200
# Create an I2C gyro object def main():
gyro = itg3200.Itg3200(0) # Create an I2C gyro object
gyro = itg3200.Itg3200(0)
while(1): while(1):
gyro.update() # Update the data gyro.update() # Update the data
rot = gyro.getRawValues() # Read raw sensor data rot = gyro.getRawValues() # Read raw sensor data
ang = gyro.getRotation() # Read rotational speed (deg/sec) ang = gyro.getRotation() # Read rotational speed (deg/sec)
print "Raw: %6d %6d %6d" % (rot[0], rot[1], rot[2]) print "Raw: %6d %6d %6d" % (rot[0], rot[1], rot[2])
print "AngX: %5.2f" % (ang[0]) print "AngX: %5.2f" % (ang[0])
print "AngY: %5.2f" % (ang[1]) print "AngY: %5.2f" % (ang[1])
print "AngZ: %5.2f" % (ang[2]) print "AngZ: %5.2f" % (ang[2])
print "Temp: %5.2f Raw: %6d" % (gyro.getTemperature(), gyro.getRawTemp()) print "Temp: %5.2f Raw: %6d" % (gyro.getTemperature(), gyro.getRawTemp())
print ' ' print ' '
time.sleep(1) time.sleep(1)
# Delete the gyro object # Delete the gyro object
del gyro del gyro
if __name__ == '__main__':
main()

24
examples/python/jhd1313m1-lcd.py Normal file → Executable file
View File

@ -23,16 +23,20 @@
import pyupm_i2clcd as lcd import pyupm_i2clcd as lcd
# Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS) def main():
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62) # Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS)
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
myLcd.setCursor(0,0) myLcd.setCursor(0,0)
# RGB Blue # RGB Blue
#myLcd.setColor(53, 39, 249) #myLcd.setColor(53, 39, 249)
# RGB Red # RGB Red
myLcd.setColor(255, 0, 0) myLcd.setColor(255, 0, 0)
myLcd.write('Hello World') myLcd.write('Hello World')
myLcd.setCursor(1,2) myLcd.setCursor(1,2)
myLcd.write('Hello World') myLcd.write('Hello World')
if __name__ == '__main__':
main()

42
examples/python/joystick12.py Normal file → Executable file
View File

@ -24,29 +24,31 @@
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_joystick12 as upmJoystick12 import pyupm_joystick12 as upmJoystick12
# Instantiate a joystick on analog pins A0 and A1 def main():
myJoystick = upmJoystick12.Joystick12(0, 1) # Instantiate a joystick on analog pins A0 and A1
myJoystick = upmJoystick12.Joystick12(0, 1)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This function lets you run code on exit, including functions from myJoystick
# This function stops python from printing a stacktrace when you hit control-C def exitHandler():
def SIGINTHandler(signum, frame): print "Exiting"
raise SystemExit sys.exit(0)
# This function lets you run code on exit, including functions from myJoystick # Register exit handlers
def exitHandler(): atexit.register(exitHandler)
print "Exiting" signal.signal(signal.SIGINT, SIGINTHandler)
sys.exit(0)
# Register exit handlers # Print the X and Y input values every second
atexit.register(exitHandler) while(1):
signal.signal(signal.SIGINT, SIGINTHandler) XString = "Driving X:" + str(myJoystick.getXInput())
YString = ": and Y:" + str(myJoystick.getYInput())
print XString + YString
time.sleep(1)
# Print the X and Y input values every second if __name__ == '__main__':
while(1): main()
XString = "Driving X:" + str(myJoystick.getXInput())
YString = ": and Y:" + str(myJoystick.getYInput())
print XString + YString
time.sleep(1)

63
examples/python/l298-stepper.py Normal file → Executable file
View File

@ -21,47 +21,48 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_l298 as upmL298 import pyupm_l298 as upmL298
# Instantiate a Stepper motor on a L298 Dual H-Bridge. def main():
# This was tested with the NEMA-17 12V, 350mA, with 200 steps per rev. # Instantiate a Stepper motor on a L298 Dual H-Bridge.
myHBridge = upmL298.L298(200, 3, 4, 7, 8, 9) # This was tested with the NEMA-17 12V, 350mA, with 200 steps per rev.
myHBridge = upmL298.L298(200, 3, 4, 7, 8, 9)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myHBridge
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myHBridge atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers myHBridge.setSpeed(10) # 10 RPMs
atexit.register(exitHandler) myHBridge.setDirection(upmL298.L298.DIR_CW)
signal.signal(signal.SIGINT, SIGINTHandler) myHBridge.enable(True)
print "Rotating 1 full revolution at 10 RPM speed."
# move 200 steps, a full rev
myHBridge.stepperSteps(200)
myHBridge.setSpeed(10) # 10 RPMs print "Sleeping for 2 seconds..."
myHBridge.setDirection(upmL298.L298.DIR_CW) time.sleep(2)
myHBridge.enable(True)
print "Rotating 1 full revolution at 10 RPM speed." print "Rotating 1/2 revolution in opposite direction at 10 RPM speed."
# move 200 steps, a full rev myHBridge.setDirection(upmL298.L298.DIR_CCW)
myHBridge.stepperSteps(200) myHBridge.stepperSteps(100)
print "Sleeping for 2 seconds..." # release
time.sleep(2) myHBridge.enable(False)
print "Rotating 1/2 revolution in opposite direction at 10 RPM speed." # exitHandler is called automatically
myHBridge.setDirection(upmL298.L298.DIR_CCW)
myHBridge.stepperSteps(100)
# release if __name__ == '__main__':
myHBridge.enable(False) main()
# exitHandler is called automatically

61
examples/python/l298.py Normal file → Executable file
View File

@ -21,45 +21,46 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit import time, sys, signal, atexit
import pyupm_l298 as upmL298 import pyupm_l298 as upmL298
# Instantiate one of the 2 possible DC motors on a L298 Dual def main():
# H-Bridge. For controlling a stepper motor, see the l298-stepper # Instantiate one of the 2 possible DC motors on a L298 Dual
# example. # H-Bridge. For controlling a stepper motor, see the l298-stepper
myHBridge = upmL298.L298(3, 4, 7) # example.
myHBridge = upmL298.L298(3, 4, 7)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
## Exit handlers ## # This lets you run code on exit,
# This stops python from printing a stacktrace when you hit control-C # including functions from myHBridge
def SIGINTHandler(signum, frame): def exitHandler():
raise SystemExit print "Exiting"
sys.exit(0)
# This lets you run code on exit, # Register exit handlers
# including functions from myHBridge atexit.register(exitHandler)
def exitHandler(): signal.signal(signal.SIGINT, SIGINTHandler)
print "Exiting"
sys.exit(0)
# Register exit handlers print "Starting motor at 50% for 3 seconds..."
atexit.register(exitHandler) myHBridge.setSpeed(50)
signal.signal(signal.SIGINT, SIGINTHandler) myHBridge.setDirection(upmL298.L298.DIR_CW)
myHBridge.enable(True)
time.sleep(3)
print "Starting motor at 50% for 3 seconds..." print "Reversing direction..."
myHBridge.setSpeed(50) myHBridge.setDirection(upmL298.L298.DIR_NONE) # fast stop
myHBridge.setDirection(upmL298.L298.DIR_CW) myHBridge.setDirection(upmL298.L298.DIR_CCW)
myHBridge.enable(True) time.sleep(3);
time.sleep(3) myHBridge.setSpeed(0)
myHBridge.enable(False)
print "Reversing direction..." # exitHandler is called automatically
myHBridge.setDirection(upmL298.L298.DIR_NONE) # fast stop
myHBridge.setDirection(upmL298.L298.DIR_CCW)
time.sleep(3);
myHBridge.setSpeed(0) if __name__ == '__main__':
myHBridge.enable(False) main()
# exitHandler is called automatically

Some files were not shown because too many files have changed in this diff Show More