From 2f78d9f62b7b96ebdd4faecf5e7a2f92a227bda3 Mon Sep 17 00:00:00 2001 From: Noel Eck Date: Thu, 29 Sep 2016 18:24:19 -0700 Subject: [PATCH] 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 --- .travis.yml | 6 +- doxy/samples.mapping.txt | 145 +++++----- examples/python/a110x.py | 42 +-- examples/python/ad8232.py | 48 ++-- examples/python/adafruitms1438-stepper.py | 90 +++--- examples/python/adafruitms1438.py | 82 +++--- examples/python/adc121c021.py | 48 ++-- examples/python/adxl335.py | 82 +++--- examples/python/adxl345.py | 29 +- examples/python/adxrs610.py | 46 ++-- examples/python/aeotecdsb09104.py | 81 +++--- examples/python/aeotecdw2e.py | 76 +++--- examples/python/aeotecsdg2.py | 64 +++-- examples/python/aeotecss6.py | 56 ++-- examples/python/ak8975.py | 44 +-- examples/python/apa102.py | 33 +-- examples/python/apds9002.py | 38 +-- examples/python/at42qt1070.py | 80 +++--- examples/python/bh1750.py | 40 +-- examples/python/biss0001.py | 44 +-- examples/python/bma220.py | 42 +-- examples/python/bma250e.py | 46 ++-- examples/python/bmc150.py | 42 +-- examples/python/bme280.py | 38 +-- examples/python/bmg160.py | 46 ++-- examples/python/bmi055.py | 42 +-- examples/python/bmi160.py | 40 +-- examples/python/bmm150.py | 46 ++-- examples/python/bmp280.py | 38 +-- examples/python/bmpx8x.py | 56 ++-- examples/python/bmx055.py | 42 +-- examples/python/bno055.py | 76 +++--- examples/python/button.py | 20 +- examples/python/buzzer.py | 34 ++- examples/python/cjq4435.py | 33 ++- examples/python/collision.py | 52 ++-- examples/python/curieimu.py | 38 +-- examples/python/cwlsxxa.py | 40 +-- examples/python/dfrec.py | 42 +-- examples/python/dfrorp.py | 66 ++--- examples/python/dfrph.py | 48 ++-- examples/python/ds1307.py | 53 ++-- examples/python/ds18b20.py | 48 ++-- examples/python/ds2413.py | 52 ++-- examples/python/e50hx.py | 84 +++--- examples/python/eboled.py | 25 +- examples/python/ehr.py | 69 ++--- examples/python/eldriver.py | 50 ++-- examples/python/electromagnet.py | 56 ++-- examples/python/emg.py | 42 +-- examples/python/enc03r.py | 60 ++-- examples/python/es08a.py | 42 +-- examples/python/gp2y0a.py | 62 +++-- examples/python/gprs.py | 78 +++--- examples/python/grovebutton.py | 20 +- examples/python/grovecircularled.py | 36 +-- examples/python/grovecollision.py | 52 ++-- examples/python/groveehr.py | 69 ++--- examples/python/groveeldriver.py | 50 ++-- examples/python/groveelectromagnet.py | 56 ++-- examples/python/groveemg.py | 42 +-- examples/python/grovegprs.py | 78 +++--- examples/python/grovegsr.py | 42 +-- examples/python/groveled.py | 30 +- examples/python/groveledbar.py | 66 ++--- examples/python/grovelight.py | 24 +- examples/python/grovelinefinder.py | 42 +-- examples/python/grovemd-stepper.py | 37 +-- examples/python/grovemd.py | 35 +-- examples/python/grovemoisture.py | 60 ++-- examples/python/groveo2.py | 40 +-- examples/python/groverelay.py | 38 +-- examples/python/groverotary.py | 33 ++- examples/python/grovescam.py | 40 +-- examples/python/groveslide.py | 23 +- examples/python/grovespeaker.py | 16 +- examples/python/grovetemp.py | 30 +- examples/python/grovevdiv.py | 46 ++-- examples/python/grovewater.py | 42 +-- examples/python/grovewfs.py | 62 +++-- examples/python/gsr.py | 42 +-- examples/python/guvas12d.py | 50 ++-- examples/python/h3lis331dl.py | 84 +++--- examples/python/h803x.py | 110 ++++---- examples/python/hdxxvxta.py | 40 +-- examples/python/hka5.py | 36 +-- examples/python/hm11.py | 143 +++++----- examples/python/hmc5883l.py | 33 ++- examples/python/hmtrp.py | 198 +++++++------- examples/python/hp20x.py | 47 ++-- examples/python/ht9170.py | 49 ++-- examples/python/hwxpxx.py | 60 ++-- examples/python/ili9341.py | 92 ++++--- examples/python/ina132.py | 41 +-- examples/python/isd1820.py | 75 +++-- examples/python/itg3200.py | 34 ++- examples/python/jhd1313m1-lcd.py | 24 +- examples/python/joystick12.py | 42 +-- examples/python/l298-stepper.py | 63 ++--- examples/python/l298.py | 61 +++-- examples/python/ldt0028.py | 74 ++--- examples/python/led.py | 30 +- examples/python/light.py | 24 +- examples/python/linefinder.py | 42 +-- examples/python/lm35.py | 38 +-- examples/python/loudness.py | 40 +-- examples/python/lsm303.py | 96 +++---- examples/python/lsm9ds0.py | 50 ++-- examples/python/m24lr64e.py | 37 +-- examples/python/make_oled_pic.py | 72 ++--- examples/python/maxsonarez.py | 53 ++-- examples/python/md-stepper.py | 37 +-- examples/python/md.py | 35 +-- examples/python/mg811.py | 40 +-- examples/python/mhz16.py | 72 ++--- examples/python/mic.py | 46 ++-- examples/python/mma7361.py | 52 ++-- examples/python/mma7660.py | 90 +++--- examples/python/moisture.py | 60 ++-- examples/python/mpr121.py | 75 ++--- examples/python/mpu60x0.py | 46 ++-- examples/python/mpu9150.py | 48 ++-- examples/python/mpu9250.py | 48 ++-- examples/python/mq2.py | 62 +++-- examples/python/mq3.py | 62 +++-- examples/python/mq303a.py | 80 +++--- examples/python/mq4.py | 62 +++-- examples/python/mq5.py | 62 +++-- examples/python/mq6.py | 62 +++-- examples/python/mq7.py | 62 +++-- examples/python/mq8.py | 62 +++-- examples/python/mq9.py | 62 +++-- examples/python/nlgpio16.py | 46 ++-- examples/python/nmea_gps.py | 38 +-- examples/python/nmea_gps_i2c.py | 39 +-- examples/python/nunchuck.py | 76 +++--- examples/python/o2.py | 40 +-- examples/python/oled_ssd1308.py | 132 ++++----- examples/python/oled_ssd1327.py | 316 +++++++++++----------- examples/python/otp538u.py | 52 ++-- examples/python/ozwdump.py | 128 ++++----- examples/python/pn532-writeurl.py | 115 ++++---- examples/python/pn532.py | 96 +++---- examples/python/ppd42ns.py | 50 ++-- examples/python/relay.py | 38 +-- examples/python/rfr359f.py | 44 +-- examples/python/rgbringcoder.py | 87 +++--- examples/python/rhusb.py | 52 ++-- examples/python/rotary.py | 33 ++- examples/python/rotaryencoder.py | 38 +-- examples/python/rpr220.py | 48 ++-- examples/python/sainsmartks.py | 47 ++-- examples/python/scam.py | 40 +-- examples/python/sht1x.py | 38 +-- examples/python/si114x.py | 64 ++--- examples/python/slide.py | 23 +- examples/python/sm130.py | 50 ++-- examples/python/speaker.py | 16 +- examples/python/stepmotor.py | 67 ++--- examples/python/sx1276-fsk.py | 106 ++++---- examples/python/sx1276-lora.py | 106 ++++---- examples/python/sx6119.py | 40 +-- examples/python/t3311.py | 72 ++--- examples/python/t8100.py | 84 +++--- examples/python/ta12200.py | 46 ++-- examples/python/tb7300.py | 102 +++---- examples/python/tcs3414cs.py | 46 ++-- examples/python/teams.py | 44 +-- examples/python/temperature.py | 30 +- examples/python/tex00.py | 56 ++-- examples/python/tm1637.py | 52 ++-- examples/python/tp401.py | 49 ++-- examples/python/tsl2561.py | 36 +-- examples/python/ttp223.py | 28 +- examples/python/tzemt400.py | 48 ++-- examples/python/uln200xa.py | 60 ++-- examples/python/urm37-uart.py | 38 +-- examples/python/urm37.py | 40 +-- examples/python/using_carrays.py | 31 --- examples/python/vcap.py | 61 +++-- examples/python/vdiv.py | 46 ++-- examples/python/water.py | 42 +-- examples/python/waterlevel.py | 46 ++-- examples/python/wfs.py | 62 +++-- examples/python/wheelencoder.py | 40 +-- examples/python/wt5001.py | 133 +++++---- examples/python/xbee.py | 87 +++--- examples/python/yg1006.py | 42 +-- examples/python/zfm20-register.py | 161 ++++++----- examples/python/zfm20.py | 102 +++---- src/CMakeLists.txt | 2 +- src/lp8860/javaupm_lp8860.i | 11 + src/ms5611/javaupm_ms5611.i | 11 + src/si1132/javaupm_si1132.i | 16 +- src/smartdrive/javaupm_smartdrive.i | 11 + src/upm/javaupm_interfaces.i | 19 +- src/upm/javaupm_light_sensor.i | 15 +- tests/CMakeLists.txt | 35 ++- tests/check_autoloadlibrary.py | 3 +- tests/check_clean.py | 2 + tests/check_examplenames.py | 75 +++++ tests/check_pythonload.py | 68 +++++ tests/check_samplenames.py | 53 ---- 203 files changed, 5890 insertions(+), 5216 deletions(-) mode change 100644 => 100755 examples/python/a110x.py mode change 100644 => 100755 examples/python/ad8232.py mode change 100644 => 100755 examples/python/adafruitms1438-stepper.py mode change 100644 => 100755 examples/python/adafruitms1438.py mode change 100644 => 100755 examples/python/adc121c021.py mode change 100644 => 100755 examples/python/adxl335.py mode change 100644 => 100755 examples/python/adxl345.py mode change 100644 => 100755 examples/python/adxrs610.py mode change 100644 => 100755 examples/python/aeotecdsb09104.py mode change 100644 => 100755 examples/python/aeotecdw2e.py mode change 100644 => 100755 examples/python/aeotecsdg2.py mode change 100644 => 100755 examples/python/aeotecss6.py mode change 100644 => 100755 examples/python/ak8975.py mode change 100644 => 100755 examples/python/apa102.py mode change 100644 => 100755 examples/python/apds9002.py mode change 100644 => 100755 examples/python/at42qt1070.py mode change 100644 => 100755 examples/python/bh1750.py mode change 100644 => 100755 examples/python/biss0001.py mode change 100644 => 100755 examples/python/bma220.py mode change 100644 => 100755 examples/python/bma250e.py mode change 100644 => 100755 examples/python/bmc150.py mode change 100644 => 100755 examples/python/bme280.py mode change 100644 => 100755 examples/python/bmg160.py mode change 100644 => 100755 examples/python/bmi055.py mode change 100644 => 100755 examples/python/bmi160.py mode change 100644 => 100755 examples/python/bmm150.py mode change 100644 => 100755 examples/python/bmp280.py mode change 100644 => 100755 examples/python/bmpx8x.py mode change 100644 => 100755 examples/python/bmx055.py mode change 100644 => 100755 examples/python/bno055.py mode change 100644 => 100755 examples/python/button.py mode change 100644 => 100755 examples/python/buzzer.py mode change 100644 => 100755 examples/python/cjq4435.py mode change 100644 => 100755 examples/python/collision.py mode change 100644 => 100755 examples/python/curieimu.py mode change 100644 => 100755 examples/python/cwlsxxa.py mode change 100644 => 100755 examples/python/dfrec.py mode change 100644 => 100755 examples/python/dfrorp.py mode change 100644 => 100755 examples/python/dfrph.py mode change 100644 => 100755 examples/python/ds1307.py mode change 100644 => 100755 examples/python/ds18b20.py mode change 100644 => 100755 examples/python/ds2413.py mode change 100644 => 100755 examples/python/e50hx.py mode change 100644 => 100755 examples/python/eboled.py mode change 100644 => 100755 examples/python/ehr.py mode change 100644 => 100755 examples/python/eldriver.py mode change 100644 => 100755 examples/python/electromagnet.py mode change 100644 => 100755 examples/python/emg.py mode change 100644 => 100755 examples/python/enc03r.py mode change 100644 => 100755 examples/python/es08a.py mode change 100644 => 100755 examples/python/gp2y0a.py mode change 100644 => 100755 examples/python/gprs.py mode change 100644 => 100755 examples/python/grovebutton.py mode change 100644 => 100755 examples/python/grovecircularled.py mode change 100644 => 100755 examples/python/grovecollision.py mode change 100644 => 100755 examples/python/groveehr.py mode change 100644 => 100755 examples/python/groveeldriver.py mode change 100644 => 100755 examples/python/groveelectromagnet.py mode change 100644 => 100755 examples/python/groveemg.py mode change 100644 => 100755 examples/python/grovegprs.py mode change 100644 => 100755 examples/python/grovegsr.py mode change 100644 => 100755 examples/python/groveled.py mode change 100644 => 100755 examples/python/groveledbar.py mode change 100644 => 100755 examples/python/grovelight.py mode change 100644 => 100755 examples/python/grovelinefinder.py mode change 100644 => 100755 examples/python/grovemd-stepper.py mode change 100644 => 100755 examples/python/grovemd.py mode change 100644 => 100755 examples/python/grovemoisture.py mode change 100644 => 100755 examples/python/groveo2.py mode change 100644 => 100755 examples/python/groverelay.py mode change 100644 => 100755 examples/python/groverotary.py mode change 100644 => 100755 examples/python/grovescam.py mode change 100644 => 100755 examples/python/groveslide.py mode change 100644 => 100755 examples/python/grovespeaker.py mode change 100644 => 100755 examples/python/grovetemp.py mode change 100644 => 100755 examples/python/grovevdiv.py mode change 100644 => 100755 examples/python/grovewater.py mode change 100644 => 100755 examples/python/grovewfs.py mode change 100644 => 100755 examples/python/gsr.py mode change 100644 => 100755 examples/python/guvas12d.py mode change 100644 => 100755 examples/python/h3lis331dl.py mode change 100644 => 100755 examples/python/h803x.py mode change 100644 => 100755 examples/python/hdxxvxta.py mode change 100644 => 100755 examples/python/hka5.py mode change 100644 => 100755 examples/python/hm11.py mode change 100644 => 100755 examples/python/hmc5883l.py mode change 100644 => 100755 examples/python/hmtrp.py mode change 100644 => 100755 examples/python/hp20x.py mode change 100644 => 100755 examples/python/ht9170.py mode change 100644 => 100755 examples/python/hwxpxx.py mode change 100644 => 100755 examples/python/ili9341.py mode change 100644 => 100755 examples/python/ina132.py mode change 100644 => 100755 examples/python/isd1820.py mode change 100644 => 100755 examples/python/itg3200.py mode change 100644 => 100755 examples/python/jhd1313m1-lcd.py mode change 100644 => 100755 examples/python/joystick12.py mode change 100644 => 100755 examples/python/l298-stepper.py mode change 100644 => 100755 examples/python/l298.py mode change 100644 => 100755 examples/python/ldt0028.py mode change 100644 => 100755 examples/python/led.py mode change 100644 => 100755 examples/python/light.py mode change 100644 => 100755 examples/python/linefinder.py mode change 100644 => 100755 examples/python/lm35.py mode change 100644 => 100755 examples/python/loudness.py mode change 100644 => 100755 examples/python/lsm303.py mode change 100644 => 100755 examples/python/lsm9ds0.py mode change 100644 => 100755 examples/python/m24lr64e.py mode change 100644 => 100755 examples/python/maxsonarez.py mode change 100644 => 100755 examples/python/md-stepper.py mode change 100644 => 100755 examples/python/md.py mode change 100644 => 100755 examples/python/mg811.py mode change 100644 => 100755 examples/python/mhz16.py mode change 100644 => 100755 examples/python/mic.py mode change 100644 => 100755 examples/python/mma7361.py mode change 100644 => 100755 examples/python/mma7660.py mode change 100644 => 100755 examples/python/moisture.py mode change 100644 => 100755 examples/python/mpr121.py mode change 100644 => 100755 examples/python/mpu60x0.py mode change 100644 => 100755 examples/python/mpu9150.py mode change 100644 => 100755 examples/python/mpu9250.py mode change 100644 => 100755 examples/python/mq2.py mode change 100644 => 100755 examples/python/mq3.py mode change 100644 => 100755 examples/python/mq303a.py mode change 100644 => 100755 examples/python/mq4.py mode change 100644 => 100755 examples/python/mq5.py mode change 100644 => 100755 examples/python/mq6.py mode change 100644 => 100755 examples/python/mq7.py mode change 100644 => 100755 examples/python/mq8.py mode change 100644 => 100755 examples/python/mq9.py mode change 100644 => 100755 examples/python/nlgpio16.py mode change 100644 => 100755 examples/python/nmea_gps.py mode change 100644 => 100755 examples/python/nmea_gps_i2c.py mode change 100644 => 100755 examples/python/nunchuck.py mode change 100644 => 100755 examples/python/o2.py mode change 100644 => 100755 examples/python/oled_ssd1308.py mode change 100644 => 100755 examples/python/oled_ssd1327.py mode change 100644 => 100755 examples/python/otp538u.py mode change 100644 => 100755 examples/python/ozwdump.py mode change 100644 => 100755 examples/python/pn532-writeurl.py mode change 100644 => 100755 examples/python/pn532.py mode change 100644 => 100755 examples/python/ppd42ns.py mode change 100644 => 100755 examples/python/relay.py mode change 100644 => 100755 examples/python/rfr359f.py mode change 100644 => 100755 examples/python/rgbringcoder.py mode change 100644 => 100755 examples/python/rhusb.py mode change 100644 => 100755 examples/python/rotary.py mode change 100644 => 100755 examples/python/rotaryencoder.py mode change 100644 => 100755 examples/python/rpr220.py mode change 100644 => 100755 examples/python/sainsmartks.py mode change 100644 => 100755 examples/python/scam.py mode change 100644 => 100755 examples/python/sht1x.py mode change 100644 => 100755 examples/python/si114x.py mode change 100644 => 100755 examples/python/slide.py mode change 100644 => 100755 examples/python/sm130.py mode change 100644 => 100755 examples/python/speaker.py mode change 100644 => 100755 examples/python/stepmotor.py mode change 100644 => 100755 examples/python/sx1276-fsk.py mode change 100644 => 100755 examples/python/sx1276-lora.py mode change 100644 => 100755 examples/python/sx6119.py mode change 100644 => 100755 examples/python/t3311.py mode change 100644 => 100755 examples/python/t8100.py mode change 100644 => 100755 examples/python/ta12200.py mode change 100644 => 100755 examples/python/tb7300.py mode change 100644 => 100755 examples/python/tcs3414cs.py mode change 100644 => 100755 examples/python/teams.py mode change 100644 => 100755 examples/python/temperature.py mode change 100644 => 100755 examples/python/tex00.py mode change 100644 => 100755 examples/python/tm1637.py mode change 100644 => 100755 examples/python/tp401.py mode change 100644 => 100755 examples/python/tsl2561.py mode change 100644 => 100755 examples/python/ttp223.py mode change 100644 => 100755 examples/python/tzemt400.py mode change 100644 => 100755 examples/python/uln200xa.py mode change 100644 => 100755 examples/python/urm37-uart.py mode change 100644 => 100755 examples/python/urm37.py delete mode 100644 examples/python/using_carrays.py mode change 100644 => 100755 examples/python/vcap.py mode change 100644 => 100755 examples/python/vdiv.py mode change 100644 => 100755 examples/python/water.py mode change 100644 => 100755 examples/python/waterlevel.py mode change 100644 => 100755 examples/python/wfs.py mode change 100644 => 100755 examples/python/wheelencoder.py mode change 100644 => 100755 examples/python/wt5001.py mode change 100644 => 100755 examples/python/xbee.py mode change 100644 => 100755 examples/python/yg1006.py mode change 100644 => 100755 examples/python/zfm20-register.py mode change 100644 => 100755 examples/python/zfm20.py create mode 100755 tests/check_examplenames.py create mode 100755 tests/check_pythonload.py delete mode 100755 tests/check_samplenames.py diff --git a/.travis.yml b/.travis.yml index f71b0e82..45f53d31 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,8 +33,10 @@ before_script: script: - 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 - - 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 - - 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 + - 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 -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: apt: sources: diff --git a/doxy/samples.mapping.txt b/doxy/samples.mapping.txt index f044dbe7..61ed8082 100644 --- a/doxy/samples.mapping.txt +++ b/doxy/samples.mapping.txt @@ -1,73 +1,72 @@ -# Mapping C++ sample files to Java sample files -a110x-intr.cxx A110X_intrSample.java -a110x.cxx A110XSample.java -adc121c021.cxx ADC121C021Sample.java -adxl345.cxx Adxl345Sample.java -biss0001.cxx BISS0001Sample.java -bmpx8x.cxx BMPX8XSample.java -buzzer-sound.cxx Buzzer_soundSample.java -cjq4435.cxx CJQ4435Sample.java -ds1307.cxx DS1307Sample.java -enc03r.cxx ENC03RSample.java -es08a.cxx ES08ASample.java -button.cxx ButtonSample.java -groveehr.cxx GroveEHRSample.java -groveled.cxx GroveLEDSample.java -grovelinefinder.cxx GroveLineFinderSample.java -light.cxx LightSample.java -grovemoisture.cxx GroveMoistureSample.java -relay.cxx RelaySample.java -rotary.cxx RotarySample.java -grovescam.cxx GROVESCAMSample.java -slide.cxx SlideSample.java -speaker.cxx SpeakerSample.java -vdiv.cxx VDivSample.java -water.cxx WaterSample.java -grovewfs.cxx GroveWFSSample.java -guvas12d.cxx GUVAS12DSample.java -h3lis331dl.cxx H3LIS331DLSample.java -hcsr04.cxx HCSR04Sample.java -hm11.cxx HM11Sample.java -hmc5883l.cxx Hmc5883lSample.java -htu21d.cxx HTU21DSample.java -itg3200.cxx Itg3200Sample.java -jhd1313m1-lcd.cxx Jhd1313m1_lcdSample.java -joystick12.cxx Joystick12Sample.java -lcm1602-i2c.cxx Lcm1602_i2cSample.java -ldt0028.cxx LDT0028Sample.java -lol.cxx LoLSample.java -lsm303.cxx LSM303Sample.java -m24lr64e.cxx M24LR64ESample.java -max44000.cxx MAX44000Sample.java -mic.cxx MicrophoneSample.java -mma7455.cxx MMA7455Sample.java -mma7660.cxx MMA7660Sample.java -mpl3115a2.cxx MPL3115A2Sample.java -mpr121.cxx MPR121Sample.java -mpu9150.cxx MPU9150Sample.java -mq2.cxx MQ2Sample.java -mq303a.cxx MQ303ASample.java -mq5.cxx MQ5Sample.java -groveledbar GroveLEDBar -nrf24l01-receiver.cxx NRF24L01_receiverSample.java -nrf24l01-transmitter.cxx NRF24L01_transmitterSample.java -nunchuck.cxx NUNCHUCKSample.java -otp538u.cxx OTP538USample.java -ppd42ns.cxx PPD42NSSample.java -pulsensor.cxx PulsensorSample.java -rfr359f.cxx RFR359FSample.java -rotaryencoder.cxx RotaryEncoderSample.java -rpr220-intr.cxx RPR220_intrSample.java -rpr220.cxx RPR220Sample.java -ssd1308-oled.cxx SSD1308_oledSample.java -ssd1327-oled.cxx SSD1327_oledSample.java -st7735.cxx ST7735Sample.java -stepmotor.cxx StepMotorSample.java -tm1637.cxx TM1637Sample.java -tp401.cxx TP401Sample.java -tsl2561.cxx TSL2561Sample.java -ttp223.cxx TTP223Sample.java -ublox6.cxx Ublox6Sample.java -uln200xa.cxx ULN200XASample.java -wt5001.cxx WT5001Sample.java -yg1006.cxx YG1006Sample.java +# Mapping examples across provided languages +a110x.cxx A110XSample.java a110x.js a110x.py +a110x-intr.cxx A110X_intrSample.java a110x-intr.js a110x-intr.py +adc121c021.cxx ADC121C021Sample.java adc121c021.js adc121c021.py +adxl345.cxx Adxl345Sample.java adxl345.js adxl345.py +biss0001.cxx BISS0001Sample.java biss0001.js biss0001.py +bmpx8x.cxx BMPX8XSample.java bmpx8x.js bmpx8x.py +button.cxx ButtonSample.java button.js button.py +buzzer-sound.cxx Buzzer_soundSample.java buzzer-sound.js buzzer-sound.py +cjq4435.cxx CJQ4435Sample.java cjq4435.js cjq4435.py +ds1307.cxx DS1307Sample.java ds1307.js ds1307.py +enc03r.cxx ENC03RSample.java enc03r.js enc03r.py +es08a.cxx ES08ASample.java es08a.js es08a.py +groveehr.cxx GroveEHRSample.java groveehr.js groveehr.py +groveledbar.cxx GroveLEDBar.java groveledbar.js groveledbar.py +groveled.cxx GroveLEDSample.java groveled.js groveled.py +grovelinefinder.cxx GroveLineFinderSample.java grovelinefinder.js grovelinefinder.py +grovemoisture.cxx GroveMoistureSample.java grovemoisture.js grovemoisture.py +grovescam.cxx GROVESCAMSample.java grovescam.js grovescam.py +grovewfs.cxx GroveWFSSample.java grovewfs.js grovewfs.py +guvas12d.cxx GUVAS12DSample.java guvas12d.js guvas12d.py +h3lis331dl.cxx H3LIS331DLSample.java h3lis331dl.js h3lis331dl.py +hcsr04.cxx HCSR04Sample.java hcsr04.js hcsr04.py +hm11.cxx HM11Sample.java hm11.js hm11.py +hmc5883l.cxx Hmc5883lSample.java hmc5883l.js hmc5883l.py +htu21d.cxx HTU21DSample.java htu21d.js htu21d.py +itg3200.cxx Itg3200Sample.java itg3200.js itg3200.py +jhd1313m1-lcd.cxx Jhd1313m1_lcdSample.java jhd1313m1-lcd.js jhd1313m1-lcd.py +joystick12.cxx Joystick12Sample.java joystick12.js joystick12.py +lcm1602-i2c.cxx Lcm1602_i2cSample.java lcm1602-i2c.js lcm1602-i2c.py +ldt0028.cxx LDT0028Sample.java ldt0028.js ldt0028.py +light.cxx LightSample.java light.js light.py +lol.cxx LoLSample.java lol.js lol.py +lsm303.cxx LSM303Sample.java lsm303.js lsm303.py +m24lr64e.cxx M24LR64ESample.java m24lr64e.js m24lr64e.py +max44000.cxx MAX44000Sample.java max44000.js max44000.py +mic.cxx MicrophoneSample.java mic.js mic.py +mma7455.cxx MMA7455Sample.java mma7455.js mma7455.py +mma7660.cxx MMA7660Sample.java mma7660.js mma7660.py +mpl3115a2.cxx MPL3115A2Sample.java mpl3115a2.js mpl3115a2.py +mpr121.cxx MPR121Sample.java mpr121.js mpr121.py +mpu9150.cxx MPU9150Sample.java mpu9150.js mpu9150.py +mq2.cxx MQ2Sample.java mq2.js mq2.py +mq303a.cxx MQ303ASample.java mq303a.js mq303a.py +mq5.cxx MQ5Sample.java mq5.js mq5.py +nrf24l01-receiver.cxx NRF24L01_receiverSample.java nrf24l01-receiver.js nrf24l01-receiver.py +nrf24l01-transmitter.cxx NRF24L01_transmitterSample.java nrf24l01-transmitter.js nrf24l01-transmitter.py +nunchuck.cxx NUNCHUCKSample.java nunchuck.js nunchuck.py +otp538u.cxx OTP538USample.java otp538u.js otp538u.py +ppd42ns.cxx PPD42NSSample.java ppd42ns.js ppd42ns.py +pulsensor.cxx PulsensorSample.java pulsensor.js pulsensor.py +relay.cxx RelaySample.java relay.js relay.py +rfr359f.cxx RFR359FSample.java rfr359f.js rfr359f.py +rotary.cxx RotarySample.java rotary.js rotary.py +rotaryencoder.cxx RotaryEncoderSample.java rotaryencoder.js rotaryencoder.py +rpr220.cxx RPR220Sample.java rpr220.js rpr220.py +rpr220-intr.cxx RPR220_intrSample.java rpr220-intr.js rpr220-intr.py +slide.cxx SlideSample.java slide.js slide.py +speaker.cxx SpeakerSample.java speaker.js speaker.py +ssd1308-oled.cxx SSD1308_oledSample.java ssd1308-oled.js ssd1308-oled.py +ssd1327-oled.cxx SSD1327_oledSample.java ssd1327-oled.js ssd1327-oled.py +st7735.cxx ST7735Sample.java st7735.js st7735.py +stepmotor.cxx StepMotorSample.java stepmotor.js stepmotor.py +tm1637.cxx TM1637Sample.java tm1637.js tm1637.py +tp401.cxx TP401Sample.java tp401.js tp401.py +tsl2561.cxx TSL2561Sample.java tsl2561.js tsl2561.py +ttp223.cxx TTP223Sample.java ttp223.js ttp223.py +uln200xa.cxx ULN200XASample.java uln200xa.js uln200xa.py +vdiv.cxx VDivSample.java vdiv.js vdiv.py +water.cxx WaterSample.java water.js water.py +wt5001.cxx WT5001Sample.java wt5001.js wt5001.py +yg1006.cxx YG1006Sample.java yg1006.js yg1006.py diff --git a/examples/python/a110x.py b/examples/python/a110x.py old mode 100644 new mode 100755 index 15ba01e3..503714a4 --- a/examples/python/a110x.py +++ b/examples/python/a110x.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_a110x as upmA110x -# Instantiate a Hall Effect magnet sensor on digital pin D2 -myHallEffectSensor = upmA110x.A110X(2) +def main(): + # 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 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, including functions from myHallEffectSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myHallEffectSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myHallEffectSensor.magnetDetected()): + print "Magnet (south polarity) detected." + else: + print "No magnet detected." + time.sleep(1) - -while(1): - if (myHallEffectSensor.magnetDetected()): - print "Magnet (south polarity) detected." - else: - print "No magnet detected." - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/ad8232.py b/examples/python/ad8232.py old mode 100644 new mode 100755 index 97284ada..1527d462 --- a/examples/python/ad8232.py +++ b/examples/python/ad8232.py @@ -24,31 +24,33 @@ import time, sys, signal, atexit import pyupm_ad8232 as upmAD8232 -# Instantiate a AD8232 sensor on digital pins 10 (LO+), 11 (LO-) -# and an analog pin, 0 (OUTPUT) -myAD8232 = upmAD8232.AD8232(10, 11, 0) +def main(): + # Instantiate a AD8232 sensor on digital pins 10 (LO+), 11 (LO-) + # 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 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, including functions from myAD8232 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myAD8232 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Output the raw numbers from the ADC, for plotting elsewhere. + # 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) - -# Output the raw numbers from the ADC, for plotting elsewhere. -# 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) +if __name__ == '__main__': + main() diff --git a/examples/python/adafruitms1438-stepper.py b/examples/python/adafruitms1438-stepper.py old mode 100644 new mode 100755 index 5385951a..1f7f4679 --- a/examples/python/adafruitms1438-stepper.py +++ b/examples/python/adafruitms1438-stepper.py @@ -24,65 +24,65 @@ import time, sys, signal, atexit import pyupm_adafruitms1438 as upmAdafruitms1438 +def main(): + # Import header values + I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS + I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR -# Import header values -I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS -I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR + M12Motor = upmAdafruitms1438.AdafruitMS1438.STEPMOTOR_M12 + MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW + MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW -M12Motor = upmAdafruitms1438.AdafruitMS1438.STEPMOTOR_M12 -MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW -MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW + # Instantiate an Adafruit MS 1438 on I2C bus 0 + myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr) + ## 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 -myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr) + # This function lets you run code on exit, + # 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 ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # Setup for use with a stepper motor connected to the M1 & M2 ports -# This function lets you run code on exit, -# including functions from myMotorShield -def exitHandler(): - myMotorShield.disableStepper(M12Motor) - print "Exiting" - sys.exit(0) + # set a PWM period of 50Hz -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # disable first, to be safe + myMotorShield.disableStepper(M12Motor) + # 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 -myMotorShield.disableStepper(M12Motor) + print "Rotating 1 full revolution at 10 RPM speed." + myMotorShield.stepperSteps(M12Motor, 200) -# configure for a NEMA-17, 200 steps per revolution -myMotorShield.stepConfig(M12Motor, 200) + print "Sleeping for 2 seconds..." + time.sleep(2) + print "Rotating 1/2 revolution in opposite direction at 10 RPM speed." -# set speed at 10 RPM's -myMotorShield.setStepperSpeed(M12Motor, 10); -myMotorShield.setStepperDirection(M12Motor, MotorDirCW) + myMotorShield.setStepperDirection(M12Motor, MotorDirCCW) + myMotorShield.stepperSteps(M12Motor, 100) -# enable -print "Enabling..." -myMotorShield.enableStepper(M12Motor) + print "Disabling..." -print "Rotating 1 full revolution at 10 RPM speed." -myMotorShield.stepperSteps(M12Motor, 200) + # exitHandler runs automatically -print "Sleeping for 2 seconds..." -time.sleep(2) -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 +if __name__ == '__main__': + main() diff --git a/examples/python/adafruitms1438.py b/examples/python/adafruitms1438.py old mode 100644 new mode 100755 index 816bbe5d..7634c592 --- a/examples/python/adafruitms1438.py +++ b/examples/python/adafruitms1438.py @@ -24,60 +24,60 @@ import time, sys, signal, atexit import pyupm_adafruitms1438 as upmAdafruitms1438 +def main(): + # Import header values + I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS + I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR -# Import header values -I2CBus = upmAdafruitms1438.ADAFRUITMS1438_I2C_BUS -I2CAddr = upmAdafruitms1438.ADAFRUITMS1438_DEFAULT_I2C_ADDR + M3Motor = upmAdafruitms1438.AdafruitMS1438.MOTOR_M3 + MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW + MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW -M3Motor = upmAdafruitms1438.AdafruitMS1438.MOTOR_M3 -MotorDirCW = upmAdafruitms1438.AdafruitMS1438.DIR_CW -MotorDirCCW = upmAdafruitms1438.AdafruitMS1438.DIR_CCW + # Instantiate an Adafruit MS 1438 on I2C bus 0 + myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr) + ## 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 -myMotorShield = upmAdafruitms1438.AdafruitMS1438(I2CBus, I2CAddr) + # This function lets you run code on exit, + # 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 ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # Setup for use with a DC motor connected to the M3 port -# This function lets you run code on exit, -# including functions from myMotorShield -def exitHandler(): - myMotorShield.disableMotor(M3Motor) - print "Exiting" - sys.exit(0) + # set a PWM period of 50Hz + myMotorShield.setPWMPeriod(50) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # disable first, to be safe + myMotorShield.disableMotor(M3Motor) + # 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 -myMotorShield.setPWMPeriod(50) + time.sleep(3) -# disable first, to be safe -myMotorShield.disableMotor(M3Motor) + print "Reversing M3" + myMotorShield.setMotorDirection(M3Motor, MotorDirCCW) -# set speed at 50% -myMotorShield.setMotorSpeed(M3Motor, 50) -myMotorShield.setMotorDirection(M3Motor, MotorDirCW) + time.sleep(3) -print ("Spin M3 at half speed for 3 seconds, " -"then reverse for 3 seconds.") -myMotorShield.enableMotor(M3Motor) + print "Stopping M3" -time.sleep(3) + # exitHandler runs automatically -print "Reversing M3" -myMotorShield.setMotorDirection(M3Motor, MotorDirCCW) - -time.sleep(3) - -print "Stopping M3" - -# exitHandler runs automatically +if __name__ == '__main__': + main() diff --git a/examples/python/adc121c021.py b/examples/python/adc121c021.py old mode 100644 new mode 100755 index 61500c4a..383d4e0c --- a/examples/python/adc121c021.py +++ b/examples/python/adc121c021.py @@ -24,32 +24,34 @@ import time, sys, signal, atexit import pyupm_adc121c021 as upmAdc121c021 -# Instantiate an ADC121C021 on I2C bus 0 -busID = upmAdc121c021.ADC121C021_I2C_BUS -I2CAddr = upmAdc121c021.ADC121C021_DEFAULT_I2C_ADDR +def main(): + # Instantiate an ADC121C021 on I2C bus 0 + 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myAnalogDigitalConv + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myAnalogDigitalConv -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # get the data every 50 milliseconds + while(1): + val = myAnalogDigitalConv.value() + voltsVal = myAnalogDigitalConv.valueToVolts(val) + print "ADC value: %s Volts = %s" % (val, voltsVal) + time.sleep(.05) - -# get the data every 50 milliseconds -while(1): - val = myAnalogDigitalConv.value() - voltsVal = myAnalogDigitalConv.valueToVolts(val) - print "ADC value: %s Volts = %s" % (val, voltsVal) - time.sleep(.05) +if __name__ == '__main__': + main() diff --git a/examples/python/adxl335.py b/examples/python/adxl335.py old mode 100644 new mode 100755 index bc62181d..9cc4b6dd --- a/examples/python/adxl335.py +++ b/examples/python/adxl335.py @@ -24,55 +24,57 @@ import time, sys, signal, atexit 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 "Sleeping for 2 seconds" -time.sleep(2) + print "Please make sure the sensor is completely still." + print "Sleeping for 2 seconds" + 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 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, + # including functions from myAnalogAccel + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myAnalogAccel -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Calibrating..." + myAnalogAccel.calibrate() + x = upmAdxl335.new_intPointer() + y = upmAdxl335.new_intPointer() + z = upmAdxl335.new_intPointer() -print "Calibrating..." -myAnalogAccel.calibrate() + aX = upmAdxl335.new_floatPointer() + aY = upmAdxl335.new_floatPointer() + aZ = upmAdxl335.new_floatPointer() -x = upmAdxl335.new_intPointer() -y = upmAdxl335.new_intPointer() -z = upmAdxl335.new_intPointer() + while (1): + 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 -aX = upmAdxl335.new_floatPointer() -aY = upmAdxl335.new_floatPointer() -aZ = upmAdxl335.new_floatPointer() + myAnalogAccel.acceleration(aX, aY, aZ) + 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 -while (1): - 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 + print " " - myAnalogAccel.acceleration(aX, aY, aZ) - 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 + time.sleep(.2) - print " " - - time.sleep(.2) +if __name__ == '__main__': + main() diff --git a/examples/python/adxl345.py b/examples/python/adxl345.py old mode 100644 new mode 100755 index d19110ad..40bfab85 --- a/examples/python/adxl345.py +++ b/examples/python/adxl345.py @@ -23,19 +23,22 @@ from time import sleep import pyupm_adxl345 as adxl345 -# Create an I2C accelerometer object -adxl = adxl345.Adxl345(0) +def main(): + # Create an I2C accelerometer object + adxl = adxl345.Adxl345(0) -# Loop indefinitely -while True: + # Loop indefinitely + 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 - 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]) + # Sleep for 1 s + sleep(1) - # Sleep for 1 s - sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/adxrs610.py b/examples/python/adxrs610.py old mode 100644 new mode 100755 index 5183e7b2..d70a5161 --- a/examples/python/adxrs610.py +++ b/examples/python/adxrs610.py @@ -24,32 +24,36 @@ import time, sys, signal, atexit import pyupm_adxrs610 as sensorObj -# Instantiate a ADXRS610 sensor on analog pin A0 (dataout), and -# analog A1 (temp out) with an analog reference voltage of -# 5.0 -sensor = sensorObj.ADXRS610(0, 1, 5.0) +def main(): + # Instantiate a ADXRS610 sensor on analog pin A0 (dataout), and + # analog A1 (temp out) with an analog reference voltage of + # 5.0 + sensor = sensorObj.ADXRS610(0, 1, 5.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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# set a deadband region around the zero point to report 0.0 (optional) -sensor.setDeadband(0.015); + # set a deadband region around the zero point to report 0.0 (optional) + sensor.setDeadband(0.015); -# Every tenth of a second, sample the ADXRS610 and output it's -# corresponding temperature and angular velocity + # Every tenth of a second, sample the ADXRS610 and output it's + # corresponding temperature and angular velocity -while (1): + while (1): print "Vel (deg/s):", sensor.getAngularVelocity() print "Temp (C):", sensor.getTemperature() - time.sleep(.1) + time.sleep(.1) + +if __name__ == '__main__': + main() diff --git a/examples/python/aeotecdsb09104.py b/examples/python/aeotecdsb09104.py old mode 100644 new mode 100755 index 2ec9c319..2035ff94 --- a/examples/python/aeotecdsb09104.py +++ b/examples/python/aeotecdsb09104.py @@ -24,65 +24,50 @@ import time, sys, signal, atexit import pyupm_ozw as sensorObj -# This function lets you run code on exit -def exitHandler(): - print "Exiting" - sys.exit(0) +def main(): + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) + # Register exit handlers + atexit.register(exitHandler) -defaultDev = "/dev/ttyACM0" -if (len(sys.argv) > 1): + defaultDev = "/dev/ttyACM0" + if (len(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 -# will almost certainly need to change this to reflect your own -# network. Use the ozwdump example to see what nodes are available. -sensor = sensorObj.AeotecDSB09104(12) + # Instantiate an Aeotec DSB09104 instance, on device node 12. You + # will almost certainly need to change this to reflect your own + # network. Use the ozwdump example to see what nodes are available. + sensor = sensorObj.AeotecDSB09104(12) -# The first thing to do is create options, then lock them when done. -sensor.optionsCreate() -sensor.optionsLock() + # The first thing to do is create options, then lock them when done. + sensor.optionsCreate() + sensor.optionsLock() -# Next, initialize it. -print "Initializing, this may take awhile depending on your ZWave network" + # Next, initialize it. + print "Initializing, this may take awhile depending on your ZWave network" -sensor.init(defaultDev) -print "Initialization complete" + sensor.init(defaultDev) + print "Initialization complete" -print "Querying data..." + print "Querying data..." -while (True): + while (True): sensor.update() - print "Watts, Channel 1:", - print sensor.getWattsC1(), - print "W" + print "Watts, Channel 1: %0.03f W" % sensor.getWattsC1() + print "Watts, Channel 2: %0.03f W" % sensor.getWattsC2() + print "Watts, Channel 3: %0.03f W" % sensor.getWattsC3() - print "Watts, Channel 2:", - print sensor.getWattsC2(), - print "W" + print "Energy, Channel 1: %0.03f kWh" % sensor.getEnergyC1() + print "Energy, Channel 2: %0.03f kWh" % sensor.getEnergyC2() + print "Energy, Channel 3: %0.03f kWh" % sensor.getEnergyC3() - print "Watts, Channel 3:", - 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 + print "Battery Level: %d\n" % sensor.getBatteryLevel() time.sleep(3) + +if __name__ == '__main__': + main() diff --git a/examples/python/aeotecdw2e.py b/examples/python/aeotecdw2e.py old mode 100644 new mode 100755 index 35f16fe4..b16aeef9 --- a/examples/python/aeotecdw2e.py +++ b/examples/python/aeotecdw2e.py @@ -24,57 +24,59 @@ import time, sys, signal, atexit import pyupm_ozw as sensorObj -# This function lets you run code on exit -def exitHandler(): - print "Exiting" - sys.exit(0) +def main(): + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) + # Register exit handlers + atexit.register(exitHandler) -defaultDev = "/dev/ttyACM0" -if (len(sys.argv) > 1): + defaultDev = "/dev/ttyACM0" + if (len(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 -# device node 10. You will almost certainly need to change this to -# reflect your own network. Use the ozwdump example to see what nodes -# are available. -sensor = sensorObj.AeotecDW2E(10) + # Instantiate an Aeotec Door/Window 2nd Edition sensor instance, on + # device node 10. You will almost certainly need to change this to + # reflect your own network. Use the ozwdump example to see what nodes + # are available. + sensor = sensorObj.AeotecDW2E(10) -# The first thing to do is create options, then lock them when done. -sensor.optionsCreate() -sensor.optionsLock() + # The first thing to do is create options, then lock them when done. + sensor.optionsCreate() + sensor.optionsLock() -# Next, initialize it. -print "Initializing, this may take awhile depending on your ZWave network" + # Next, initialize it. + print "Initializing, this may take awhile depending on your ZWave network" -sensor.init(defaultDev) -print "Initialization complete" + sensor.init(defaultDev) + print "Initialization complete" -print "Querying data..." - -while (True): + print "Querying data..." + while (True): if (sensor.isDeviceAvailable()): - print "Alarm status:", - print sensor.isAlarmTripped() + print "Alarm status:", + print sensor.isAlarmTripped() - print "Tamper Switch status:", - print sensor.isTamperTripped() + print "Tamper Switch status:", + print sensor.isTamperTripped() - print "Battery Level:", - print sensor.getBatteryLevel(), - print "%" + print "Battery Level:", + print sensor.getBatteryLevel(), + print "%" - print + print else: - print "Device has not yet responded to probe." - print "Try waking it, or wait until it wakes itself if ", - print "configured to do so." - - print + print "Device has not yet responded to probe." + print "Try waking it, or wait until it wakes itself if ", + print "configured to do so." + print time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/aeotecsdg2.py b/examples/python/aeotecsdg2.py old mode 100644 new mode 100755 index 8c67ac96..e9be138a --- a/examples/python/aeotecsdg2.py +++ b/examples/python/aeotecsdg2.py @@ -24,51 +24,52 @@ import time, sys, signal, atexit import pyupm_ozw as sensorObj -# This function lets you run code on exit -def exitHandler(): +def main(): + # This function lets you run code on exit + def exitHandler(): print "Turning switch off and sleeping for 5 seconds..." sensor.off() time.sleep(5) - print "Exiting" - sys.exit(0) + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) + # Register exit handlers + atexit.register(exitHandler) -defaultDev = "/dev/ttyACM0" -if (len(sys.argv) > 1): + defaultDev = "/dev/ttyACM0" + if (len(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 -# 9. You will almost certainly need to change this to reflect your -# own network. Use the ozwdump example to see what nodes are -# available. -sensor = sensorObj.AeotecSDG2(9) + # Instantiate an Aeotec Smart Dimmer Gen2 instance, on device node + # 9. You will almost certainly need to change this to reflect your + # own network. Use the ozwdump example to see what nodes are + # available. + sensor = sensorObj.AeotecSDG2(9) -# The first thing to do is create options, then lock them when done. -sensor.optionsCreate() -sensor.optionsLock() + # The first thing to do is create options, then lock them when done. + sensor.optionsCreate() + sensor.optionsLock() -# Next, initialize it. -print "Initializing, this may take awhile depending on your ZWave network" + # Next, initialize it. + print "Initializing, this may take awhile depending on your ZWave network" -sensor.init(defaultDev) -print "Initialization complete" + sensor.init(defaultDev) + print "Initialization complete" -# turn light on -print "Turning switch on, then sleeping for 5 secs" -sensor.on(); -time.sleep(5); + # turn light on + print "Turning switch on, then sleeping for 5 secs" + sensor.on(); + time.sleep(5); -print "Querying data..." -dim = False; -while (True): + print "Querying data..." + dim = False; + while (True): # put on a light show... if (dim): - sensor.setLevel(25) + sensor.setLevel(25) else: - sensor.on() + sensor.on() dim = not dim; @@ -94,3 +95,6 @@ while (True): print time.sleep(5) + +if __name__ == '__main__': + main() diff --git a/examples/python/aeotecss6.py b/examples/python/aeotecss6.py old mode 100644 new mode 100755 index 70a3f0e4..3c6ec287 --- a/examples/python/aeotecss6.py +++ b/examples/python/aeotecss6.py @@ -24,45 +24,46 @@ import time, sys, signal, atexit import pyupm_ozw as sensorObj -# This function lets you run code on exit -def exitHandler(): +def main(): + # This function lets you run code on exit + def exitHandler(): print "Turning switch off and sleeping for 5 seconds..." sensor.off() time.sleep(5) - print "Exiting" - sys.exit(0) + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) + # Register exit handlers + atexit.register(exitHandler) -defaultDev = "/dev/ttyACM0" -if (len(sys.argv) > 1): + defaultDev = "/dev/ttyACM0" + if (len(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. -# You will almost certainly need to change this to reflect your own -# network. Use the ozwdump example to see what nodes are available. -sensor = sensorObj.AeotecSS6(11) + # Instantiate an Aeotec Smart Switch 6 instance, on device node 11. + # You will almost certainly need to change this to reflect your own + # network. Use the ozwdump example to see what nodes are available. + sensor = sensorObj.AeotecSS6(11) -# The first thing to do is create options, then lock them when done. -sensor.optionsCreate() -sensor.optionsLock() + # The first thing to do is create options, then lock them when done. + sensor.optionsCreate() + sensor.optionsLock() -# Next, initialize it. -print "Initializing, this may take awhile depending on your ZWave network" + # Next, initialize it. + print "Initializing, this may take awhile depending on your ZWave network" -sensor.init(defaultDev) -print "Initialization complete" + sensor.init(defaultDev) + print "Initialization complete" -# turn light on -print "Turning switch on, then sleeping for 5 secs" -sensor.on(); -time.sleep(5); + # turn light on + print "Turning switch on, then sleeping for 5 secs" + sensor.on(); + time.sleep(5); -print "Querying data..." + print "Querying data..." -while (True): + while (True): sensor.update() print "Switch status:", @@ -85,3 +86,6 @@ while (True): print time.sleep(3) + +if __name__ == '__main__': + main() diff --git a/examples/python/ak8975.py b/examples/python/ak8975.py old mode 100644 new mode 100755 index ad19df9f..69cd7b90 --- a/examples/python/ak8975.py +++ b/examples/python/ak8975.py @@ -24,36 +24,40 @@ import time, sys, signal, atexit import pyupm_mpu9150 as sensorObj -# Instantiate an AK8975 on I2C bus 0 -sensor = sensorObj.AK8975() +def main(): + # Instantiate an AK8975 on I2C bus 0 + sensor = sensorObj.AK8975() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -sensor.init() + sensor.init() -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() 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 " MZ: ", sensorObj.floatp_value(z) print - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/apa102.py b/examples/python/apa102.py old mode 100644 new mode 100755 index 721d4d42..9cddb959 --- a/examples/python/apa102.py +++ b/examples/python/apa102.py @@ -21,28 +21,29 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_apa102 as mylib -# Instantiate a strip of 30 LEDs on SPI bus 0 -ledStrip = mylib.APA102(30, 0, False) +def main(): + # Instantiate a strip of 30 LEDs on SPI bus 0 + ledStrip = mylib.APA102(30, 0, False) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# Register exit handlers -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + signal.signal(signal.SIGINT, SIGINTHandler) -print "Setting all LEDs to Green" -ledStrip.setAllLeds(31, 0, 255, 0) + print "Setting all LEDs to Green" + ledStrip.setAllLeds(31, 0, 255, 0) -print "Setting LEDs between 10 and 20 to Red" -ledStrip.setLeds(10, 20, 31, 255, 0, 0) - -print "Setting LED 15 to Blue" -ledStrip.setLed(15, 31, 0, 0, 255) + print "Setting LEDs between 10 and 20 to Red" + ledStrip.setLeds(10, 20, 31, 255, 0, 0) + print "Setting LED 15 to Blue" + ledStrip.setLed(15, 31, 0, 0, 255) +if __name__ == '__main__': + main() diff --git a/examples/python/apds9002.py b/examples/python/apds9002.py old mode 100644 new mode 100755 index f9ea3cb9..04bf3ecd --- a/examples/python/apds9002.py +++ b/examples/python/apds9002.py @@ -24,27 +24,29 @@ import time, sys, signal, atexit import pyupm_apds9002 as upmApds9002 -# Instantiate a Grove Luminance sensor on analog pin A0 -myLuminance = upmApds9002.APDS9002(0) +def main(): + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myLuminance + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myLuminance -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + print "Luminance value is {0}".format( + myLuminance.value()) + time.sleep(1) -while(1): - print "Luminance value is {0}".format( - myLuminance.value()) - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/at42qt1070.py b/examples/python/at42qt1070.py old mode 100644 new mode 100755 index 06addfe9..21045004 --- a/examples/python/at42qt1070.py +++ b/examples/python/at42qt1070.py @@ -24,56 +24,56 @@ import time, sys, signal, atexit import pyupm_at42qt1070 as upmAt42qt1070 -# functions -def printButtons(touchObj): - buttonPressed = False - buttons = touchObj.getButtons() +def main(): + # functions + def printButtons(touchObj): + buttonPressed = False + buttons = touchObj.getButtons() - sys.stdout.write("Buttons Pressed: ") - for i in range(7): - if (buttons & (1 << i)): - sys.stdout.write(str(i) + " ") - buttonPressed = True + sys.stdout.write("Buttons Pressed: ") + for i in range(7): + if (buttons & (1 << i)): + sys.stdout.write(str(i) + " ") + buttonPressed = True - if (not buttonPressed): - sys.stdout.write("None") + if (not buttonPressed): + sys.stdout.write("None") - print " " + print " " - if (touchObj.isCalibrating()): - print "Calibration is occurring." + if (touchObj.isCalibrating()): + print "Calibration is occurring." - if (touchObj.isOverflowed()): - print "Overflow was detected." + if (touchObj.isOverflowed()): + 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 -DEFAULT_I2C_ADDR = upmAt42qt1070.AT42QT1070_DEFAULT_I2C_ADDR + # Instantiate an AT42QT1070 on I2C bus 0 + myTouchSensor = upmAt42qt1070.AT42QT1070(I2C_BUS, + DEFAULT_I2C_ADDR) -# Instantiate an AT42QT1070 on I2C bus 0 -myTouchSensor = upmAt42qt1070.AT42QT1070(I2C_BUS, - DEFAULT_I2C_ADDR) + # Exit handlers + def SIGINTHandler(signum, frame): + raise SystemExit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Exit handlers -def SIGINTHandler(signum, frame): - raise SystemExit + # This function lets you run code on exit, including functions from myTouchSensor + atexit.register(exitHandler) + # This function stops python from printing a stacktrace when you hit control-C + signal.signal(signal.SIGINT, SIGINTHandler) -def exitHandler(): - print "Exiting" - sys.exit(0) + # Print the button being touched every 0.1 seconds + while(1): + myTouchSensor.updateState() + printButtons(myTouchSensor) + time.sleep(.1) - -# This function lets you run code on exit, including functions from myTouchSensor -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) +if __name__ == '__main__': + main() diff --git a/examples/python/bh1750.py b/examples/python/bh1750.py old mode 100644 new mode 100755 index ca680e98..2ab1a354 --- a/examples/python/bh1750.py +++ b/examples/python/bh1750.py @@ -24,27 +24,31 @@ import time, sys, signal, atexit import pyupm_bh1750 as sensorObj -# Instantiate a BH1750 sensor using defaults (I2C bus (0), using -# the default I2C address (0x23), and setting the mode to highest -# resolution, lowest power mode). -sensor = sensorObj.BH1750() +def main(): + # Instantiate a BH1750 sensor using defaults (I2C bus (0), using + # the default I2C address (0x23), and setting the mode to highest + # resolution, lowest power mode). + sensor = sensorObj.BH1750() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + 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() - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/biss0001.py b/examples/python/biss0001.py old mode 100644 new mode 100755 index ba8901d0..6ab7a0f2 --- a/examples/python/biss0001.py +++ b/examples/python/biss0001.py @@ -24,29 +24,31 @@ import time, sys, signal, atexit import pyupm_biss0001 as upmMotion -# Instantiate a Grove Motion sensor on GPIO pin D2 -myMotion = upmMotion.BISS0001(2) +def main(): + # 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 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, including functions from myMotion + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMotion -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Read the value every second and detect motion + while(1): + if (myMotion.value()): + print "Detecting moving object" + else: + print "No moving objects detected" + time.sleep(1) - -# Read the value every second and detect motion -while(1): - if (myMotion.value()): - print "Detecting moving object" - else: - print "No moving objects detected" - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/bma220.py b/examples/python/bma220.py old mode 100644 new mode 100755 index 9db6cdfd..bd725ddf --- a/examples/python/bma220.py +++ b/examples/python/bma220.py @@ -24,32 +24,36 @@ import time, sys, signal, atexit import pyupm_bma220 as sensorObj -# Instantiate an BMA220 using default parameters (bus 0, addr 0x0a) -sensor = sensorObj.BMA220() +def main(): + # Instantiate an BMA220 using default parameters (bus 0, addr 0x0a) + sensor = sensorObj.BMA220() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() 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 " AZ:", sensorObj.floatp_value(z) - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/bma250e.py b/examples/python/bma250e.py old mode 100644 new mode 100755 index 051273c2..8c83f29a --- a/examples/python/bma250e.py +++ b/examples/python/bma250e.py @@ -24,32 +24,33 @@ import time, sys, signal, atexit import pyupm_bmx055 as sensorObj -# Instantiate a BMP250E instance using default i2c bus and address -sensor = sensorObj.BMA250E() +def main(): + # 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: -# BMA250E(0, -1, 10); + # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: + # BMA250E(0, -1, 10); -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# now output data every 250 milliseconds -while (1): + # now output data every 250 milliseconds + while (1): sensor.update() sensor.getAccelerometer(x, y, z) @@ -63,4 +64,7 @@ while (1): print sensor.getTemperature(True), "F" print - time.sleep(.250) + time.sleep(.250) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmc150.py b/examples/python/bmc150.py old mode 100644 new mode 100755 index efb1d99e..58be6de8 --- a/examples/python/bmc150.py +++ b/examples/python/bmc150.py @@ -24,29 +24,30 @@ import time, sys, signal, atexit import pyupm_bmx055 as sensorObj -# Instantiate a BMC150 instance using default i2c bus and address -sensor = sensorObj.BMC150() +def main(): + # Instantiate a BMC150 instance using default i2c bus and address + sensor = sensorObj.BMC150() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# now output data every 250 milliseconds -while (1): + # now output data every 250 milliseconds + while (1): sensor.update() sensor.getAccelerometer(x, y, z) @@ -62,4 +63,7 @@ while (1): print " uT" print - time.sleep(.250) + time.sleep(.250) + +if __name__ == '__main__': + main() diff --git a/examples/python/bme280.py b/examples/python/bme280.py old mode 100644 new mode 100755 index 160a95a4..f2fdee74 --- a/examples/python/bme280.py +++ b/examples/python/bme280.py @@ -24,27 +24,28 @@ import time, sys, signal, atexit import pyupm_bmp280 as sensorObj -# Instantiate a BME280 instance using default i2c bus and address -sensor = sensorObj.BME280() +def main(): + # 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: -# BME280(0, -1, 10); + # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: + # BME280(0, -1, 10); -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -while (1): + while (1): sensor.update() print "Compensation Temperature:", sensor.getTemperature(), "C /", @@ -57,4 +58,7 @@ while (1): print "Humidity:", sensor.getHumidity(), "%RH" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmg160.py b/examples/python/bmg160.py old mode 100644 new mode 100755 index 112e3d68..c197964d --- a/examples/python/bmg160.py +++ b/examples/python/bmg160.py @@ -24,32 +24,33 @@ import time, sys, signal, atexit import pyupm_bmx055 as sensorObj -# Instantiate a BMP250E instance using default i2c bus and address -sensor = sensorObj.BMG160() +def main(): + # 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: -# BMG160(0, -1, 10); + # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: + # BMG160(0, -1, 10); -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# now output data every 250 milliseconds -while (1): + # now output data every 250 milliseconds + while (1): sensor.update() sensor.getGyroscope(x, y, z) @@ -63,4 +64,7 @@ while (1): print sensor.getTemperature(True), "F" print - time.sleep(.250) + time.sleep(.250) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmi055.py b/examples/python/bmi055.py old mode 100644 new mode 100755 index 96ddac29..5bad7d6f --- a/examples/python/bmi055.py +++ b/examples/python/bmi055.py @@ -24,29 +24,30 @@ import time, sys, signal, atexit import pyupm_bmx055 as sensorObj -# Instantiate a BMI055 instance using default i2c bus and address -sensor = sensorObj.BMI055() +def main(): + # Instantiate a BMI055 instance using default i2c bus and address + sensor = sensorObj.BMI055() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# now output data every 250 milliseconds -while (1): + # now output data every 250 milliseconds + while (1): sensor.update() sensor.getAccelerometer(x, y, z) @@ -62,4 +63,7 @@ while (1): print " degrees/s" print - time.sleep(.250) + time.sleep(.250) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmi160.py b/examples/python/bmi160.py old mode 100644 new mode 100755 index f7e7aa16..4514dc1d --- a/examples/python/bmi160.py +++ b/examples/python/bmi160.py @@ -24,28 +24,29 @@ import time, sys, signal, atexit import pyupm_bmi160 as sensorObj -# Instantiate a BMI160 instance using default i2c bus and address -sensor = sensorObj.BMI160() +def main(): + # Instantiate a BMI160 instance using default i2c bus and address + sensor = sensorObj.BMI160() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() sensor.getAccelerometer(x, y, z) print "Accelerometer: AX: ", sensorObj.floatp_value(x), @@ -63,4 +64,7 @@ while (1): print " MZ: ", sensorObj.floatp_value(z) print - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmm150.py b/examples/python/bmm150.py old mode 100644 new mode 100755 index 69f36bf3..f6435a34 --- a/examples/python/bmm150.py +++ b/examples/python/bmm150.py @@ -24,32 +24,33 @@ import time, sys, signal, atexit import pyupm_bmx055 as sensorObj -# Instantiate a BMP250E instance using default i2c bus and address -sensor = sensorObj.BMM150() +def main(): + # 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: -# BMM150(0, -1, 10); + # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: + # BMM150(0, -1, 10); -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# now output data every 250 milliseconds -while (1): + # now output data every 250 milliseconds + while (1): sensor.update() sensor.getMagnetometer(x, y, z) @@ -59,4 +60,7 @@ while (1): print " uT" print - time.sleep(.250) + time.sleep(.250) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmp280.py b/examples/python/bmp280.py old mode 100644 new mode 100755 index 899e0a8e..94758f7d --- a/examples/python/bmp280.py +++ b/examples/python/bmp280.py @@ -24,27 +24,28 @@ import time, sys, signal, atexit import pyupm_bmp280 as sensorObj -# Instantiate a BMP280 instance using default i2c bus and address -sensor = sensorObj.BMP280() +def main(): + # 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: -# BMP280(0, -1, 10); + # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: + # BMP280(0, -1, 10); -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -while (1): + while (1): sensor.update() print "Compensation Temperature:", sensor.getTemperature(), "C /", @@ -55,4 +56,7 @@ while (1): print "Computed Altitude:", sensor.getAltitude(), "m" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/bmpx8x.py b/examples/python/bmpx8x.py old mode 100644 new mode 100755 index 017fba5b..81bdd620 --- a/examples/python/bmpx8x.py +++ b/examples/python/bmpx8x.py @@ -24,36 +24,38 @@ import time, sys, signal, atexit import pyupm_bmpx8x as upmBmpx8x -# Load Barometer module on i2c -myBarometer = upmBmpx8x.BMPX8X(0, upmBmpx8x.ADDR); +def main(): + # 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 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, including functions from myBarometer + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myBarometer -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Print the pressure, altitude, sea level, and + # temperature values every 0.1 seconds + 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 -# temperature values every 0.1 seconds -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) +if __name__ == '__main__': + main() diff --git a/examples/python/bmx055.py b/examples/python/bmx055.py old mode 100644 new mode 100755 index 45012cfb..05b33677 --- a/examples/python/bmx055.py +++ b/examples/python/bmx055.py @@ -24,29 +24,30 @@ import time, sys, signal, atexit import pyupm_bmx055 as sensorObj -# Instantiate a BMX055 instance using default i2c bus and address -sensor = sensorObj.BMX055() +def main(): + # Instantiate a BMX055 instance using default i2c bus and address + sensor = sensorObj.BMX055() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# now output data every 250 milliseconds -while (1): + # now output data every 250 milliseconds + while (1): sensor.update() sensor.getAccelerometer(x, y, z) @@ -68,4 +69,7 @@ while (1): print " uT" print - time.sleep(.250) + time.sleep(.250) + +if __name__ == '__main__': + main() diff --git a/examples/python/bno055.py b/examples/python/bno055.py old mode 100644 new mode 100755 index 6e5a500a..14c2df53 --- a/examples/python/bno055.py +++ b/examples/python/bno055.py @@ -24,57 +24,58 @@ import time, sys, signal, atexit import pyupm_bno055 as sensorObj -# Instantiate an BNO055 using default parameters (bus 0, addr -# 0x28). The default running mode is NDOF absolute orientation -# mode. -sensor = sensorObj.BNO055() +def main(): + # Instantiate an BNO055 using default parameters (bus 0, addr + # 0x28). The default running mode is NDOF absolute orientation + # mode. + sensor = sensorObj.BNO055() -## 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 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -mag = sensorObj.new_intp() -acc = sensorObj.new_intp() -gyr = sensorObj.new_intp() -syst = sensorObj.new_intp() + mag = sensorObj.new_intp() + acc = sensorObj.new_intp() + gyr = sensorObj.new_intp() + syst = sensorObj.new_intp() -w = sensorObj.new_floatp() -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + w = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -print "First we need to calibrate. 4 numbers will be output every" -print "second for each sensor. 0 means uncalibrated, and 3 means" -print "fully calibrated." -print "See the UPM documentation on this sensor for instructions on" -print "what actions are required to calibrate." -print + print "First we need to calibrate. 4 numbers will be output every" + print "second for each sensor. 0 means uncalibrated, and 3 means" + print "fully calibrated." + print "See the UPM documentation on this sensor for instructions on" + print "what actions are required to calibrate." + print -while (not sensor.isFullyCalibrated()): + while (not sensor.isFullyCalibrated()): sensor.getCalibrationStatus(mag, acc, gyr, syst) print "Magnetometer:", sensorObj.intp_value(mag), print " Accelerometer:", sensorObj.intp_value(acc), print " Gyroscope:", sensorObj.intp_value(gyr), print " System:", sensorObj.intp_value(syst), - time.sleep(1) + time.sleep(1) -print -print "Calibration complete." -print + print + print "Calibration complete." + print -# now output various fusion data every 250 milliseconds + # now output various fusion data every 250 milliseconds -while (True): + while (True): sensor.update() sensor.getEulerAngles(x, y, z) @@ -103,3 +104,6 @@ while (True): print time.sleep(.25); + +if __name__ == '__main__': + main() diff --git a/examples/python/button.py b/examples/python/button.py old mode 100644 new mode 100755 index eaac3eee..44f8149e --- a/examples/python/button.py +++ b/examples/python/button.py @@ -23,13 +23,17 @@ import time import pyupm_grove as grove -# Create the button object using GPIO pin 0 -button = grove.Button(0) +def main(): + # Create the button object using GPIO pin 0 + button = grove.Button(0) -# Read the input and print, waiting one second between readings -while 1: - print button.name(), ' value is ', button.value() - time.sleep(1) + # Read the input and print, waiting one second between readings + while 1: + print button.name(), ' value is ', button.value() + time.sleep(1) -# Delete the button object -del button + # Delete the button object + del button + +if __name__ == '__main__': + main() diff --git a/examples/python/buzzer.py b/examples/python/buzzer.py old mode 100644 new mode 100755 index b1a3d18b..0e220119 --- a/examples/python/buzzer.py +++ b/examples/python/buzzer.py @@ -23,23 +23,27 @@ import time import pyupm_buzzer as upmBuzzer -# Create the buzzer object using GPIO pin 5 -buzzer = upmBuzzer.Buzzer(5) +def main(): + # Create the buzzer object using GPIO pin 5 + buzzer = upmBuzzer.Buzzer(5) -chords = [upmBuzzer.DO, upmBuzzer.RE, upmBuzzer.MI, upmBuzzer.FA, - upmBuzzer.SOL, upmBuzzer.LA, upmBuzzer.SI, upmBuzzer.DO, - upmBuzzer.SI]; + chords = [upmBuzzer.DO, upmBuzzer.RE, upmBuzzer.MI, upmBuzzer.FA, + upmBuzzer.SOL, upmBuzzer.LA, upmBuzzer.SI, upmBuzzer.DO, + upmBuzzer.SI]; -# Print sensor name -print buzzer.name() + # Print sensor name + print buzzer.name() -# Play sound (DO, RE, MI, etc.), pausing for 0.1 seconds between notes -for chord_ind in range (0,7): - # play each note for one second - print buzzer.playSound(chords[chord_ind], 1000000) - time.sleep(0.1) + # Play sound (DO, RE, MI, etc.), pausing for 0.1 seconds between notes + for chord_ind in range (0,7): + # play each note for one second + print buzzer.playSound(chords[chord_ind], 1000000) + time.sleep(0.1) -print "exiting application" + print "exiting application" -# Delete the buzzer object -del buzzer + # Delete the buzzer object + del buzzer + +if __name__ == '__main__': + main() diff --git a/examples/python/cjq4435.py b/examples/python/cjq4435.py old mode 100644 new mode 100755 index a4ed268f..487035a7 --- a/examples/python/cjq4435.py +++ b/examples/python/cjq4435.py @@ -25,22 +25,25 @@ from __future__ import division import time import pyupm_cjq4435 as upmCjq4435 -# Instantiate a CJQ4435 MOSFET on a PWM capable digital pin D3 -myMOSFETsensor = upmCjq4435.CJQ4435(3) +def main(): + # Instantiate a CJQ4435 MOSFET on a PWM capable digital pin D3 + myMOSFETsensor = upmCjq4435.CJQ4435(3) + myMOSFETsensor.setPeriodMS(10) + myMOSFETsensor.enable(True) -myMOSFETsensor.setPeriodMS(10) -myMOSFETsensor.enable(True) + # start with a duty cycle of 0.0 (off) and increment to 1.0 (on) + 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) -for i in range(11): - myMOSFETsensor.setDutyCycle(i / 10) - time.sleep(.1) -time.sleep(1) + # Now take it back down + # start with a duty cycle of 1.0 (on) and decrement to 0.0 (off) + for i in range(10, -1, -1): + myMOSFETsensor.setDutyCycle(i / 10) + time.sleep(.1) + time.sleep(1) -# Now take it back down -# start with a duty cycle of 1.0 (on) and decrement to 0.0 (off) -for i in range(10, -1, -1): - myMOSFETsensor.setDutyCycle(i / 10) - time.sleep(.1) -time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/collision.py b/examples/python/collision.py old mode 100644 new mode 100755 index 463aba9b..ed9bac7e --- a/examples/python/collision.py +++ b/examples/python/collision.py @@ -24,34 +24,36 @@ import time, sys, signal, atexit import pyupm_collision as upmcollision -# The was tested with the Collision Sensor -# Instantiate a Collision on digital pin D2 -mycollision = upmcollision.Collision(2) +def main(): + # The was tested with the Collision Sensor + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myGrovecollision + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myGrovecollision -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + collisionState = False + print "No collision" + 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 -print "No collision" - -while(1): - if (mycollision.isColliding() and not collisionState): - print "Collision!" - collisionState = True - elif (not mycollision.isColliding() and collisionState): - print "No collision" - collisionState = False +if __name__ == '__main__': + main() diff --git a/examples/python/curieimu.py b/examples/python/curieimu.py old mode 100644 new mode 100755 index 8596fef1..26b4473e --- a/examples/python/curieimu.py +++ b/examples/python/curieimu.py @@ -30,27 +30,31 @@ mraa.addSubplatform(mraa.GENERIC_FIRMATA, "/dev/ttyACM0") import time, sys, signal, atexit import pyupm_curieimu as curieimu -sensor = curieimu.CurieImu() -## Exit handlers ## -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + sensor = curieimu.CurieImu() -def exitHandler(): - print "Exiting" - sys.exit(0) + ## Exit handlers ## + def SIGINTHandler(signum, frame): + raise SystemExit -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + def exitHandler(): + print "Exiting" + sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -while(1): - sensor.updateAccel(); + while(1): + sensor.updateAccel(); - outputStr = "acc: gX {0} - gY {1} - gZ {2}".format( - sensor.getAccelX(), sensor.getAccelY(), - sensor.getAccelZ()) - print outputStr + outputStr = "acc: gX {0} - gY {1} - gZ {2}".format( + sensor.getAccelX(), sensor.getAccelY(), + sensor.getAccelZ()) + print outputStr - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/cwlsxxa.py b/examples/python/cwlsxxa.py old mode 100644 new mode 100755 index da73416a..39477f81 --- a/examples/python/cwlsxxa.py +++ b/examples/python/cwlsxxa.py @@ -24,28 +24,29 @@ import time, sys, signal, atexit import pyupm_cwlsxxa as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Initializing..." + print "Initializing..." -# Instantiate an CWLSXXA instance, using A0 for CO2, A1 for -# humidity and A2 for temperature -sensor = sensorObj.CWLSXXA(0, 1, 2) + # Instantiate an CWLSXXA instance, using A0 for CO2, A1 for + # humidity and A2 for temperature + sensor = sensorObj.CWLSXXA(0, 1, 2) -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() @@ -58,4 +59,7 @@ while (1): print "CO2:", sensor.getCO2(), "ppm" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/dfrec.py b/examples/python/dfrec.py old mode 100644 new mode 100755 index 6b2d48d9..23cb756e --- a/examples/python/dfrec.py +++ b/examples/python/dfrec.py @@ -24,28 +24,29 @@ import time, sys, signal, atexit import pyupm_dfrec as sensorObj -# Instantiate a DFRobot EC sensor on analog pin A0, with a ds18b20 -# temperature sensor connected to UART 0, and a device index (for -# the ds1820b uart bus) of 0, and an analog reference voltage of -# 5.0. -sensor = sensorObj.DFREC(0, 0, 0, 5.0) +def main(): + # Instantiate a DFRobot EC sensor on analog pin A0, with a ds18b20 + # temperature sensor connected to UART 0, and a device index (for + # the ds1820b uart bus) of 0, and an analog reference voltage of + # 5.0. + sensor = sensorObj.DFREC(0, 0, 0, 5.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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every 2 seconds, update and print values -while (True): + # Every 2 seconds, update and print values + while (True): sensor.update() print "EC =", sensor.getEC(), "ms/cm" @@ -53,4 +54,7 @@ while (True): print ", Temperature = ", sensor.getTemperature(), "C" print - time.sleep(2) + time.sleep(2) + +if __name__ == '__main__': + main() diff --git a/examples/python/dfrorp.py b/examples/python/dfrorp.py old mode 100644 new mode 100755 index 89d0a12e..c536dc9c --- a/examples/python/dfrorp.py +++ b/examples/python/dfrorp.py @@ -24,45 +24,49 @@ import time, sys, signal, atexit import pyupm_dfrorp as sensorObj -# Instantiate a DFRobot ORP sensor on analog pin A0 with an analog -# reference voltage of 5.0. -sensor = sensorObj.DFRORP(0, 5.0) +def main(): + # Instantiate a DFRobot ORP sensor on analog pin A0 with an analog + # reference voltage of 5.0. + sensor = sensorObj.DFRORP(0, 5.0) -# To calibrate: -# -# Disconnect the sensor probe (but leave the sensor interface board -# connected). Then run one of the examples while holding down the -# 'calibrate' button on the device. Read the ORP value reported -# (it should be fairly small). -# -# This value is what you should supply to setCalibrationOffset(). -# Then reconnect the probe to the interface board and you should be -# ready to go. -# -# DO NOT press the calibrate button on the interface board while -# the probe is attached or you can permanently damage the probe. -sensor.setCalibrationOffset(0.97); + # To calibrate: + # + # Disconnect the sensor probe (but leave the sensor interface board + # connected). Then run one of the examples while holding down the + # 'calibrate' button on the device. Read the ORP value reported + # (it should be fairly small). + # + # This value is what you should supply to setCalibrationOffset(). + # Then reconnect the probe to the interface board and you should be + # ready to go. + # + # DO NOT press the calibrate button on the interface board while + # the probe is attached or you can permanently damage the probe. + sensor.setCalibrationOffset(0.97); -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every second, update and print values -while (True): + # Every second, update and print values + while (True): sensor.update() print "ORP:", sensor.getORP(), "mV" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/dfrph.py b/examples/python/dfrph.py old mode 100644 new mode 100755 index 1fadf039..33184a7a --- a/examples/python/dfrph.py +++ b/examples/python/dfrph.py @@ -24,33 +24,37 @@ import time, sys, signal, atexit import pyupm_dfrph as sensorObj -# Instantiate a DFRPH sensor on analog pin A0, with an analog -# reference voltage of 5.0 -sensor = sensorObj.DFRPH(0, 5.0) +def main(): + # Instantiate a DFRPH sensor on analog pin A0, with an analog + # reference voltage of 5.0 + sensor = sensorObj.DFRPH(0, 5.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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# After calibration, set the offset (based on calibration with a pH -# 7.0 buffer solution). See the UPM sensor documentation for -# calibrations instructions. -sensor.setOffset(0.065); + # After calibration, set the offset (based on calibration with a pH + # 7.0 buffer solution). See the UPM sensor documentation for + # calibrations instructions. + sensor.setOffset(0.065); -# Every second, sample the pH and output it's corresponding -# analog voltage. + # Every second, sample the pH and output it's corresponding + # analog voltage. -while (1): + while (1): print "Detected volts: ", sensor.volts() print "pH value: ", sensor.pH() - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/ds1307.py b/examples/python/ds1307.py old mode 100644 new mode 100755 index 7d35d8ec..f7c057b6 --- a/examples/python/ds1307.py +++ b/examples/python/ds1307.py @@ -24,37 +24,40 @@ import time, sys, signal, atexit import pyupm_ds1307 as upmDs1307 -# load RTC clock on i2c bus 0 -myRTCClock = upmDs1307.DS1307(0) +def main(): + # load RTC clock on i2c bus 0 + myRTCClock = upmDs1307.DS1307(0) -def printTime(RTCObj): - timeStr = "The time is: {0}/{1}/{2} {3}:{4}:{5}".format( - RTCObj.month, RTCObj.dayOfMonth, RTCObj.year, - RTCObj.hours, RTCObj.minutes, RTCObj.seconds) + def printTime(RTCObj): + timeStr = "The time is: {0}/{1}/{2} {3}:{4}:{5}".format( + RTCObj.month, RTCObj.dayOfMonth, RTCObj.year, + RTCObj.hours, RTCObj.minutes, RTCObj.seconds) - if (RTCObj.amPmMode): - timeStr += (" PM " if RTCObj.pm else " AM ") + if (RTCObj.amPmMode): + timeStr += (" PM " if RTCObj.pm else " AM ") - print timeStr + print timeStr - print "Clock is in", ("AM/PM mode" - if RTCObj.amPmMode else "24hr mode") + print "Clock is in", ("AM/PM 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 -print "Loading the current time... " -result = myRTCClock.loadTime() -if (not result): - print "myRTCClock.loadTime() failed." - sys.exit(0) + printTime(myRTCClock); -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 -print "setting the year to 50" -myRTCClock.year = 50 -myRTCClock.setTime() + # reload the time and print it + myRTCClock.loadTime() + printTime(myRTCClock) -# reload the time and print it -myRTCClock.loadTime() -printTime(myRTCClock) +if __name__ == '__main__': + main() diff --git a/examples/python/ds18b20.py b/examples/python/ds18b20.py old mode 100644 new mode 100755 index d91d33c8..f4847525 --- a/examples/python/ds18b20.py +++ b/examples/python/ds18b20.py @@ -24,36 +24,37 @@ import time, sys, signal, atexit import pyupm_ds18b20 as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Initializing..." + print "Initializing..." -# Instantiate an DS18B20 instance using the default values (uart 0) -sensor = sensorObj.DS18B20(0) + # Instantiate an DS18B20 instance using the default values (uart 0) + sensor = sensorObj.DS18B20(0) -# locate and setup our devices -sensor.init() + # locate and setup our devices + sensor.init() -print "Found", sensor.devicesFound(), "device(s)" -print + print "Found", sensor.devicesFound(), "device(s)" + print -if (not sensor.devicesFound()): + if (not sensor.devicesFound()): sys.exit(1); -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values for the first sensor sensor.update(0) @@ -61,4 +62,7 @@ while (1): print "Temperature:", sensor.getTemperature(0), "C /", print sensor.getTemperature(0, True), "F" - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/ds2413.py b/examples/python/ds2413.py old mode 100644 new mode 100755 index 2dc95d83..d72ae3ac --- a/examples/python/ds2413.py +++ b/examples/python/ds2413.py @@ -24,34 +24,38 @@ import time, sys, signal, atexit import pyupm_ds2413 as sensorObj -# Instantiate a DS2413 Module on a Dallas 1-wire bus connected to UART 0 -sensor = sensorObj.DS2413(0) +def main(): + # Instantiate a DS2413 Module on a Dallas 1-wire bus connected to UART 0 + sensor = sensorObj.DS2413(0) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# find all of the DS2413 devices present on the bus -sensor.init(); + # find all of the DS2413 devices present on the bus + sensor.init(); -# how many devices were found? -print "Found", sensor.devicesFound(), "device(s)" + # how many devices were found? + print "Found", sensor.devicesFound(), "device(s)" -# read the gpio and latch values from the first device -# the lower 4 bits are of the form: -# -print "GPIO device 0 values:", sensor.readGpios(0) + # read the gpio and latch values from the first device + # the lower 4 bits are of the form: + # + print "GPIO device 0 values:", sensor.readGpios(0) -# set the gpio latch values of the first device -print "Setting GPIO latches to on" -sensor.writeGpios(0, 0x03); + # set the gpio latch values of the first device + print "Setting GPIO latches to on" + sensor.writeGpios(0, 0x03); + +if __name__ == '__main__': + main() diff --git a/examples/python/e50hx.py b/examples/python/e50hx.py old mode 100644 new mode 100755 index a2910015..e96c7829 --- a/examples/python/e50hx.py +++ b/examples/python/e50hx.py @@ -24,57 +24,58 @@ import time, sys, signal, atexit import pyupm_e50hx as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# You will need to edit this example to conform to your site and your -# devices, specifically the Device Object Instance ID passed to the -# constructor, and the arguments to initMaster() that are -# appropriate for your BACnet network. + # You will need to edit this example to conform to your site and your + # devices, specifically the Device Object Instance ID passed to the + # constructor, and the arguments to initMaster() that are + # appropriate for your BACnet network. -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an E50HX object for an E50HX device that has 1075425 -# as it's unique Device Object Instance ID. NOTE: You will -# certainly want to change this to the correct value for your -# device(s). -sensor = sensorObj.E50HX(1075425) + # Instantiate an E50HX object for an E50HX device that has 1075425 + # as it's unique Device Object Instance ID. NOTE: You will + # certainly want to change this to the correct value for your + # device(s). + sensor = sensorObj.E50HX(1075425) -# Initialize our BACnet master, if it has not already been -# initialized, with the device and baudrate, choosing 1000001 as -# our unique Device Object Instance ID, 2 as our MAC address and -# using default values for maxMaster and maxInfoFrames -sensor.initMaster(defaultDev, 38400, 1000001, 2) + # Initialize our BACnet master, if it has not already been + # initialized, with the device and baudrate, choosing 1000001 as + # our unique Device Object Instance ID, 2 as our MAC address and + # using default values for maxMaster and maxInfoFrames + sensor.initMaster(defaultDev, 38400, 1000001, 2) -# Uncomment to enable debugging output -# sensor.setDebug(True); + # Uncomment to enable debugging output + # sensor.setDebug(True); -# output the serial number and firmware revision -print -print "Device Description:", sensor.getDeviceDescription() -print "Device Location:", sensor.getDeviceLocation() -print + # output the serial number and firmware revision + print + print "Device Description:", sensor.getDeviceDescription() + print "Device Location:", sensor.getDeviceLocation() + print -# update and print available values every second -while (1): + # update and print available values every second + while (1): print "System Voltage:", print sensor.getAnalogValue(sensorObj.E50HX.AV_System_Voltage), print " ", @@ -92,4 +93,7 @@ while (1): print sensor.getAnalogInput(sensorObj.E50HX.AI_Power_Up_Count) print - time.sleep(5) + time.sleep(5) + +if __name__ == '__main__': + main() diff --git a/examples/python/eboled.py b/examples/python/eboled.py old mode 100644 new mode 100755 index b33aaba6..3fab0f42 --- a/examples/python/eboled.py +++ b/examples/python/eboled.py @@ -25,17 +25,18 @@ import time, sys import pyupm_i2clcd as lcdObj -# 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) - +def main(): + # 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) +if __name__ == '__main__': + main() diff --git a/examples/python/ehr.py b/examples/python/ehr.py old mode 100644 new mode 100755 index 7f1e6335..2ed3d6a2 --- a/examples/python/ehr.py +++ b/examples/python/ehr.py @@ -21,48 +21,49 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_ehr as upmehr -# Instantiate a Ear-clip Heart Rate sensor on digital pin D2 -myHeartRateSensor = upmehr.EHR(2) +def main(): + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myHeartRateSensor + def exitHandler(): + myHeartRateSensor.stopBeatCounter() + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myHeartRateSensor -def exitHandler(): - myHeartRateSensor.stopBeatCounter() - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # set the beat counter to 0, init the clock and start counting beats + myHeartRateSensor.clearBeatCounter() + 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 -myHeartRateSensor.clearBeatCounter() -myHeartRateSensor.initClock() -myHeartRateSensor.startBeatCounter() + # heartRate() requires that at least 5 seconds pass before + # returning anything other than 0 + fr = myHeartRateSensor.heartRate() -while(1): - # we grab these (millis and flowCount) just for display - # purposes in this example - millis = myHeartRateSensor.getMillis() - beats = myHeartRateSensor.beatCounter() + # 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) - # heartRate() requires that at least 5 seconds pass before - # returning anything other than 0 - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/eldriver.py b/examples/python/eldriver.py old mode 100644 new mode 100755 index fc94db2a..71733012 --- a/examples/python/eldriver.py +++ b/examples/python/eldriver.py @@ -24,34 +24,36 @@ import time, sys, signal, atexit import pyupm_eldriver as upmeldriver -# The was tested with the El Driver Module -# Instantiate a El Driver on digital pin D2 -myEldriver = upmeldriver.ElDriver(2) +def main(): + # The was tested with the El Driver Module + # 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 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, including functions from myEldriver + def exitHandler(): + print "Exiting" + myEldriver.off() + sys.exit(0) -# This function lets you run code on exit, including functions from myEldriver -def exitHandler(): - print "Exiting" - myEldriver.off() - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + lightState = True + while(1): + if (lightState): + myEldriver.on() + else: + myEldriver.off() + lightState = not lightState -lightState = True + time.sleep(1) -while(1): - if (lightState): - myEldriver.on() - else: - myEldriver.off() - lightState = not lightState - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/electromagnet.py b/examples/python/electromagnet.py old mode 100644 new mode 100755 index a658971c..317d82f1 --- a/examples/python/electromagnet.py +++ b/examples/python/electromagnet.py @@ -24,37 +24,39 @@ import time, sys, signal, atexit import pyupm_electromagnet as upmelectromagnet -# This was tested with the Electromagnetic Module -# Instantiate a Electromagnet on digital pin D2 -myElectromagnet = upmelectromagnet.Electromagnet(2) +def main(): + # This was tested with the Electromagnetic Module + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myElectromagnet + def exitHandler(): + print "Exiting" + myElectromagnet.off() + sys.exit(0) -# This lets you run code on exit, -# including functions from myElectromagnet -def exitHandler(): - print "Exiting" - myElectromagnet.off() - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + magnetState = False + # 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 -while(1): - magnetState = not magnetState - if (magnetState): - myElectromagnet.on() - else: - myElectromagnet.off() - print "Turning magnet", ("on" if magnetState else "off") - - time.sleep(5) +if __name__ == '__main__': + main() diff --git a/examples/python/emg.py b/examples/python/emg.py old mode 100644 new mode 100755 index d2446647..23a951a6 --- a/examples/python/emg.py +++ b/examples/python/emg.py @@ -24,29 +24,31 @@ import time, sys, signal, atexit import pyupm_emg as upmEmg -# Tested with the EMG Muscle Signal Reader Sensor Module -# Instantiate a EMG on analog pin A0 -myEMG = upmEmg.EMG(0) +def main(): + # Tested with the EMG Muscle Signal Reader Sensor Module + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myEMG + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myEMG -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Calibrating...." + myEMG.calibrate() + while (1): + print myEMG.value() + time.sleep(.1) -print "Calibrating...." -myEMG.calibrate() - -while (1): - print myEMG.value() - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/enc03r.py b/examples/python/enc03r.py old mode 100644 new mode 100755 index 45db89f6..7a4aa19b --- a/examples/python/enc03r.py +++ b/examples/python/enc03r.py @@ -24,41 +24,43 @@ import time, sys, signal, atexit import pyupm_enc03r as upmEnc03r -# Instantiate an ENC03R on analog pin A0 -myAnalogGyro = upmEnc03r.ENC03R(0) +def main(): + # 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 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, + # including functions from myAnalogGyro + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myAnalogGyro -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + CALIBRATION_SAMPLES = 1000 + 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" -"and do not move it while calibration takes place.\n" -"This may take a couple of minutes.") + while(1): + gyroVal = myAnalogGyro.value(); + outputStr = ("Raw value: {0}, " + "angular velocity: {1}" + " deg/s".format(gyroVal, myAnalogGyro.angularVelocity(gyroVal))) + print outputStr -myAnalogGyro.calibrate(CALIBRATION_SAMPLES) -print "Calibration complete. " -print "Reference value: ", myAnalogGyro.calibrationValue() + time.sleep(.1) -while(1): - gyroVal = myAnalogGyro.value(); - outputStr = ("Raw value: {0}, " - "angular velocity: {1}" - " deg/s".format(gyroVal, myAnalogGyro.angularVelocity(gyroVal))) - print outputStr - - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/es08a.py b/examples/python/es08a.py old mode 100644 new mode 100755 index 09a12845..436d6c6c --- a/examples/python/es08a.py +++ b/examples/python/es08a.py @@ -1,4 +1,4 @@ -# Author: John Van Drasek +# Author: John Van Drasek # Copyright (c) 2015 Intel Corporation. # # 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. import time -import pyupm_servo as servo +import pyupm_servo as servo -# Create the servo object using D5 -gServo = servo.ES08A(5) +def main(): + # Create the servo object using D5 + gServo = servo.ES08A(5) -for i in range(0,10): - # Set the servo arm to 0 degrees - gServo.setAngle(0) - print 'Set angle to 0' - time.sleep(1) + for i in range(0,10): + # Set the servo arm to 0 degrees + gServo.setAngle(0) + print 'Set angle to 0' + time.sleep(1) - # Set the servo arm to 90 degrees - gServo.setAngle(90) - print 'Set angle to 90' - time.sleep(1) + # Set the servo arm to 90 degrees + gServo.setAngle(90) + print 'Set angle to 90' + time.sleep(1) - # Set the servo arm to 180 degrees - gServo.setAngle(180) - print 'Set angle to 180' - time.sleep(1) + # Set the servo arm to 180 degrees + gServo.setAngle(180) + print 'Set angle to 180' + time.sleep(1) -# Delete the servo object -del gServo + # Delete the servo object + del gServo + +if __name__ == '__main__': + main() diff --git a/examples/python/gp2y0a.py b/examples/python/gp2y0a.py old mode 100644 new mode 100755 index f736d2cb..30a6afe2 --- a/examples/python/gp2y0a.py +++ b/examples/python/gp2y0a.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gp2y0a as upmGp2y0a -# Note, for the Grove 80cm version of this sensor, due to the way it is wired, -# you need to plug this into the A0 port, where it will use the available -# A1 pin for data. -# Instantiate a GP2Y0A on analog pin A1 -myIRProximity = upmGp2y0a.GP2Y0A(1) +def main(): + # Note, for the Grove 80cm version of this sensor, due to the way it is wired, + # you need to plug this into the A0 port, where it will use the available + # A1 pin for data. + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myIRProximity + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myIRProximity -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # analog voltage, usually 3.3 or 5.0 + GP2Y0A_AREF = 5.0; + 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 -GP2Y0A_AREF = 5.0; -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) +if __name__ == '__main__': + main() diff --git a/examples/python/gprs.py b/examples/python/gprs.py old mode 100644 new mode 100755 index 3f031144..6252cd32 --- a/examples/python/gprs.py +++ b/examples/python/gprs.py @@ -24,54 +24,53 @@ import time, sys, signal, atexit import pyupm_gprs as sensorObj -# Instantiate a GPRS Module on UART 0 -sensor = sensorObj.GPRS(0) +def main(): + # Instantiate a GPRS Module on UART 0 + sensor = sensorObj.GPRS(0) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Set the baud rate, 19200 baud is the default. -if (sensor.setBaudRate(19200)): - print "Failed to set baud rate" - sys.exit(0) + # Set the baud rate, 19200 baud is the default. + if (sensor.setBaudRate(19200)): + print "Failed to set baud rate" + 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" -"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 - -# simple helper function to send a command and wait for a response -def sendCommand(sensor, cmd): + # 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 cmd += "\r"; - sensor.writeDataStr(cmd) + sensor.writeDataStr(cmd) - # wait up to 1 second - if (sensor.dataAvailable(1000)): - print "Returned: ", - print sensor.readDataStr(1024) - else: - print "Timed out waiting for response" + # wait up to 1 second + if (sensor.dataAvailable(1000)): + print "Returned: ", + print sensor.readDataStr(1024) + else: + print "Timed out waiting for response" - -if (len(sys.argv) > 1): - print "Sending command line argument (" + sys.argv[1] + ")..." - sendCommand(sensor, sys.argv[1]) -else: + if (len(sys.argv) > 1): + print "Sending command line argument (" + sys.argv[1] + ")..." + sendCommand(sensor, sys.argv[1]) + else: # query the module manufacturer print "Querying module manufacturer (AT+CGMI)..." sendCommand(sensor, "AT+CGMI"); @@ -84,3 +83,6 @@ else: # A comprehensive list is available from the datasheet at: # http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf + +if __name__ == '__main__': + main() diff --git a/examples/python/grovebutton.py b/examples/python/grovebutton.py old mode 100644 new mode 100755 index c62c399a..9f0661c1 --- a/examples/python/grovebutton.py +++ b/examples/python/grovebutton.py @@ -23,13 +23,17 @@ import time import pyupm_grove as grove -# Create the button object using GPIO pin 0 -button = grove.GroveButton(0) +def main(): + # Create the button object using GPIO pin 0 + button = grove.GroveButton(0) -# Read the input and print, waiting one second between readings -while 1: - print button.name(), ' value is ', button.value() - time.sleep(1) + # Read the input and print, waiting one second between readings + while 1: + print button.name(), ' value is ', button.value() + time.sleep(1) -# Delete the button object -del button + # Delete the button object + del button + +if __name__ == '__main__': + main() diff --git a/examples/python/grovecircularled.py b/examples/python/grovecircularled.py old mode 100644 new mode 100755 index 1c5a485d..a7e17e85 --- a/examples/python/grovecircularled.py +++ b/examples/python/grovecircularled.py @@ -25,26 +25,30 @@ import time, sys, signal, atexit import pyupm_my9221 as upmGroveCircularLED -# Exit handlers -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + # Exit handlers + def SIGINTHandler(signum, frame): + raise SystemExit -def exitHandler(): - circle.setLevel(0, True) - print "Exiting" - sys.exit(0) + def exitHandler(): + circle.setLevel(0, True) + print "Exiting" + sys.exit(0) -# This function lets you run code on exit -atexit.register(exitHandler) -# This function stops python from printing a stacktrace when you hit control-C -signal.signal(signal.SIGINT, SIGINTHandler) + # This function lets you run code on exit + atexit.register(exitHandler) + # This function stops python from printing a stacktrace when you hit control-C + signal.signal(signal.SIGINT, SIGINTHandler) -# Instantiate a Grove Circular LED on gpio pins 9 and 8 -circle = upmGroveCircularLED.GroveCircularLED(9, 8) + # Instantiate a Grove Circular LED on gpio pins 9 and 8 + circle = upmGroveCircularLED.GroveCircularLED(9, 8) -level = 0 + level = 0 -while(1): + while(1): circle.setSpinner(level) level = (level + 1) % 24 - time.sleep(.1) + time.sleep(.1) + +if __name__ == '__main__': + main() diff --git a/examples/python/grovecollision.py b/examples/python/grovecollision.py old mode 100644 new mode 100755 index 6cdd05cf..b0093451 --- a/examples/python/grovecollision.py +++ b/examples/python/grovecollision.py @@ -24,34 +24,36 @@ import time, sys, signal, atexit import pyupm_grovecollision as upmGrovecollision -# The was tested with the Grove Collision Sensor -# Instantiate a Grove Collision on digital pin D2 -myGrovecollision = upmGrovecollision.GroveCollision(2) +def main(): + # The was tested with the Grove Collision Sensor + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myGrovecollision + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myGrovecollision -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + collisionState = False + print "No collision" + 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 -print "No collision" - -while(1): - if (myGrovecollision.isColliding() and not collisionState): - print "Collision!" - collisionState = True - elif (not myGrovecollision.isColliding() and collisionState): - print "No collision" - collisionState = False +if __name__ == '__main__': + main() diff --git a/examples/python/groveehr.py b/examples/python/groveehr.py old mode 100644 new mode 100755 index 3dd0ee22..11e7d140 --- a/examples/python/groveehr.py +++ b/examples/python/groveehr.py @@ -21,48 +21,49 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_groveehr as upmGroveehr -# Instantiate a Grove Ear-clip Heart Rate sensor on digital pin D2 -myHeartRateSensor = upmGroveehr.GroveEHR(2) +def main(): + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myHeartRateSensor + def exitHandler(): + myHeartRateSensor.stopBeatCounter() + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myHeartRateSensor -def exitHandler(): - myHeartRateSensor.stopBeatCounter() - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # set the beat counter to 0, init the clock and start counting beats + myHeartRateSensor.clearBeatCounter() + 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 -myHeartRateSensor.clearBeatCounter() -myHeartRateSensor.initClock() -myHeartRateSensor.startBeatCounter() + # heartRate() requires that at least 5 seconds pass before + # returning anything other than 0 + fr = myHeartRateSensor.heartRate() -while(1): - # we grab these (millis and flowCount) just for display - # purposes in this example - millis = myHeartRateSensor.getMillis() - beats = myHeartRateSensor.beatCounter() + # 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) - # heartRate() requires that at least 5 seconds pass before - # returning anything other than 0 - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/groveeldriver.py b/examples/python/groveeldriver.py old mode 100644 new mode 100755 index c9fd9360..1a503707 --- a/examples/python/groveeldriver.py +++ b/examples/python/groveeldriver.py @@ -24,34 +24,36 @@ import time, sys, signal, atexit import pyupm_groveeldriver as upmGroveeldriver -# The was tested with the Grove El Driver Module -# Instantiate a Grove El Driver on digital pin D2 -myEldriver = upmGroveeldriver.GroveElDriver(2) +def main(): + # The was tested with the Grove El Driver Module + # 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 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, including functions from myEldriver + def exitHandler(): + print "Exiting" + myEldriver.off() + sys.exit(0) -# This function lets you run code on exit, including functions from myEldriver -def exitHandler(): - print "Exiting" - myEldriver.off() - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + lightState = True + while(1): + if (lightState): + myEldriver.on() + else: + myEldriver.off() + lightState = not lightState -lightState = True + time.sleep(1) -while(1): - if (lightState): - myEldriver.on() - else: - myEldriver.off() - lightState = not lightState - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/groveelectromagnet.py b/examples/python/groveelectromagnet.py old mode 100644 new mode 100755 index c84af688..20c05a6e --- a/examples/python/groveelectromagnet.py +++ b/examples/python/groveelectromagnet.py @@ -24,37 +24,39 @@ import time, sys, signal, atexit import pyupm_groveelectromagnet as upmGroveelectromagnet -# This was tested with the Grove Electromagnetic Module -# Instantiate a Grove Electromagnet on digital pin D2 -myElectromagnet = upmGroveelectromagnet.GroveElectromagnet(2) +def main(): + # This was tested with the Grove Electromagnetic Module + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myElectromagnet + def exitHandler(): + print "Exiting" + myElectromagnet.off() + sys.exit(0) -# This lets you run code on exit, -# including functions from myElectromagnet -def exitHandler(): - print "Exiting" - myElectromagnet.off() - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + magnetState = False + # 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 -while(1): - magnetState = not magnetState - if (magnetState): - myElectromagnet.on() - else: - myElectromagnet.off() - print "Turning magnet", ("on" if magnetState else "off") - - time.sleep(5) +if __name__ == '__main__': + main() diff --git a/examples/python/groveemg.py b/examples/python/groveemg.py old mode 100644 new mode 100755 index 898db266..d577aadc --- a/examples/python/groveemg.py +++ b/examples/python/groveemg.py @@ -24,29 +24,31 @@ import time, sys, signal, atexit import pyupm_groveemg as upmGroveemg -# Tested with the GroveEMG Muscle Signal Reader Sensor Module -# Instantiate a GroveEMG on analog pin A0 -myEMG = upmGroveemg.GroveEMG(0) +def main(): + # Tested with the GroveEMG Muscle Signal Reader Sensor Module + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myEMG + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myEMG -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Calibrating...." + myEMG.calibrate() + while (1): + print myEMG.value() + time.sleep(.1) -print "Calibrating...." -myEMG.calibrate() - -while (1): - print myEMG.value() - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/grovegprs.py b/examples/python/grovegprs.py old mode 100644 new mode 100755 index d441e38a..14f786f2 --- a/examples/python/grovegprs.py +++ b/examples/python/grovegprs.py @@ -24,54 +24,53 @@ import time, sys, signal, atexit import pyupm_grovegprs as sensorObj -# Instantiate a GroveGPRS Module on UART 0 -sensor = sensorObj.GroveGPRS(0) +def main(): + # Instantiate a GroveGPRS Module on UART 0 + sensor = sensorObj.GroveGPRS(0) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Set the baud rate, 19200 baud is the default. -if (sensor.setBaudRate(19200)): - print "Failed to set baud rate" - sys.exit(0) + # Set the baud rate, 19200 baud is the default. + if (sensor.setBaudRate(19200)): + print "Failed to set baud rate" + 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" -"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 - -# simple helper function to send a command and wait for a response -def sendCommand(sensor, cmd): + # 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 cmd += "\r"; - sensor.writeDataStr(cmd) + sensor.writeDataStr(cmd) - # wait up to 1 second - if (sensor.dataAvailable(1000)): - print "Returned: ", - print sensor.readDataStr(1024) - else: - print "Timed out waiting for response" + # wait up to 1 second + if (sensor.dataAvailable(1000)): + print "Returned: ", + print sensor.readDataStr(1024) + else: + print "Timed out waiting for response" - -if (len(sys.argv) > 1): - print "Sending command line argument (" + sys.argv[1] + ")..." - sendCommand(sensor, sys.argv[1]) -else: + if (len(sys.argv) > 1): + print "Sending command line argument (" + sys.argv[1] + ")..." + sendCommand(sensor, sys.argv[1]) + else: # query the module manufacturer print "Querying module manufacturer (AT+CGMI)..." sendCommand(sensor, "AT+CGMI"); @@ -84,3 +83,6 @@ else: # A comprehensive list is available from the datasheet at: # http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf + +if __name__ == '__main__': + main() diff --git a/examples/python/grovegsr.py b/examples/python/grovegsr.py old mode 100644 new mode 100755 index 993a6b0f..c86abe26 --- a/examples/python/grovegsr.py +++ b/examples/python/grovegsr.py @@ -24,30 +24,32 @@ import time, sys, signal, atexit 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 -myGSR = upmGrovegsr.GroveGSR(0) + # Instantiate a GroveGSR on analog pin A0 + 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myGSR + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myGSR -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Calibrating...." + myGSR.calibrate() + while (1): + print myGSR.value() + time.sleep(.5) -print "Calibrating...." -myGSR.calibrate() - -while (1): - print myGSR.value() - time.sleep(.5) +if __name__ == '__main__': + main() diff --git a/examples/python/groveled.py b/examples/python/groveled.py old mode 100644 new mode 100755 index eb104bf0..13c4ae86 --- a/examples/python/groveled.py +++ b/examples/python/groveled.py @@ -23,19 +23,23 @@ import time import pyupm_grove as grove -# Create the Grove LED object using GPIO pin 2 -led = grove.GroveLed(2) +def main(): + # Create the Grove LED object using GPIO pin 2 + led = grove.GroveLed(2) -# Print the name -print led.name() + # Print the name + print led.name() -# Turn the LED on and off 10 times, pausing one second -# between transitions -for i in range (0,10): - led.on() - time.sleep(1) - led.off() - time.sleep(1) + # Turn the LED on and off 10 times, pausing one second + # between transitions + for i in range (0,10): + led.on() + time.sleep(1) + led.off() + time.sleep(1) -# Delete the Grove LED object -del led + # Delete the Grove LED object + del led + +if __name__ == '__main__': + main() diff --git a/examples/python/groveledbar.py b/examples/python/groveledbar.py old mode 100644 new mode 100755 index 39d84622..cab0009f --- a/examples/python/groveledbar.py +++ b/examples/python/groveledbar.py @@ -24,41 +24,43 @@ import time, sys, signal, atexit import pyupm_my9221 as upmMy9221 -# Instantiate a MY9221, we use D8 for the data, and D9 for the -# data clock. This was tested with a Grove LED bar. -myLEDBar = upmMy9221.GroveLEDBar(8, 9) +def main(): + # Instantiate a MY9221, we use D8 for the data, and D9 for the + # 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 SIGINTHandler(signum, frame): - raise SystemExit + def exitHandler(): + myLEDBar.setBarLevel(0, True) + print "Exiting" + sys.exit(0) -def exitHandler(): - myLEDBar.setBarLevel(0, True) - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + atexit.register(exitHandler) + # This function stops python from printing a stacktrace when you hit control-C + signal.signal(signal.SIGINT, SIGINTHandler) -# This function lets you run code on exit -atexit.register(exitHandler) -# This function stops python from printing a stacktrace when you hit control-C -signal.signal(signal.SIGINT, SIGINTHandler) + directionBool = True + level = 1 + 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 -level = 1 - -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 +if __name__ == '__main__': + main() diff --git a/examples/python/grovelight.py b/examples/python/grovelight.py old mode 100644 new mode 100755 index a1939d75..3f7b64db --- a/examples/python/grovelight.py +++ b/examples/python/grovelight.py @@ -23,15 +23,19 @@ import time import pyupm_grove as grove -# Create the light sensor object using AIO pin 0 -light = grove.GroveLight(0) +def main(): + # 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, -# waiting one second between readings -while 1: - print light.name() + " raw value is %d" % light.raw_value() + \ - ", which is roughly %d" % light.value() + " lux"; - time.sleep(1) + # Read the input and print both the raw value and a rough lux value, + # waiting one second between readings + while 1: + print light.name() + " raw value is %d" % light.raw_value() + \ + ", which is roughly %d" % light.value() + " lux"; + time.sleep(1) -# Delete the light sensor object -del light + # Delete the light sensor object + del light + +if __name__ == '__main__': + main() diff --git a/examples/python/grovelinefinder.py b/examples/python/grovelinefinder.py old mode 100644 new mode 100755 index bdcd68a9..10651be1 --- a/examples/python/grovelinefinder.py +++ b/examples/python/grovelinefinder.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_grovelinefinder as upmGrovelinefinder -# Instantiate a Grove line finder sensor on digital pin D2 -myLineFinder = upmGrovelinefinder.GroveLineFinder(2) +def main(): + # 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 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, including functions from myLineFinder + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myLineFinder -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myLineFinder.whiteDetected()): + print "White detected." + else: + print "Black detected." + time.sleep(1) - -while(1): - if (myLineFinder.whiteDetected()): - print "White detected." - else: - print "Black detected." - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/grovemd-stepper.py b/examples/python/grovemd-stepper.py old mode 100644 new mode 100755 index 7bafae5e..c77d46ad --- a/examples/python/grovemd-stepper.py +++ b/examples/python/grovemd-stepper.py @@ -24,29 +24,32 @@ import time import pyupm_grovemd as upmGrovemd -I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS -I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR +def main(): + I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS + I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR -# Instantiate an I2C Grove Motor Driver on I2C bus 0 -myMotorDriver = upmGrovemd.GroveMD(I2C_BUS, I2C_ADDR) + # Instantiate an I2C Grove Motor Driver on I2C bus 0 + 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 -myMotorDriver.configStepper(200) + # configure it, for this example, we'll assume 200 steps per rev + myMotorDriver.configStepper(200) -# set for half a rotation -myMotorDriver.setStepperSteps(100) + # set for half a rotation + myMotorDriver.setStepperSteps(100) -# let it go - clockwise rotation, 10 RPM speed -myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CW, 10) + # let it go - clockwise rotation, 10 RPM speed + myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CW, 10) -time.sleep(3) + time.sleep(3) -# Now do it backwards... -myMotorDriver.setStepperSteps(100) -myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CCW, 10) + # Now do it backwards... + myMotorDriver.setStepperSteps(100) + myMotorDriver.enableStepper(upmGrovemd.GroveMD.STEP_DIR_CCW, 10) -# now disable -myMotorDriver.disableStepper() + # now disable + myMotorDriver.disableStepper() +if __name__ == '__main__': + main() diff --git a/examples/python/grovemd.py b/examples/python/grovemd.py old mode 100644 new mode 100755 index ac4243d8..a9ec646f --- a/examples/python/grovemd.py +++ b/examples/python/grovemd.py @@ -24,24 +24,27 @@ import time import pyupm_grovemd as upmGrovemd -I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS -I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR +def main(): + I2C_BUS = upmGrovemd.GROVEMD_I2C_BUS + I2C_ADDR = upmGrovemd.GROVEMD_DEFAULT_I2C_ADDR -# Instantiate an I2C Grove Motor Driver on I2C bus 0 -myMotorDriver = upmGrovemd.GroveMD(I2C_BUS, I2C_ADDR) + # Instantiate an I2C Grove Motor Driver on I2C bus 0 + 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% -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) + time.sleep(3) + # counter clockwise + print "Reversing M1 and M2 for 3 seconds" + myMotorDriver.setMotorDirections(upmGrovemd.GroveMD.DIR_CCW, + upmGrovemd.GroveMD.DIR_CCW) + time.sleep(3) -time.sleep(3) -# counter clockwise -print "Reversing M1 and M2 for 3 seconds" -myMotorDriver.setMotorDirections(upmGrovemd.GroveMD.DIR_CCW, -upmGrovemd.GroveMD.DIR_CCW) -time.sleep(3) + print "Stopping motors" + myMotorDriver.setMotorSpeeds(0, 0) -print "Stopping motors" -myMotorDriver.setMotorSpeeds(0, 0) +if __name__ == '__main__': + main() diff --git a/examples/python/grovemoisture.py b/examples/python/grovemoisture.py old mode 100644 new mode 100755 index 78d3fe47..23ced3bc --- a/examples/python/grovemoisture.py +++ b/examples/python/grovemoisture.py @@ -24,38 +24,40 @@ import time, sys, signal, atexit import pyupm_grovemoisture as upmMoisture -# Instantiate a Grove Moisture sensor on analog pin A0 -myMoisture = upmMoisture.GroveMoisture(0) +def main(): + # 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 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, including functions from myMoisture + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMoisture -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Values (approximate): + # 0-300, sensor in air or dry soil + # 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): -# 0-300, sensor in air or dry soil -# 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) +if __name__ == '__main__': + main() diff --git a/examples/python/groveo2.py b/examples/python/groveo2.py old mode 100644 new mode 100755 index 03f612bb..4737b779 --- a/examples/python/groveo2.py +++ b/examples/python/groveo2.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_groveo2 as upmGroveo2 -# This was tested with the O2 Oxygen Concentration Sensor Module -# Instantiate a GroveO2 on analog pin A0 -myGroveO2 = upmGroveo2.GroveO2(0) +def main(): + # This was tested with the O2 Oxygen Concentration Sensor Module + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myGroveO2 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myGroveO2 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + print "The output voltage is: {0}mV".format( + myGroveO2.voltageValue()) + time.sleep(.1) -while(1): - print "The output voltage is: {0}mV".format( - myGroveO2.voltageValue()) - - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/groverelay.py b/examples/python/groverelay.py old mode 100644 new mode 100755 index 44f033fa..03cb0803 --- a/examples/python/groverelay.py +++ b/examples/python/groverelay.py @@ -23,22 +23,26 @@ import time import pyupm_grove as grove -# Create the relay switch object using GPIO pin 0 -relay = grove.GroveRelay(0) +def main(): + # Create the relay switch object using GPIO pin 0 + relay = grove.GroveRelay(0) -# Close and then open the relay switch 3 times, -# waiting one second each time. The LED on the relay switch -# will light up when the switch is on (closed). -# The switch will also make a noise between transitions. -for i in range (0,3): - relay.on() - if relay.isOn(): - print relay.name(), 'is on' - time.sleep(1) - relay.off() - if relay.isOff(): - print relay.name(), 'is off' - time.sleep(1) + # Close and then open the relay switch 3 times, + # waiting one second each time. The LED on the relay switch + # will light up when the switch is on (closed). + # The switch will also make a noise between transitions. + for i in range (0,3): + relay.on() + if relay.isOn(): + print relay.name(), 'is on' + time.sleep(1) + relay.off() + if relay.isOff(): + print relay.name(), 'is off' + time.sleep(1) -# Delete the relay switch object -del relay + # Delete the relay switch object + del relay + +if __name__ == '__main__': + main() diff --git a/examples/python/groverotary.py b/examples/python/groverotary.py old mode 100644 new mode 100755 index 6d62c3c8..5a637cea --- a/examples/python/groverotary.py +++ b/examples/python/groverotary.py @@ -23,23 +23,26 @@ from time import sleep import pyupm_grove as grove -# New knob on AIO pin 0 -knob = grove.GroveRotary(0) +def main(): + # New knob on AIO pin 0 + knob = grove.GroveRotary(0) -# Loop indefinitely -while True: + # Loop indefinitely + while True: + # Read values + abs = knob.abs_value() + absdeg = knob.abs_deg() + absrad = knob.abs_rad() - # Read values - abs = knob.abs_value() - absdeg = knob.abs_deg() - absrad = knob.abs_rad() + rel = knob.rel_value() + reldeg = knob.rel_deg() + relrad = knob.rel_rad() - rel = knob.rel_value() - reldeg = knob.rel_deg() - relrad = knob.rel_rad() + print "Abs values: %4d" % int(abs) , " raw %4d" % int(absdeg), "deg = %5.2f" % absrad , " rad ", + print "Rel values: %4d" % int(rel) , " raw %4d" % int(reldeg), "deg = %5.2f" % relrad , " rad" - print "Abs values: %4d" % int(abs) , " raw %4d" % int(absdeg), "deg = %5.2f" % absrad , " rad ", - print "Rel values: %4d" % int(rel) , " raw %4d" % int(reldeg), "deg = %5.2f" % relrad , " rad" + # Sleep for 2.5 s + sleep(2.5) - # Sleep for 2.5 s - sleep(2.5) +if __name__ == '__main__': + main() diff --git a/examples/python/grovescam.py b/examples/python/grovescam.py old mode 100644 new mode 100755 index 53ede097..2adba976 --- a/examples/python/grovescam.py +++ b/examples/python/grovescam.py @@ -25,37 +25,41 @@ import sys import pyupm_grovescam as upmGrovescam -# Instantiate a Grove Serial Camera on UART 0 -camera = upmGrovescam.GROVESCAM(0) +def main(): + # Instantiate a Grove Serial Camera on UART 0 + camera = upmGrovescam.GROVESCAM(0) -# make sure port is initialized properly. 115200 baud is the default. -if (not camera.setupTty()): - print "Failed to setup tty port parameters" - sys.exit(1) + # make sure port is initialized properly. 115200 baud is the default. + if (not camera.setupTty()): + print "Failed to setup tty port parameters" + sys.exit(1) -if (camera.init()): + if (camera.init()): print "Initialized..." -else: + else: print "init() failed" -if (camera.preCapture()): + if (camera.preCapture()): print "preCapture succeeded..." -else: + else: print "preCapture failed." -if (camera.doCapture()): + if (camera.doCapture()): print "doCapture succeeded..." -else: + else: 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..." if (camera.storeImage("image.jpg")): - print "storeImage succeeded..." + print "storeImage succeeded..." else: - print "storeImage failed." + print "storeImage failed." -print "Exiting." -sys.exit(0) + print "Exiting." + sys.exit(0) + +if __name__ == '__main__': + main() diff --git a/examples/python/groveslide.py b/examples/python/groveslide.py old mode 100644 new mode 100755 index 894fdc81..81e932d2 --- a/examples/python/groveslide.py +++ b/examples/python/groveslide.py @@ -23,17 +23,20 @@ from time import sleep import pyupm_grove as grove -# New Grove Slider on AIO pin 0 -slider = grove.GroveSlide(0) +def main(): + # New Grove Slider on AIO pin 0 + slider = grove.GroveSlide(0) -# Loop indefinitely -while True: + # Loop indefinitely + while True: + # Read values + raw = slider.raw_value() + volts = slider.voltage_value() - # Read values - raw = slider.raw_value() - volts = slider.voltage_value() + print "Slider value: ", raw , " = %.2f" % volts , " V" - print "Slider value: ", raw , " = %.2f" % volts , " V" + # Sleep for 2.5 s + sleep(2.5) - # Sleep for 2.5 s - sleep(2.5) +if __name__ == '__main__': + main() diff --git a/examples/python/grovespeaker.py b/examples/python/grovespeaker.py old mode 100644 new mode 100755 index 6e53b3c5..af2d18c8 --- a/examples/python/grovespeaker.py +++ b/examples/python/grovespeaker.py @@ -24,11 +24,15 @@ import time, sys, signal, atexit import pyupm_grovespeaker as upmGrovespeaker -# Instantiate a Grove Speaker on digital pin D2 -mySpeaker = upmGrovespeaker.GroveSpeaker(2) +def main(): + # Instantiate a Grove Speaker on digital pin D2 + mySpeaker = upmGrovespeaker.GroveSpeaker(2) -# Play all 7 of the lowest notes -mySpeaker.playAll() + # Play all 7 of the lowest notes + mySpeaker.playAll() -# Play a medium C-sharp -mySpeaker.playSound('c', True, "med") + # Play a medium C-sharp + mySpeaker.playSound('c', True, "med") + +if __name__ == '__main__': + main() diff --git a/examples/python/grovetemp.py b/examples/python/grovetemp.py old mode 100644 new mode 100755 index bd9cc244..643109d6 --- a/examples/python/grovetemp.py +++ b/examples/python/grovetemp.py @@ -24,18 +24,22 @@ import time import pyupm_grove as grove -# Create the temperature sensor object using AIO pin 0 -temp = grove.GroveTemp(0) -print temp.name() +def main(): + # Create the temperature sensor object using AIO pin 0 + temp = grove.GroveTemp(0) + print temp.name() -# Read the temperature ten times, printing both the Celsius and -# equivalent Fahrenheit temperature, waiting one second between readings -for i in range(0, 10): - celsius = temp.value() - fahrenheit = celsius * 9.0/5.0 + 32.0; - print "%d degrees Celsius, or %d degrees Fahrenheit" \ - % (celsius, fahrenheit) - time.sleep(1) + # Read the temperature ten times, printing both the Celsius and + # equivalent Fahrenheit temperature, waiting one second between readings + for i in range(0, 10): + celsius = temp.value() + fahrenheit = celsius * 9.0/5.0 + 32.0; + print "%d degrees Celsius, or %d degrees Fahrenheit" \ + % (celsius, fahrenheit) + time.sleep(1) -# Delete the temperature sensor object -del temp + # Delete the temperature sensor object + del temp + +if __name__ == '__main__': + main() diff --git a/examples/python/grovevdiv.py b/examples/python/grovevdiv.py old mode 100644 new mode 100755 index 7719277c..69dffde7 --- a/examples/python/grovevdiv.py +++ b/examples/python/grovevdiv.py @@ -24,31 +24,33 @@ import time, sys, signal, atexit import pyupm_grovevdiv as upmGrovevdiv -# Instantiate a Grove Voltage Divider sensor on analog pin A0 -myVoltageDivider = upmGrovevdiv.GroveVDiv(0) +def main(): + # 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 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, + # including functions from myVoltageDivider + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myVoltageDivider -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + val = myVoltageDivider.value(100) + 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): - val = myVoltageDivider.value(100) - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/grovewater.py b/examples/python/grovewater.py old mode 100644 new mode 100755 index 54a3d149..ba7b5b1d --- a/examples/python/grovewater.py +++ b/examples/python/grovewater.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_grovewater as upmGrovewater -# Instantiate a Grove Water sensor on digital pin D2 -myWaterSensor = upmGrovewater.GroveWater(2) +def main(): + # 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 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, including functions from myWaterSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myWaterSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myWaterSensor.isWet()): + print "Sensor is wet" + else: + print "Sensor is dry" + time.sleep(1) - -while(1): - if (myWaterSensor.isWet()): - print "Sensor is wet" - else: - print "Sensor is dry" - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/grovewfs.py b/examples/python/grovewfs.py old mode 100644 new mode 100755 index 84c5a979..51773afa --- a/examples/python/grovewfs.py +++ b/examples/python/grovewfs.py @@ -24,41 +24,43 @@ import time, sys, signal, atexit import pyupm_grovewfs as upmGrovewfs -# Instantiate a Grove Water Flow Sensor on digital pin D2 -myWaterFlow = upmGrovewfs.GroveWFS(2) +def main(): + # 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 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, + # including functions from myWaterFlow + def exitHandler(): + myWaterFlow.stopFlowCounter() + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myWaterFlow -def exitHandler(): - myWaterFlow.stopFlowCounter() - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # set the flow counter to 0 and start counting + myWaterFlow.clearFlowCounter() + 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 -myWaterFlow.clearFlowCounter() -myWaterFlow.startFlowCounter() + fr = myWaterFlow.flowRate() -while (1): - # we grab these (millis and flowCount) just for display - # purposes in this example - millis = myWaterFlow.getMillis() - flowCount = myWaterFlow.flowCounter() + # 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) - fr = myWaterFlow.flowRate() - - # 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) +if __name__ == '__main__': + main() diff --git a/examples/python/gsr.py b/examples/python/gsr.py old mode 100644 new mode 100755 index 43ff809a..6468ff08 --- a/examples/python/gsr.py +++ b/examples/python/gsr.py @@ -24,30 +24,32 @@ import time, sys, signal, atexit 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 -myGSR = upmGsr.GSR(0) + # Instantiate a GSR on analog pin A0 + 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myGSR + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myGSR -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Calibrating...." + myGSR.calibrate() + while (1): + print myGSR.value() + time.sleep(.5) -print "Calibrating...." -myGSR.calibrate() - -while (1): - print myGSR.value() - time.sleep(.5) +if __name__ == '__main__': + main() diff --git a/examples/python/guvas12d.py b/examples/python/guvas12d.py old mode 100644 new mode 100755 index dca8de8b..fa786750 --- a/examples/python/guvas12d.py +++ b/examples/python/guvas12d.py @@ -24,33 +24,35 @@ import time, sys, signal, atexit import pyupm_guvas12d as upmUV -# Instantiate a UV sensor on analog pin A0 -myUVSensor = upmUV.GUVAS12D(0); +def main(): + # Instantiate a UV sensor on analog pin A0 + myUVSensor = upmUV.GUVAS12D(0); -# analog voltage, usually 3.3 or 5.0 -GUVAS12D_AREF = 5.0; -SAMPLES_PER_QUERY = 1024; + # analog voltage, usually 3.3 or 5.0 + GUVAS12D_AREF = 5.0; + 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 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, including functions from myUVSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myUVSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + 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) - -while(1): - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/h3lis331dl.py b/examples/python/h3lis331dl.py old mode 100644 new mode 100755 index 60142f51..776fc965 --- a/examples/python/h3lis331dl.py +++ b/examples/python/h3lis331dl.py @@ -24,53 +24,55 @@ import time, sys, signal, atexit import pyupm_h3lis331dl as upmH3LIS331DL -# Instantiate an H3LIS331DL on I2C bus 0 -myDigitalAccelerometer = upmH3LIS331DL.H3LIS331DL( - upmH3LIS331DL.H3LIS331DL_I2C_BUS, - upmH3LIS331DL.H3LIS331DL_DEFAULT_I2C_ADDR); +def main(): + # Instantiate an H3LIS331DL on I2C bus 0 + myDigitalAccelerometer = upmH3LIS331DL.H3LIS331DL( + 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 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, including functions from myDigitalAccelerometer + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myDigitalAccelerometer -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Initialize the device with default values + myDigitalAccelerometer.init() + x = upmH3LIS331DL.new_intp() + y = upmH3LIS331DL.new_intp() + z = upmH3LIS331DL.new_intp() -# Initialize the device with default values -myDigitalAccelerometer.init() + ax = upmH3LIS331DL.new_floatp() + ay = upmH3LIS331DL.new_floatp() + az = upmH3LIS331DL.new_floatp() -x = upmH3LIS331DL.new_intp() -y = upmH3LIS331DL.new_intp() -z = upmH3LIS331DL.new_intp() + while (1): + myDigitalAccelerometer.update() + 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() -ay = upmH3LIS331DL.new_floatp() -az = upmH3LIS331DL.new_floatp() + 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) -while (1): - myDigitalAccelerometer.update() - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/h803x.py b/examples/python/h803x.py old mode 100644 new mode 100755 index 4e950e0d..8924b258 --- a/examples/python/h803x.py +++ b/examples/python/h803x.py @@ -24,40 +24,41 @@ import time, sys, signal, atexit import pyupm_h803x as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an H803X instance, using MODBUS slave address 1, and -# default comm parameters (9600, 8, N, 2) -sensor = sensorObj.H803X(defaultDev, 1) + # Instantiate an H803X instance, using MODBUS slave address 1, and + # default comm parameters (9600, 8, N, 2) + sensor = sensorObj.H803X(defaultDev, 1) -# output the serial number and firmware revision -print "Slave ID:", sensor.getSlaveID() + # output the serial number and firmware revision + print "Slave ID:", sensor.getSlaveID() -print + print -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() @@ -66,41 +67,44 @@ while (1): print "Real Power (kW):", sensor.getRealPower() if (sensor.isH8036()): - # The H8036 has much more data available... + # The H8036 has much more data available... - print "Reactive Power (kVAR):", sensor.getReactivePower() - print "Apparent Power (kVA):", sensor.getApparentPower() - print "Power Factor:", sensor.getPowerFactor() - print "Volts Line to Line:", sensor.getVoltsLineToLine() - print "Volts Line to Neutral:", sensor.getVoltsLineToNeutral() + print "Reactive Power (kVAR):", sensor.getReactivePower() + print "Apparent Power (kVA):", sensor.getApparentPower() + print "Power Factor:", sensor.getPowerFactor() + print "Volts Line to Line:", sensor.getVoltsLineToLine() + 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 B (kW):", sensor.getRealPowerPhaseB() - print "Real Power Phase C (kW):", sensor.getRealPowerPhaseC() + print "Real Power Phase A (kW):", sensor.getRealPowerPhaseA() + print "Real Power Phase B (kW):", sensor.getRealPowerPhaseB() + print "Real Power Phase C (kW):", sensor.getRealPowerPhaseC() - print "Power Factor Phase A:", sensor.getPowerFactorPhaseA() - print "Power Factor Phase B:", sensor.getPowerFactorPhaseB() - print "Power Factor Phase C:", sensor.getPowerFactorPhaseC() + print "Power Factor Phase A:", sensor.getPowerFactorPhaseA() + print "Power Factor Phase B:", sensor.getPowerFactorPhaseB() + print "Power Factor Phase C:", sensor.getPowerFactorPhaseC() - print "Volts Phase A to B:", sensor.getVoltsPhaseAToB() - print "Volts Phase B to C:", sensor.getVoltsPhaseBToC() - print "Volts Phase A to C:", sensor.getVoltsPhaseAToC() - print "Volts Phase A to Neutral: ", - print sensor.getVoltsPhaseAToNeutral() - print "Volts Phase B to Neutral: ", - print sensor.getVoltsPhaseBToNeutral() - print "Volts Phase C to Neutral: ", - print sensor.getVoltsPhaseCToNeutral() + print "Volts Phase A to B:", sensor.getVoltsPhaseAToB() + print "Volts Phase B to C:", sensor.getVoltsPhaseBToC() + print "Volts Phase A to C:", sensor.getVoltsPhaseAToC() + print "Volts Phase A to Neutral: ", + print sensor.getVoltsPhaseAToNeutral() + print "Volts Phase B to Neutral: ", + print sensor.getVoltsPhaseBToNeutral() + print "Volts Phase C to Neutral: ", + print sensor.getVoltsPhaseCToNeutral() - print "Current Phase A:", sensor.getCurrentPhaseA() - print "Current Phase B:", sensor.getCurrentPhaseB() - print "Current Phase C:", sensor.getCurrentPhaseC() + print "Current Phase A:", sensor.getCurrentPhaseA() + print "Current Phase B:", sensor.getCurrentPhaseB() + print "Current Phase C:", sensor.getCurrentPhaseC() - print "Avg Real Power (kW):", sensor.getAvgRealPower() - print "Min Real Power (kW):", sensor.getMinRealPower() - print "Max Real Power (kW):", sensor.getMaxRealPower() + print "Avg Real Power (kW):", sensor.getAvgRealPower() + print "Min Real Power (kW):", sensor.getMinRealPower() + print "Max Real Power (kW):", sensor.getMaxRealPower() print - time.sleep(2) + time.sleep(2) + +if __name__ == '__main__': + main() diff --git a/examples/python/hdxxvxta.py b/examples/python/hdxxvxta.py old mode 100644 new mode 100755 index c539d909..e753ec9a --- a/examples/python/hdxxvxta.py +++ b/examples/python/hdxxvxta.py @@ -24,28 +24,29 @@ import time, sys, signal, atexit import pyupm_hdxxvxta as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Initializing..." + print "Initializing..." -# Instantiate an HDXXVXTA instance, using A1 for humidity and A0 -# for temperature -sensor = sensorObj.HDXXVXTA(1, 0) + # Instantiate an HDXXVXTA instance, using A1 for humidity and A0 + # for temperature + sensor = sensorObj.HDXXVXTA(1, 0) -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() @@ -56,4 +57,7 @@ while (1): print "Humidity:", sensor.getHumidity(), "%" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/hka5.py b/examples/python/hka5.py old mode 100644 new mode 100755 index f6ff7cae..96571879 --- a/examples/python/hka5.py +++ b/examples/python/hka5.py @@ -24,26 +24,27 @@ import time, sys, signal, atexit import pyupm_hka5 as sensorObj -# Instantiate a HKA5 sensor on uart 0. We don't use the set or -# reset pins, so we pass -1 for them. -sensor = sensorObj.HKA5(0, -1, -1) +def main(): + # Instantiate a HKA5 sensor on uart 0. We don't use the set or + # reset pins, so we pass -1 for them. + sensor = sensorObj.HKA5(0, -1, -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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# update once every 2 seconds and output data -while (True): + # update once every 2 seconds and output data + while (True): sensor.update() print "PM 1 :", @@ -60,3 +61,6 @@ while (True): print time.sleep(2) + +if __name__ == '__main__': + main() diff --git a/examples/python/hm11.py b/examples/python/hm11.py old mode 100644 new mode 100755 index c20a8ead..94a0af53 --- a/examples/python/hm11.py +++ b/examples/python/hm11.py @@ -24,87 +24,86 @@ import time, sys, signal, atexit import pyupm_hm11 as upmHm11 -# Instantiate a HM11 BLE Module on UART 0 -my_ble_obj = upmHm11.HM11(0) +def main(): + # 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 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, + # including functions from my_ble_obj + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from my_ble_obj -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + bufferLength = 256 + # 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. -if (not my_ble_obj.setupTty(upmHm11.cvar.int_B9600)): - print "Failed to setup tty port parameters" - sys.exit(0) + # simple helper function to send a command and wait for a response + def sendCommand(bleObj, cmd): + bleBuffer = upmHm11.charArray(bufferLength) + 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" -"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 + 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 + ")..." -# simple helper function to send a command and wait for a response -def sendCommand(bleObj, cmd): - bleBuffer = upmHm11.charArray(bufferLength) - bleObj.writeData(cmd, len(cmd)) + 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) - # 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" - - -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 + # 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() diff --git a/examples/python/hmc5883l.py b/examples/python/hmc5883l.py old mode 100644 new mode 100755 index 50430732..2e7f0eff --- a/examples/python/hmc5883l.py +++ b/examples/python/hmc5883l.py @@ -23,22 +23,25 @@ from time import sleep import pyupm_hmc5883l as hmc5883l -# Create an I2C compass object and set declination -hmc = hmc5883l.Hmc5883l(0) -hmc.set_declination(0.2749) +def main(): + # Create an I2C compass object and set declination + hmc = hmc5883l.Hmc5883l(0) + hmc.set_declination(0.2749) -# Loop indefinitely -while True: + # Loop indefinitely + 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 - pos = hmc.coordinates() # Read raw coordinates - hdg = hmc.heading() # Read heading - dir = hmc.direction() # Read direction + # Print values + print "Coor: %5d %5d %5d" % (pos[0], pos[1], pos[2]) + print "Heading: %5.2f" % (hdg) + print "Direction: %3.2f\n" % (dir) - # Print values - print "Coor: %5d %5d %5d" % (pos[0], pos[1], pos[2]) - print "Heading: %5.2f" % (hdg) - print "Direction: %3.2f\n" % (dir) + # Sleep for 1 s + sleep(1) - # Sleep for 1 s - sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/hmtrp.py b/examples/python/hmtrp.py old mode 100644 new mode 100755 index 9b8fe195..6e434209 --- a/examples/python/hmtrp.py +++ b/examples/python/hmtrp.py @@ -24,120 +24,120 @@ import time, sys, signal, atexit import pyupm_hmtrp as upmHmtrp -# Instantiate a HMTRP radio device on uart 0 -my_HMTRP_Radio = upmHmtrp.HMTRP(0) +def main(): + # 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 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, + # including functions from my_HMTRP_Radio + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from my_HMTRP_Radio -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + myCounter = 0 + # 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 -bufferLength = 256 -radioBuffer = upmHmtrp.charArray(bufferLength) + 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. -if (not my_HMTRP_Radio.setupTty(upmHmtrp.cvar.int_B9600)): - print "Failed to setup tty port parameters" - sys.exit(0) + ''' + By default, this radio simply transmits data sent via writeData() + and reads any available data via readData(). + 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" -"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 + If any argument was specified on the command line, do a simple + configuration query and output the results. The radio must be in + CONFIG mode for this to work. -''' -By default, this radio simply transmits data sent via writeData() -and reads any available data via readData(). + Note that the first command-line argument should be "hmtry.py" + The data we want would be the second... if it exists + ''' + 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 -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". + if (my_HMTRP_Radio.getConfig(freq, dataRate, rxBandwidth, + 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 -If any argument was specified on the command line, do a simple -configuration query and output the results. The radio must be in -CONFIG mode for this to work. + outputStr = "modulation: %d Khz txPower: %d uartBaud: %d" % ( + modulation.__getitem__(0), txPower.__getitem__(0), + 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" -The data we want would be the second... if it exists -''' -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) + 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!" - if (my_HMTRP_Radio.getConfig(freq, dataRate, rxBandwidth, - 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 + print "Transmitting %s..." % msg - outputStr = "modulation: %d Khz txPower: %d uartBaud: %d" % ( - modulation.__getitem__(0), txPower.__getitem__(0), - 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) + # 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) - if (rv > 0): - resultStr = ""; - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/hp20x.py b/examples/python/hp20x.py old mode 100644 new mode 100755 index 0eeff04f..62685f16 --- a/examples/python/hp20x.py +++ b/examples/python/hp20x.py @@ -24,31 +24,34 @@ import time, sys, signal, atexit import pyupm_hp20x as barometerObj -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # 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, -# including functions from ringCoder -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit, + # including functions from ringCoder + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Instantiate an HP20X on default I2C bus and address -bar = barometerObj.HP20X() + # Instantiate an HP20X on default I2C bus and address + bar = barometerObj.HP20X() -# Initialize the device with default values -bar.init() + # Initialize the device with default values + bar.init() -while(1): - print "Temperature:", bar.getTemperature(), "Celsius" - print "Pressure: ", bar.getPressure(), "Millibars" - print "Altitude: ", bar.getAltitude(), "Meters" - print - time.sleep(1) + while(1): + print "Temperature:", bar.getTemperature(), "Celsius" + print "Pressure: ", bar.getPressure(), "Millibars" + print "Altitude: ", bar.getAltitude(), "Meters" + print + time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/ht9170.py b/examples/python/ht9170.py old mode 100644 new mode 100755 index 838b0cc5..fe406254 --- a/examples/python/ht9170.py +++ b/examples/python/ht9170.py @@ -24,31 +24,34 @@ import time, sys, signal, atexit import pyupm_ht9170 as upmHt9170 -# Instantiate a DTMF decoder -myDTMF = upmHt9170.HT9170(12, 11, 10, 9, 8) +def main(): + # Instantiate a DTMF decoder + myDTMF = upmHt9170.HT9170(12, 11, 10, 9, 8) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# This lets you run code on exit, including functions from myDTMF -def exitHandler(): - print "Exiting" - sys.exit(0) + # This lets you run code on exit, including functions from myDTMF + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + 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 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) +if __name__ == '__main__': + main() diff --git a/examples/python/hwxpxx.py b/examples/python/hwxpxx.py old mode 100644 new mode 100755 index 0def9953..61b637bb --- a/examples/python/hwxpxx.py +++ b/examples/python/hwxpxx.py @@ -24,44 +24,45 @@ import time, sys, signal, atexit import pyupm_hwxpxx as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an HWXPXX instance, using MODBUS slave address 3, and -# default comm parameters (19200, 8, N, 2) -sensor = sensorObj.HWXPXX(defaultDev, 3) + # Instantiate an HWXPXX instance, using MODBUS slave address 3, and + # default comm parameters (19200, 8, N, 2) + sensor = sensorObj.HWXPXX(defaultDev, 3) -# output the serial number and firmware revision -print "Slave ID:", sensor.getSlaveID() + # output the serial number and firmware revision + print "Slave ID:", sensor.getSlaveID() -# stored temperature and humidity offsets -print "Temperature Offset:", sensor.getTemperatureOffset() -print "Humidity Offset:", sensor.getHumidityOffset() + # stored temperature and humidity offsets + print "Temperature Offset:", sensor.getTemperatureOffset() + print "Humidity Offset:", sensor.getHumidityOffset() -print + print -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() @@ -76,4 +77,7 @@ while (1): print "Override Switch Status:", sensor.getOverrideSwitchStatus() print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/ili9341.py b/examples/python/ili9341.py old mode 100644 new mode 100755 index 5194cc31..262822a5 --- a/examples/python/ili9341.py +++ b/examples/python/ili9341.py @@ -24,52 +24,56 @@ import time import pyupm_ili9341 as ili9341 -# Pins (Edison) -# CS_LCD GP44 (MRAA 31) -# CS_SD GP43 (MRAA 38) unused -# DC GP12 (MRAA 20) -# RESEST GP13 (MRAA 14) -lcd = ili9341.ILI9341(31, 38, 20, 14) +def main(): + # Pins (Edison) + # CS_LCD GP44 (MRAA 31) + # CS_SD GP43 (MRAA 38) unused + # DC GP12 (MRAA 20) + # RESEST GP13 (MRAA 14) + lcd = ili9341.ILI9341(31, 38, 20, 14) -# Fill the screen with a solid color -lcd.fillScreen(lcd.color565(0, 40, 16)) + # Fill the screen with a solid color + lcd.fillScreen(lcd.color565(0, 40, 16)) -# Draw some shapes -lcd.drawFastVLine(10, 10, 100, ili9341.ILI9341_RED) -lcd.drawFastHLine(20, 10, 50, ili9341.ILI9341_CYAN) -lcd.drawLine(160, 30, 200, 60, ili9341.ILI9341_GREEN) -lcd.fillRect(20, 30, 75, 60, ili9341.ILI9341_ORANGE) -lcd.drawCircle(70, 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.fillTriangle(150, 100, 110, 140, 190, 140, ili9341.ILI9341_YELLOW) -lcd.drawRoundRect(20, 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) + # Draw some shapes + lcd.drawFastVLine(10, 10, 100, ili9341.ILI9341_RED) + lcd.drawFastHLine(20, 10, 50, ili9341.ILI9341_CYAN) + lcd.drawLine(160, 30, 200, 60, ili9341.ILI9341_GREEN) + lcd.fillRect(20, 30, 75, 60, ili9341.ILI9341_ORANGE) + lcd.drawCircle(70, 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.fillTriangle(150, 100, 110, 140, 190, 140, ili9341.ILI9341_YELLOW) + lcd.drawRoundRect(20, 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) -# Write some text -lcd.setCursor(0, 200) -lcd.setTextColor(ili9341.ILI9341_LIGHTGREY) -lcd.setTextWrap(True) -lcd.setTextSize(1) -lcd._print("Text 1\n") -lcd.setTextSize(2) -lcd._print("Text 2\n") -lcd.setTextSize(3) -lcd._print("Text 3\n") -lcd.setTextSize(4) -lcd._print("Text 4\n") + # Write some text + lcd.setCursor(0, 200) + lcd.setTextColor(ili9341.ILI9341_LIGHTGREY) + lcd.setTextWrap(True) + lcd.setTextSize(1) + lcd._print("Text 1\n") + lcd.setTextSize(2) + lcd._print("Text 2\n") + lcd.setTextSize(3) + lcd._print("Text 3\n") + lcd.setTextSize(4) + lcd._print("Text 4\n") -# Test screen rotation -for r in range(0, 4): - lcd.setRotation(r) - lcd.fillRect(0, 0, 5, 5, ili9341.ILI9341_WHITE) - time.sleep(1) - -# Invert colors, wait, then revert back -lcd.invertDisplay(True) -time.sleep(2) -lcd.invertDisplay(False) + # Test screen rotation + for r in range(0, 4): + lcd.setRotation(r) + lcd.fillRect(0, 0, 5, 5, ili9341.ILI9341_WHITE) + time.sleep(1) -# Don't forget to free up that memory! -del lcd \ No newline at end of file + # Invert colors, wait, then revert back + lcd.invertDisplay(True) + time.sleep(2) + lcd.invertDisplay(False) + + # Don't forget to free up that memory! + del lcd + +if __name__ == '__main__': + main() diff --git a/examples/python/ina132.py b/examples/python/ina132.py old mode 100644 new mode 100755 index 8db48621..9ccf268f --- a/examples/python/ina132.py +++ b/examples/python/ina132.py @@ -21,31 +21,32 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_ina132 as upmIna132 -# Tested with the INA132 Differential Amplifier Sensor module. -# Instantiate an INA132 on analog pin A0 -myDifferentialAmplifier = upmIna132.INA132(0) +def main(): + # Tested with the INA132 Differential Amplifier Sensor module. + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myDifferentialAmplifier + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myDifferentialAmplifier -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + print myDifferentialAmplifier.value() + time.sleep(1) - -while(1): - print myDifferentialAmplifier.value() - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/isd1820.py b/examples/python/isd1820.py old mode 100644 new mode 100755 index f39f4778..0ea23781 --- a/examples/python/isd1820.py +++ b/examples/python/isd1820.py @@ -24,51 +24,50 @@ import time, sys, atexit import pyupm_isd1820 as upmIsd1820 -# Instantiate a ISD1820 on digital pins 2 (play) and 3 (record) -# This example was tested on the Grove Recorder. -myRecorder = upmIsd1820.ISD1820(2, 3) +def main(): + # Instantiate a ISD1820 on digital pins 2 (play) and 3 (record) + # 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: - doRecord = True + # This lets you run code on exit, + # 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, -# 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) + # if an argument was specified (any argument), go into record mode, + # else playback a previously recorded sample -# Register exit handlers -atexit.register(exitHandler) + print "Supply any argument to the command line to record." + 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, -# else playback a previously recorded sample + # 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) -print "Supply any argument to the command line to record." -print "Running this example without arguments will play back any " -print "previously recorded sound." -print "There is approximately 10 seconds of recording time.\n" + # exitHandler runs automatically - -# depending on what was selected, do it, and sleep for 15 seconds -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 +if __name__ == '__main__': + main() diff --git a/examples/python/itg3200.py b/examples/python/itg3200.py old mode 100644 new mode 100755 index cd4a7c48..18b259c5 --- a/examples/python/itg3200.py +++ b/examples/python/itg3200.py @@ -23,20 +23,24 @@ import time import pyupm_itg3200 as itg3200 -# Create an I2C gyro object -gyro = itg3200.Itg3200(0) +def main(): + # Create an I2C gyro object + gyro = itg3200.Itg3200(0) -while(1): - gyro.update() # Update the data - rot = gyro.getRawValues() # Read raw sensor data - ang = gyro.getRotation() # Read rotational speed (deg/sec) - print "Raw: %6d %6d %6d" % (rot[0], rot[1], rot[2]) - print "AngX: %5.2f" % (ang[0]) - print "AngY: %5.2f" % (ang[1]) - print "AngZ: %5.2f" % (ang[2]) - print "Temp: %5.2f Raw: %6d" % (gyro.getTemperature(), gyro.getRawTemp()) - print ' ' - time.sleep(1) + while(1): + gyro.update() # Update the data + rot = gyro.getRawValues() # Read raw sensor data + ang = gyro.getRotation() # Read rotational speed (deg/sec) + print "Raw: %6d %6d %6d" % (rot[0], rot[1], rot[2]) + print "AngX: %5.2f" % (ang[0]) + print "AngY: %5.2f" % (ang[1]) + print "AngZ: %5.2f" % (ang[2]) + print "Temp: %5.2f Raw: %6d" % (gyro.getTemperature(), gyro.getRawTemp()) + print ' ' + time.sleep(1) -# Delete the gyro object -del gyro + # Delete the gyro object + del gyro + +if __name__ == '__main__': + main() diff --git a/examples/python/jhd1313m1-lcd.py b/examples/python/jhd1313m1-lcd.py old mode 100644 new mode 100755 index fc0bc653..ce5fe764 --- a/examples/python/jhd1313m1-lcd.py +++ b/examples/python/jhd1313m1-lcd.py @@ -23,16 +23,20 @@ import pyupm_i2clcd as lcd -# Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS) -myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62) +def main(): + # Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS) + myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62) -myLcd.setCursor(0,0) -# RGB Blue -#myLcd.setColor(53, 39, 249) + myLcd.setCursor(0,0) + # RGB Blue + #myLcd.setColor(53, 39, 249) -# RGB Red -myLcd.setColor(255, 0, 0) + # RGB Red + myLcd.setColor(255, 0, 0) -myLcd.write('Hello World') -myLcd.setCursor(1,2) -myLcd.write('Hello World') + myLcd.write('Hello World') + myLcd.setCursor(1,2) + myLcd.write('Hello World') + +if __name__ == '__main__': + main() diff --git a/examples/python/joystick12.py b/examples/python/joystick12.py old mode 100644 new mode 100755 index eaae1495..edfb2a5b --- a/examples/python/joystick12.py +++ b/examples/python/joystick12.py @@ -24,29 +24,31 @@ import time, sys, signal, atexit import pyupm_joystick12 as upmJoystick12 -# Instantiate a joystick on analog pins A0 and A1 -myJoystick = upmJoystick12.Joystick12(0, 1) +def main(): + # 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 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, including functions from myJoystick + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myJoystick -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Print the X and Y input values every second + while(1): + 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 -while(1): - XString = "Driving X:" + str(myJoystick.getXInput()) - YString = ": and Y:" + str(myJoystick.getYInput()) - print XString + YString - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/l298-stepper.py b/examples/python/l298-stepper.py old mode 100644 new mode 100755 index cfac86f9..262704e8 --- a/examples/python/l298-stepper.py +++ b/examples/python/l298-stepper.py @@ -21,47 +21,48 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_l298 as upmL298 -# Instantiate a Stepper motor on a L298 Dual H-Bridge. -# This was tested with the NEMA-17 12V, 350mA, with 200 steps per rev. -myHBridge = upmL298.L298(200, 3, 4, 7, 8, 9) +def main(): + # Instantiate a Stepper motor on a L298 Dual H-Bridge. + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myHBridge + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myHBridge -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + myHBridge.setSpeed(10) # 10 RPMs + myHBridge.setDirection(upmL298.L298.DIR_CW) + 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 -myHBridge.setDirection(upmL298.L298.DIR_CW) -myHBridge.enable(True) + print "Sleeping for 2 seconds..." + time.sleep(2) -print "Rotating 1 full revolution at 10 RPM speed." -# move 200 steps, a full rev -myHBridge.stepperSteps(200) + print "Rotating 1/2 revolution in opposite direction at 10 RPM speed." + myHBridge.setDirection(upmL298.L298.DIR_CCW) + myHBridge.stepperSteps(100) -print "Sleeping for 2 seconds..." -time.sleep(2) + # release + myHBridge.enable(False) -print "Rotating 1/2 revolution in opposite direction at 10 RPM speed." -myHBridge.setDirection(upmL298.L298.DIR_CCW) -myHBridge.stepperSteps(100) + # exitHandler is called automatically -# release -myHBridge.enable(False) - -# exitHandler is called automatically +if __name__ == '__main__': + main() diff --git a/examples/python/l298.py b/examples/python/l298.py old mode 100644 new mode 100755 index f0b507c3..27b12933 --- a/examples/python/l298.py +++ b/examples/python/l298.py @@ -21,45 +21,46 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_l298 as upmL298 -# Instantiate one of the 2 possible DC motors on a L298 Dual -# H-Bridge. For controlling a stepper motor, see the l298-stepper -# example. -myHBridge = upmL298.L298(3, 4, 7) +def main(): + # Instantiate one of the 2 possible DC motors on a L298 Dual + # H-Bridge. For controlling a stepper motor, see the l298-stepper + # 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 stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myHBridge + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myHBridge -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Starting motor at 50% for 3 seconds..." + myHBridge.setSpeed(50) + myHBridge.setDirection(upmL298.L298.DIR_CW) + myHBridge.enable(True) + time.sleep(3) -print "Starting motor at 50% for 3 seconds..." -myHBridge.setSpeed(50) -myHBridge.setDirection(upmL298.L298.DIR_CW) -myHBridge.enable(True) + print "Reversing direction..." + myHBridge.setDirection(upmL298.L298.DIR_NONE) # fast stop + myHBridge.setDirection(upmL298.L298.DIR_CCW) + time.sleep(3); -time.sleep(3) + myHBridge.setSpeed(0) + myHBridge.enable(False) -print "Reversing direction..." -myHBridge.setDirection(upmL298.L298.DIR_NONE) # fast stop -myHBridge.setDirection(upmL298.L298.DIR_CCW) -time.sleep(3); + # exitHandler is called automatically -myHBridge.setSpeed(0) -myHBridge.enable(False) - -# exitHandler is called automatically +if __name__ == '__main__': + main() diff --git a/examples/python/ldt0028.py b/examples/python/ldt0028.py old mode 100644 new mode 100755 index b6001a7f..b97ce9e8 --- a/examples/python/ldt0028.py +++ b/examples/python/ldt0028.py @@ -24,43 +24,47 @@ import time import array import pyupm_ldt0028 as ldt0028 -NUMBER_OF_SECONDS = 10 -SAMPLES_PER_SECOND = 50 -THRESHOLD = 100 +def main(): + NUMBER_OF_SECONDS = 10 + SAMPLES_PER_SECOND = 50 + THRESHOLD = 100 -# Create the LDT0-028 Piezo Vibration Sensor object using AIO pin 0 -sensor = ldt0028.LDT0028(0) + # Create the LDT0-028 Piezo Vibration Sensor object using AIO pin 0 + sensor = ldt0028.LDT0028(0) -# Read the signal every 20 milliseconds for 10 seconds -print 'For the next', NUMBER_OF_SECONDS, 'seconds,', \ - SAMPLES_PER_SECOND, 'samples will be taken every second.\n' -buffer = array.array('H') -for i in range(0, NUMBER_OF_SECONDS * SAMPLES_PER_SECOND): - buffer.append(sensor.getSample()) - time.sleep(1.0/SAMPLES_PER_SECOND) + # Read the signal every 20 milliseconds for 10 seconds + print 'For the next', NUMBER_OF_SECONDS, 'seconds,', \ + SAMPLES_PER_SECOND, 'samples will be taken every second.\n' + buffer = array.array('H') + for i in range(0, NUMBER_OF_SECONDS * SAMPLES_PER_SECOND): + buffer.append(sensor.getSample()) + time.sleep(1.0/SAMPLES_PER_SECOND) -# Print the number of times the reading was greater than the threshold -count = 0 -for i in range(0, NUMBER_OF_SECONDS * SAMPLES_PER_SECOND): - if buffer[i] > THRESHOLD: - count += 1 -print sensor.name(), ' exceeded the threshold value of', \ - THRESHOLD, 'a total of', count, 'times,' -print 'out of a total of', NUMBER_OF_SECONDS*SAMPLES_PER_SECOND, \ - 'reading.\n' + # Print the number of times the reading was greater than the threshold + count = 0 + for i in range(0, NUMBER_OF_SECONDS * SAMPLES_PER_SECOND): + if buffer[i] > THRESHOLD: + count += 1 + print sensor.name(), ' exceeded the threshold value of', \ + THRESHOLD, 'a total of', count, 'times,' + print 'out of a total of', NUMBER_OF_SECONDS*SAMPLES_PER_SECOND, \ + 'reading.\n' -# Print a graphical representation of the average value sampled -# each second for the past 10 seconds, using a scale factor of 15 -print 'Now printing a graphical representation of the average reading ' -print 'each second for the last', NUMBER_OF_SECONDS, 'seconds.' -SCALE_FACTOR = 15 -for i in range(0, NUMBER_OF_SECONDS): - sum = 0 - for j in range(0, SAMPLES_PER_SECOND): - sum += buffer[i*SAMPLES_PER_SECOND+j] - average = sum / SAMPLES_PER_SECOND - stars_to_print = int(round(average / SCALE_FACTOR)) - print '(' + repr(int(round(average))).rjust(4) + ') |', '*' * stars_to_print + # Print a graphical representation of the average value sampled + # each second for the past 10 seconds, using a scale factor of 15 + print 'Now printing a graphical representation of the average reading ' + print 'each second for the last', NUMBER_OF_SECONDS, 'seconds.' + SCALE_FACTOR = 15 + for i in range(0, NUMBER_OF_SECONDS): + sum = 0 + for j in range(0, SAMPLES_PER_SECOND): + sum += buffer[i*SAMPLES_PER_SECOND+j] + average = sum / SAMPLES_PER_SECOND + stars_to_print = int(round(average / SCALE_FACTOR)) + print '(' + repr(int(round(average))).rjust(4) + ') |', '*' * stars_to_print -# Delete the sensor object -del sensor + # Delete the sensor object + del sensor + +if __name__ == '__main__': + main() diff --git a/examples/python/led.py b/examples/python/led.py old mode 100644 new mode 100755 index afcff24d..f1289c59 --- a/examples/python/led.py +++ b/examples/python/led.py @@ -23,19 +23,23 @@ import time import pyupm_led as led -# Create the Grove LED object using GPIO pin 2 -led = led.Led(2) +def main(): + # Create the Grove LED object using GPIO pin 2 + led = led.Led(2) -# Print the name -print led.name() + # Print the name + print led.name() -# Turn the LED on and off 10 times, pausing one second -# between transitions -for i in range (0,10): - led.on() - time.sleep(1) - led.off() - time.sleep(1) + # Turn the LED on and off 10 times, pausing one second + # between transitions + for i in range (0,10): + led.on() + time.sleep(1) + led.off() + time.sleep(1) -# Delete the Grove LED object -del led + # Delete the Grove LED object + del led + +if __name__ == '__main__': + main() diff --git a/examples/python/light.py b/examples/python/light.py old mode 100644 new mode 100755 index 3a7f74f3..a5088388 --- a/examples/python/light.py +++ b/examples/python/light.py @@ -23,15 +23,19 @@ import time import pyupm_light as light -# Create the light sensor object using AIO pin 0 -light = light.Light(0) +def main(): + # Create the light sensor object using AIO pin 0 + light = light.Light(0) -# Read the input and print both the raw value and a rough lux value, -# waiting one second between readings -while 1: - print light.name() + " raw value is %d" % light.raw_value() + \ - ", which is roughly %d" % light.value() + " lux"; - time.sleep(1) + # Read the input and print both the raw value and a rough lux value, + # waiting one second between readings + while 1: + print light.name() + " raw value is %d" % light.raw_value() + \ + ", which is roughly %d" % light.value() + " lux"; + time.sleep(1) -# Delete the light sensor object -del light + # Delete the light sensor object + del light + +if __name__ == '__main__': + main() diff --git a/examples/python/linefinder.py b/examples/python/linefinder.py old mode 100644 new mode 100755 index 91be81d2..fe18c9fa --- a/examples/python/linefinder.py +++ b/examples/python/linefinder.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_linefinder as upmlinefinder -# Instantiate a line finder sensor on digital pin D2 -myLineFinder = upmlinefinder.LineFinder(2) +def main(): + # Instantiate a line finder sensor on digital pin D2 + myLineFinder = upmlinefinder.LineFinder(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 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, including functions from myLineFinder + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myLineFinder -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myLineFinder.whiteDetected()): + print "White detected." + else: + print "Black detected." + time.sleep(1) - -while(1): - if (myLineFinder.whiteDetected()): - print "White detected." - else: - print "Black detected." - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/lm35.py b/examples/python/lm35.py old mode 100644 new mode 100755 index 342f0a92..6bd2eaac --- a/examples/python/lm35.py +++ b/examples/python/lm35.py @@ -24,26 +24,30 @@ import time, sys, signal, atexit import pyupm_lm35 as sensorObj -# Instantiate a LM35 on analog pin A0, with a default analog -# reference voltage of 5.0 -sensor = sensorObj.LM35(0) +def main(): + # Instantiate a LM35 on analog pin A0, with a default analog + # reference voltage of 5.0 + sensor = sensorObj.LM35(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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every half second, sample the sensor and output the temperature + # Every half second, sample the sensor and output the temperature -while (1): + while (1): print "Temperature:", sensor.getTemperature(), "C" - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/loudness.py b/examples/python/loudness.py old mode 100644 new mode 100755 index 1b4101b1..964c24cf --- a/examples/python/loudness.py +++ b/examples/python/loudness.py @@ -24,27 +24,31 @@ import time, sys, signal, atexit import pyupm_loudness as sensorObj -# Instantiate a Loudness sensor on analog pin A0, with an analog -# reference voltage of 5.0 -sensor = sensorObj.Loudness(0, 5.0) +def main(): + # Instantiate a Loudness sensor on analog pin A0, with an analog + # reference voltage of 5.0 + sensor = sensorObj.Loudness(0, 5.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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every tenth of a second, sample the loudness and output it's -# corresponding analog voltage. + # Every tenth of a second, sample the loudness and output it's + # corresponding analog voltage. -while (1): + while (1): print "Detected loudness (volts): ", sensor.loudness() - time.sleep(.1) + time.sleep(.1) + +if __name__ == '__main__': + main() diff --git a/examples/python/lsm303.py b/examples/python/lsm303.py old mode 100644 new mode 100755 index adc4cd2f..eb74fe3e --- a/examples/python/lsm303.py +++ b/examples/python/lsm303.py @@ -26,62 +26,64 @@ import time, sys, signal, atexit import pyupm_lsm303 as lsm303 -# Instantiate LSM303 compass on I2C -myAccelrCompass = lsm303.LSM303(0) +def main(): + # Instantiate LSM303 compass on I2C + myAccelrCompass = lsm303.LSM303(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myAccelrCompass + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myAccelrCompass -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + # Load coordinates into LSM303 object + successFail = myAccelrCompass.getCoordinates() + # in XYZ order. The sensor returns XZY, + # but the driver compensates and makes it XYZ + coords = myAccelrCompass.getRawCoorData() + # Print out the X, Y, and Z coordinate data + # using two different methods + outputStr = "coor: rX {0} - rY {1} - rZ {2}".format( + coords.__getitem__(0), coords.__getitem__(1), + coords.__getitem__(2)) + print outputStr -while(1): - # Load coordinates into LSM303 object - successFail = myAccelrCompass.getCoordinates() - # in XYZ order. The sensor returns XZY, - # but the driver compensates and makes it XYZ - coords = myAccelrCompass.getRawCoorData() + outputStr = "coor: gX {0} - gY {1} - gZ {2}".format( + myAccelrCompass.getCoorX(), myAccelrCompass.getCoorY(), + myAccelrCompass.getCoorZ()) + print outputStr - # Print out the X, Y, and Z coordinate data - # using two different methods - outputStr = "coor: rX {0} - rY {1} - rZ {2}".format( - coords.__getitem__(0), coords.__getitem__(1), - coords.__getitem__(2)) - print outputStr + # Get and print out the heading + print "heading:", myAccelrCompass.getHeading() - outputStr = "coor: gX {0} - gY {1} - gZ {2}".format( - myAccelrCompass.getCoorX(), myAccelrCompass.getCoorY(), - myAccelrCompass.getCoorZ()) - print outputStr + # Get the acceleration + myAccelrCompass.getAcceleration(); + accel = myAccelrCompass.getRawAccelData(); - # Get and print out the heading - print "heading:", myAccelrCompass.getHeading() + # Print out the X, Y, and Z acceleration data + # using two different methods + outputStr = "acc: rX {0} - rY {1} - Z {2}".format( + accel.__getitem__(0), accel.__getitem__(1), accel.__getitem__(2)) + print outputStr - # Get the acceleration - myAccelrCompass.getAcceleration(); - accel = myAccelrCompass.getRawAccelData(); + outputStr = "acc: gX {0} - gY {1} - gZ {2}".format( + myAccelrCompass.getAccelX(), myAccelrCompass.getAccelY(), + myAccelrCompass.getAccelZ()) + print outputStr - # Print out the X, Y, and Z acceleration data - # using two different methods - outputStr = "acc: rX {0} - rY {1} - Z {2}".format( - accel.__getitem__(0), accel.__getitem__(1), accel.__getitem__(2)) - print outputStr + print " " + time.sleep(1) - outputStr = "acc: gX {0} - gY {1} - gZ {2}".format( - myAccelrCompass.getAccelX(), myAccelrCompass.getAccelY(), - myAccelrCompass.getAccelZ()) - print outputStr - - print " " - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/lsm9ds0.py b/examples/python/lsm9ds0.py old mode 100644 new mode 100755 index 10edc94a..3a739145 --- a/examples/python/lsm9ds0.py +++ b/examples/python/lsm9ds0.py @@ -24,48 +24,52 @@ import time, sys, signal, atexit import pyupm_lsm9ds0 as sensorObj -# Instantiate an LSM9DS0 using default parameters (bus 1, gyro addr 6b, -# xm addr 1d) -sensor = sensorObj.LSM9DS0() +def main(): + # Instantiate an LSM9DS0 using default parameters (bus 1, gyro addr 6b, + # xm addr 1d) + sensor = sensorObj.LSM9DS0() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -sensor.init() + sensor.init() -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() 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 " AZ: ", sensorObj.floatp_value(z) sensor.getGyroscope(x, y, z) - print "Gyroscope: GX: ", sensorObj.floatp_value(x), + print "Gyroscope: GX: ", sensorObj.floatp_value(x), print " GY: ", sensorObj.floatp_value(y), print " GZ: ", sensorObj.floatp_value(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 " MZ: ", sensorObj.floatp_value(z) print "Temperature: ", sensor.getTemperature() print - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/m24lr64e.py b/examples/python/m24lr64e.py old mode 100644 new mode 100755 index 848181e9..4ba94a4a --- a/examples/python/m24lr64e.py +++ b/examples/python/m24lr64e.py @@ -24,26 +24,29 @@ import sys import pyupm_m24lr64e as nfcTagObj -# Instantiate a M24LR64E Grove NFC Tag Module on UART 0 -nfcTag = nfcTagObj.M24LR64E(nfcTagObj.M24LR64E_I2C_BUS) +def main(): + # Instantiate a M24LR64E Grove NFC Tag Module on UART 0 + nfcTag = nfcTagObj.M24LR64E(nfcTagObj.M24LR64E_I2C_BUS) -# This example accesses the device in the 'user' (default) mode, -# reads the last byte of data in the EEPROM, inverts it, writes -# it back, and then re-reads it. + # This example accesses the device in the 'user' (default) mode, + # reads the last byte of data in the EEPROM, inverts it, writes + # it back, and then re-reads it. -# Read the last byte of the EEPROM area -addr = (nfcTagObj.M24LR64E.EEPROM_I2C_LENGTH - 1) -print "Address: ", addr -byte = nfcTag.readByte(addr) + # Read the last byte of the EEPROM area + addr = (nfcTagObj.M24LR64E.EEPROM_I2C_LENGTH - 1) + print "Address: ", addr + byte = nfcTag.readByte(addr) -print "Read byte: ", format(byte, '02x') + print "Read byte: ", format(byte, '02x') -# Now change it to it's opposite and write it -byte = (~byte & 0xff) -nfcTag.writeByte(addr, byte) -print "Wrote inverted byte: ", format(byte, '02x') + # Now change it to it's opposite and write it + byte = (~byte & 0xff) + nfcTag.writeByte(addr, byte) + print "Wrote inverted byte: ", format(byte, '02x') -# Now read it back. -byte = nfcTag.readByte(addr) -print "Read byte: ", format(byte, '02x') + # Now read it back. + byte = nfcTag.readByte(addr) + print "Read byte: ", format(byte, '02x') +if __name__ == '__main__': + main() diff --git a/examples/python/make_oled_pic.py b/examples/python/make_oled_pic.py index 85b3ca0f..a9edb996 100755 --- a/examples/python/make_oled_pic.py +++ b/examples/python/make_oled_pic.py @@ -27,48 +27,52 @@ from __future__ import print_function from PIL import Image import sys -# Pixels are arranged in one byte for 8 vertical pixels and not addressed individually -# We convert the image to greysacle and end up making it monochrome where we -# consider that every pixel that is '40' is black. +def main(): + # Pixels are arranged in one byte for 8 vertical pixels and not addressed individually + # We convert the image to greysacle and end up making it monochrome where we + # consider that every pixel that is '40' is black. -width = 128 -height = 64 + width = 128 + height = 64 -if len(sys.argv) != 2: - print('Please specify an image to use as the only argument') - exit(1) + if len(sys.argv) != 2: + print('Please specify an image to use as the only argument') + exit(1) -im = Image.open(sys.argv[1]) -im = im.convert('L').resize((width, height)) + im = Image.open(sys.argv[1]) + im = im.convert('L').resize((width, height)) -data = list(im.getdata()) + data = list(im.getdata()) -byteblock = [0 for i in range(width)] -widthblock = [list(byteblock) for i in range(int(height/8))] -numblock = 0 -pixcount = 0 -i = 0 + byteblock = [0 for i in range(width)] + widthblock = [list(byteblock) for i in range(int(height/8))] + numblock = 0 + pixcount = 0 + i = 0 -# we split the list by width * 8, to create data chunks of 8rows -datachunks=[data[x:x+(width*8)] for x in range(0, len(data), (width*8))] + # we split the list by width * 8, to create data chunks of 8rows + datachunks=[data[x:x+(width*8)] for x in range(0, len(data), (width*8))] -# grab every pixel of image (or datachunk) -while i < len(widthblock): - pixcount = 0 - for y in datachunks[i]: - xcoor = pixcount % width - ycoor = int(pixcount/width) - blknum = xcoor % len(widthblock) - blkycoor = ycoor + # grab every pixel of image (or datachunk) + while i < len(widthblock): + pixcount = 0 + for y in datachunks[i]: + xcoor = pixcount % width + ycoor = int(pixcount/width) + blknum = xcoor % len(widthblock) + blkycoor = ycoor - # 40 is what we consider 'black' - if y > 40: - widthblock[i][xcoor] |= (1 << blkycoor) + # 40 is what we consider 'black' + if y > 40: + widthblock[i][xcoor] |= (1 << blkycoor) - pixcount += 1 - i += 1 + pixcount += 1 + i += 1 -flatlist = [y for x in widthblock for y in x] + flatlist = [y for x in widthblock for y in x] -carray = 'static uint8_t image[] = {\n' + ', '.join(str(x) for x in flatlist) -print(carray + '\n};') + carray = 'static uint8_t image[] = {\n' + ', '.join(str(x) for x in flatlist) + print(carray + '\n};') + +if __name__ == '__main__': + main() diff --git a/examples/python/maxsonarez.py b/examples/python/maxsonarez.py old mode 100644 new mode 100755 index 645ca58b..d06e215f --- a/examples/python/maxsonarez.py +++ b/examples/python/maxsonarez.py @@ -24,37 +24,40 @@ import time, sys, signal, atexit import pyupm_maxsonarez as MaxSonarEZ -# Instantiate a MaxSonar-EZ on analog pin A1, with an analog -# reference voltage of MAXSONAREZ_AREF -Sonar = MaxSonarEZ.MAXSONAREZ(1) +def main(): + # Instantiate a MaxSonar-EZ on analog pin A1, with an analog + # reference voltage of MAXSONAREZ_AREF + Sonar = MaxSonarEZ.MAXSONAREZ(1) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# This lets you run code on exit, -# including functions from Sonar -def exitHandler(): - print "Exiting" - sys.exit(0) + # This lets you run code on exit, + # including functions from Sonar + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) + # analog voltage, usually 3.3 or 5.0 + MAXSONAREZ_AREF = 5.0; -# analog voltage, usually 3.3 or 5.0 -MAXSONAREZ_AREF = 5.0; + # Every second, sample the sonar and output the distance to an + # object in inches. -# Every second, sample the sonar and output the distance to an -# object in inches. + # With the EZ3 version, the minimum and maximum ranges seemed to be + # between 6 and 33 inches -# With the EZ3 version, the minimum and maximum ranges seemed to be -# between 6 and 33 inches - -while (1): - print "AREF: {0}, distance in inches: {1}".format( + while (1): + print "AREF: {0}, distance in inches: {1}".format( MAXSONAREZ_AREF, Sonar.inches()) - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/md-stepper.py b/examples/python/md-stepper.py old mode 100644 new mode 100755 index 92767b30..0d7c6806 --- a/examples/python/md-stepper.py +++ b/examples/python/md-stepper.py @@ -24,29 +24,32 @@ import time import pyupm_md as upmmd -I2C_BUS = upmmd.MD_I2C_BUS -I2C_ADDR = upmmd.MD_DEFAULT_I2C_ADDR +def main(): + I2C_BUS = upmmd.MD_I2C_BUS + I2C_ADDR = upmmd.MD_DEFAULT_I2C_ADDR -# Instantiate an I2C Motor Driver on I2C bus 0 -myMotorDriver = upmmd.MD(I2C_BUS, I2C_ADDR) + # Instantiate an I2C Motor Driver on I2C bus 0 + myMotorDriver = upmmd.MD(I2C_BUS, I2C_ADDR) -# This example demonstrates using the MD to drive a stepper motor + # This example demonstrates using the MD to drive a stepper motor -# configure it, for this example, we'll assume 200 steps per rev -myMotorDriver.configStepper(200) + # configure it, for this example, we'll assume 200 steps per rev + myMotorDriver.configStepper(200) -# set for half a rotation -myMotorDriver.setStepperSteps(100) + # set for half a rotation + myMotorDriver.setStepperSteps(100) -# let it go - clockwise rotation, 10 RPM speed -myMotorDriver.enableStepper(upmmd.MD.STEP_DIR_CW, 10) + # let it go - clockwise rotation, 10 RPM speed + myMotorDriver.enableStepper(upmmd.MD.STEP_DIR_CW, 10) -time.sleep(3) + time.sleep(3) -# Now do it backwards... -myMotorDriver.setStepperSteps(100) -myMotorDriver.enableStepper(upmmd.MD.STEP_DIR_CCW, 10) + # Now do it backwards... + myMotorDriver.setStepperSteps(100) + myMotorDriver.enableStepper(upmmd.MD.STEP_DIR_CCW, 10) -# now disable -myMotorDriver.disableStepper() + # now disable + myMotorDriver.disableStepper() +if __name__ == '__main__': + main() diff --git a/examples/python/md.py b/examples/python/md.py old mode 100644 new mode 100755 index 4585529c..5146538b --- a/examples/python/md.py +++ b/examples/python/md.py @@ -24,24 +24,27 @@ import time import pyupm_md as upmmd -I2C_BUS = upmmd.MD_I2C_BUS -I2C_ADDR = upmmd.MD_DEFAULT_I2C_ADDR +def main(): + I2C_BUS = upmmd.MD_I2C_BUS + I2C_ADDR = upmmd.MD_DEFAULT_I2C_ADDR -# Instantiate an I2C Motor Driver on I2C bus 0 -myMotorDriver = upmmd.MD(I2C_BUS, I2C_ADDR) + # Instantiate an I2C Motor Driver on I2C bus 0 + myMotorDriver = upmmd.MD(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(upmmd.MD.DIR_CW, upmmd.MD.DIR_CW) + myMotorDriver.setMotorSpeeds(127, 127) -# set direction to CW and set speed to 50% -print "Spin M1 and M2 at half speed for 3 seconds" -myMotorDriver.setMotorDirections(upmmd.MD.DIR_CW, upmmd.MD.DIR_CW) -myMotorDriver.setMotorSpeeds(127, 127) + time.sleep(3) + # counter clockwise + print "Reversing M1 and M2 for 3 seconds" + myMotorDriver.setMotorDirections(upmmd.MD.DIR_CCW, + upmmd.MD.DIR_CCW) + time.sleep(3) -time.sleep(3) -# counter clockwise -print "Reversing M1 and M2 for 3 seconds" -myMotorDriver.setMotorDirections(upmmd.MD.DIR_CCW, -upmmd.MD.DIR_CCW) -time.sleep(3) + print "Stopping motors" + myMotorDriver.setMotorSpeeds(0, 0) -print "Stopping motors" -myMotorDriver.setMotorSpeeds(0, 0) +if __name__ == '__main__': + main() diff --git a/examples/python/mg811.py b/examples/python/mg811.py old mode 100644 new mode 100755 index 78a75d80..8d5cc12f --- a/examples/python/mg811.py +++ b/examples/python/mg811.py @@ -24,28 +24,32 @@ import time, sys, signal, atexit import pyupm_mg811 as sensorObj -# Instantiate an MG811 on analog pin A0, and digital pin D2 with an -# analog reference voltage of MG811_AREF (5.0) +def main(): + # Instantiate an MG811 on analog pin A0, and digital pin D2 with an + # analog reference voltage of MG811_AREF (5.0) -sensor = sensorObj.MG811(0, 2, 5.0) + sensor = sensorObj.MG811(0, 2, 5.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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every tenth of a second, sample the sensor and output it's -# detected CO2 concentration in parts per million (ppm) + # Every tenth of a second, sample the sensor and output it's + # detected CO2 concentration in parts per million (ppm) -while (1): + while (1): print "CO2 concentration in PPM: ", sensor.ppm() - time.sleep(.1) + time.sleep(.1) + +if __name__ == '__main__': + main() diff --git a/examples/python/mhz16.py b/examples/python/mhz16.py old mode 100644 new mode 100755 index 4fa0615a..912d71c4 --- a/examples/python/mhz16.py +++ b/examples/python/mhz16.py @@ -24,47 +24,49 @@ import time, sys, signal, atexit import pyupm_mhz16 as upmMhz16 -# Instantiate a MHZ16 serial CO2 sensor on uart 0. -# This example was tested on the Grove CO2 sensor module. -myCO2 = upmMhz16.MHZ16(0) +def main(): + # Instantiate a MHZ16 serial CO2 sensor on uart 0. + # This example was tested on the Grove CO2 sensor module. + myCO2 = upmMhz16.MHZ16(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myCO2 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myCO2 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # make sure port is initialized properly. 9600 baud is the default. + if (not myCO2.setupTty(upmMhz16.cvar.int_B9600)): + print "Failed to setup tty port parameters" + sys.exit(0) + print ("Make sure that the sensor has had " + "at least 3 minutes to warm up\n" + "or you will not get valid results.\n" + "The temperature reported is not the ambient temperature,\n" + "but rather the temperature of the sensor elements.") -# make sure port is initialized properly. 9600 baud is the default. -if (not myCO2.setupTty(upmMhz16.cvar.int_B9600)): - print "Failed to setup tty port parameters" - sys.exit(0) + time.sleep(1) -print ("Make sure that the sensor has had " -"at least 3 minutes to warm up\n" -"or you will not get valid results.\n" -"The temperature reported is not the ambient temperature,\n" -"but rather the temperature of the sensor elements.") + while(1): + if (not myCO2.getData()): + print "Failed to retrieve data" + else: + outputStr = ("CO2 concentration: {0} PPM, " + "Temperature (in C): {1}".format( + myCO2.getGas(), myCO2.getTemperature())) + print outputStr -time.sleep(1) + time.sleep(2) -while(1): - if (not myCO2.getData()): - print "Failed to retrieve data" - else: - outputStr = ("CO2 concentration: {0} PPM, " - "Temperature (in C): {1}".format( - myCO2.getGas(), myCO2.getTemperature())) - print outputStr - - time.sleep(2) +if __name__ == '__main__': + main() diff --git a/examples/python/mic.py b/examples/python/mic.py old mode 100644 new mode 100755 index 240d61e8..86a73c58 --- a/examples/python/mic.py +++ b/examples/python/mic.py @@ -21,27 +21,31 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import time -import pyupm_mic as upmMicrophone +import pyupm_mic as upmMicrophone -# Attach microphone to analog port A0 -myMic = upmMicrophone.Microphone(0) -threshContext = upmMicrophone.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 +def main(): + # Attach microphone to analog port A0 + myMic = upmMicrophone.Microphone(0) + threshContext = upmMicrophone.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of dots as averages -while(1): - buffer = upmMicrophone.uint16Array(128) - len = myMic.getSampledWindow(2, 128, buffer); - if len: - thresh = myMic.findThreshold(threshContext, 30, buffer, len) - myMic.printGraph(threshContext) - if(thresh): - print "Threshold is ", thresh + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of dots as averages + while(1): + buffer = upmMicrophone.uint16Array(128) + len = myMic.getSampledWindow(2, 128, buffer); + if len: + thresh = myMic.findThreshold(threshContext, 30, buffer, len) + myMic.printGraph(threshContext) + if(thresh): + print "Threshold is ", thresh -# Delete the upmMicrophone object -del myMic + # Delete the upmMicrophone object + del myMic + +if __name__ == '__main__': + main() diff --git a/examples/python/mma7361.py b/examples/python/mma7361.py old mode 100644 new mode 100755 index 43b57601..404282a1 --- a/examples/python/mma7361.py +++ b/examples/python/mma7361.py @@ -24,35 +24,36 @@ import time, sys, signal, atexit import pyupm_mma7361 as sensorObj -# Instantiate a MMA7361 sensor on analog pins A0 (X), A1 (Y) A2 -# (Z), selftest pin on D2, sleep pin on D3 nd an analog reference -# value of 5.0. The freefall pin and the range pin are unused -# (-1). -sensor = sensorObj.MMA7361(0, 1, 2, 2, 3, -1, -1, 5.0) +def main(): + # Instantiate a MMA7361 sensor on analog pins A0 (X), A1 (Y) A2 + # (Z), selftest pin on D2, sleep pin on D3 nd an analog reference + # value of 5.0. The freefall pin and the range pin are unused + # (-1). + sensor = sensorObj.MMA7361(0, 1, 2, 2, 3, -1, -1, 5.0) -# 1.5g (true = 6g) -sensor.setRange(False) + # 1.5g (true = 6g) + sensor.setRange(False) -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -# Every 10th of a second, update and print values -while (1): + # Every 10th of a second, update and print values + while (1): sensor.update() sensor.getAcceleration(x, y, z) @@ -66,4 +67,7 @@ while (1): print " z:", sensorObj.floatp_value(z) print - time.sleep(.100) + time.sleep(.100) + +if __name__ == '__main__': + main() diff --git a/examples/python/mma7660.py b/examples/python/mma7660.py old mode 100644 new mode 100755 index 1471a60d..b807581c --- a/examples/python/mma7660.py +++ b/examples/python/mma7660.py @@ -24,58 +24,60 @@ import time, sys, signal, atexit import pyupm_mma7660 as upmMMA7660 -# Instantiate an MMA7660 on I2C bus 0 -myDigitalAccelerometer = upmMMA7660.MMA7660( - upmMMA7660.MMA7660_I2C_BUS, - upmMMA7660.MMA7660_DEFAULT_I2C_ADDR); +def main(): + # Instantiate an MMA7660 on I2C bus 0 + myDigitalAccelerometer = upmMMA7660.MMA7660( + upmMMA7660.MMA7660_I2C_BUS, + upmMMA7660.MMA7660_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 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, including functions from myDigitalAccelerometer + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myDigitalAccelerometer -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # place device in standby mode so we can write registers + myDigitalAccelerometer.setModeStandby() + # enable 64 samples per second + myDigitalAccelerometer.setSampleRate(upmMMA7660.MMA7660.AUTOSLEEP_64) -# place device in standby mode so we can write registers -myDigitalAccelerometer.setModeStandby() + # place device into active mode + myDigitalAccelerometer.setModeActive() -# enable 64 samples per second -myDigitalAccelerometer.setSampleRate(upmMMA7660.MMA7660.AUTOSLEEP_64) + x = upmMMA7660.new_intp() + y = upmMMA7660.new_intp() + z = upmMMA7660.new_intp() -# place device into active mode -myDigitalAccelerometer.setModeActive() + ax = upmMMA7660.new_floatp() + ay = upmMMA7660.new_floatp() + az = upmMMA7660.new_floatp() -x = upmMMA7660.new_intp() -y = upmMMA7660.new_intp() -z = upmMMA7660.new_intp() + while (1): + myDigitalAccelerometer.getRawValues(x, y, z) + outputStr = ("Raw values: x = {0}" + " y = {1}" + " z = {2}").format(upmMMA7660.intp_value(x), + upmMMA7660.intp_value(y), + upmMMA7660.intp_value(z)) + print outputStr -ax = upmMMA7660.new_floatp() -ay = upmMMA7660.new_floatp() -az = upmMMA7660.new_floatp() + myDigitalAccelerometer.getAcceleration(ax, ay, az) + outputStr = ("Acceleration: x = {0}" + "g y = {1}" + "g z = {2}g").format(upmMMA7660.floatp_value(ax), + upmMMA7660.floatp_value(ay), + upmMMA7660.floatp_value(az)) + print outputStr + time.sleep(.5) -while (1): - myDigitalAccelerometer.getRawValues(x, y, z) - outputStr = ("Raw values: x = {0}" - " y = {1}" - " z = {2}").format(upmMMA7660.intp_value(x), - upmMMA7660.intp_value(y), - upmMMA7660.intp_value(z)) - print outputStr - - myDigitalAccelerometer.getAcceleration(ax, ay, az) - outputStr = ("Acceleration: x = {0}" - "g y = {1}" - "g z = {2}g").format(upmMMA7660.floatp_value(ax), - upmMMA7660.floatp_value(ay), - upmMMA7660.floatp_value(az)) - print outputStr - time.sleep(.5) +if __name__ == '__main__': + main() diff --git a/examples/python/moisture.py b/examples/python/moisture.py old mode 100644 new mode 100755 index 1723d3e8..18579152 --- a/examples/python/moisture.py +++ b/examples/python/moisture.py @@ -24,38 +24,40 @@ import time, sys, signal, atexit import pyupm_moisture as upmMoisture -# Instantiate a Grove Moisture sensor on analog pin A0 -myMoisture = upmMoisture.Moisture(0) +def main(): + # Instantiate a Grove Moisture sensor on analog pin A0 + myMoisture = upmMoisture.Moisture(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 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, including functions from myMoisture + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMoisture -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Values (approximate): + # 0-300, sensor in air or dry soil + # 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): -# 0-300, sensor in air or dry soil -# 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) +if __name__ == '__main__': + main() diff --git a/examples/python/mpr121.py b/examples/python/mpr121.py old mode 100644 new mode 100755 index 8e382629..cb0df5a5 --- a/examples/python/mpr121.py +++ b/examples/python/mpr121.py @@ -24,50 +24,51 @@ import time, sys, signal, atexit import pyupm_mpr121 as upmMpr121 -I2C_BUS = upmMpr121.MPR121_I2C_BUS -DEFAULT_I2C_ADDR = upmMpr121.MPR121_DEFAULT_I2C_ADDR +def main(): + I2C_BUS = upmMpr121.MPR121_I2C_BUS + DEFAULT_I2C_ADDR = upmMpr121.MPR121_DEFAULT_I2C_ADDR -# Instantiate an MPR121 touch sensor on I2C -myTouchSensor = upmMpr121.MPR121(I2C_BUS, DEFAULT_I2C_ADDR) + # Instantiate an MPR121 touch sensor on I2C + myTouchSensor = upmMpr121.MPR121(I2C_BUS, DEFAULT_I2C_ADDR) + + ## Exit handlers ## + # 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, + # including functions from myTouchSensor + def exitHandler(): + print "Exiting" + sys.exit(0) + + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + def printButtons(touchSensor): + buttonPressed = False -# This function lets you run code on exit, -# including functions from myTouchSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + outputStr = "Buttons Pressed: " + for i in range(12): + if (touchSensor.m_buttonStates & (1 << i)): + outputStr += (str(i) + " ") + buttonPressed = True -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + if (not buttonPressed): + outputStr += "None" + print outputStr + if (touchSensor.m_overCurrentFault): + print "Over Current Fault detected!" -def printButtons(touchSensor): - buttonPressed = False + while(1): + myTouchSensor.readButtons() + printButtons(myTouchSensor) - outputStr = "Buttons Pressed: " - for i in range(12): - if (touchSensor.m_buttonStates & (1 << i)): - outputStr += (str(i) + " ") - buttonPressed = True + time.sleep(1) - if (not buttonPressed): - outputStr += "None" - - print outputStr - - if (touchSensor.m_overCurrentFault): - print "Over Current Fault detected!" - - -while(1): - myTouchSensor.readButtons() - printButtons(myTouchSensor) - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/mpu60x0.py b/examples/python/mpu60x0.py old mode 100644 new mode 100755 index 009e3eea..a9d5df8c --- a/examples/python/mpu60x0.py +++ b/examples/python/mpu60x0.py @@ -24,42 +24,46 @@ import time, sys, signal, atexit import pyupm_mpu9150 as sensorObj -# Instantiate an MPU60X0 on I2C bus 0 -sensor = sensorObj.MPU60X0() +def main(): + # Instantiate an MPU60X0 on I2C bus 0 + sensor = sensorObj.MPU60X0() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -sensor.init() + sensor.init() -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() 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 " AZ: ", sensorObj.floatp_value(z) sensor.getGyroscope(x, y, z) - print "Gyroscope: GX: ", sensorObj.floatp_value(x), + print "Gyroscope: GX: ", sensorObj.floatp_value(x), print " GY: ", sensorObj.floatp_value(y), print " GZ: ", sensorObj.floatp_value(z) print "Temperature: ", sensor.getTemperature() print - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/mpu9150.py b/examples/python/mpu9150.py old mode 100644 new mode 100755 index bba54b0e..20c3b088 --- a/examples/python/mpu9150.py +++ b/examples/python/mpu9150.py @@ -24,47 +24,51 @@ import time, sys, signal, atexit import pyupm_mpu9150 as sensorObj -# Instantiate an MPU9150 on I2C bus 0 -sensor = sensorObj.MPU9150() +def main(): + # Instantiate an MPU9150 on I2C bus 0 + sensor = sensorObj.MPU9150() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -sensor.init() + sensor.init() -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() 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 " AZ: ", sensorObj.floatp_value(z) sensor.getGyroscope(x, y, z) - print "Gyroscope: GX: ", sensorObj.floatp_value(x), + print "Gyroscope: GX: ", sensorObj.floatp_value(x), print " GY: ", sensorObj.floatp_value(y), print " GZ: ", sensorObj.floatp_value(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 " MZ: ", sensorObj.floatp_value(z) print "Temperature: ", sensor.getTemperature() print - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/mpu9250.py b/examples/python/mpu9250.py old mode 100644 new mode 100755 index 1653846a..83ca52c6 --- a/examples/python/mpu9250.py +++ b/examples/python/mpu9250.py @@ -24,47 +24,51 @@ import time, sys, signal, atexit import pyupm_mpu9150 as sensorObj -# Instantiate an MPU9250 on I2C bus 0 -sensor = sensorObj.MPU9250() +def main(): + # Instantiate an MPU9250 on I2C bus 0 + sensor = sensorObj.MPU9250() -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -sensor.init() + sensor.init() -x = sensorObj.new_floatp() -y = sensorObj.new_floatp() -z = sensorObj.new_floatp() + x = sensorObj.new_floatp() + y = sensorObj.new_floatp() + z = sensorObj.new_floatp() -while (1): + while (1): sensor.update() 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 " AZ: ", sensorObj.floatp_value(z) sensor.getGyroscope(x, y, z) - print "Gyroscope: GX: ", sensorObj.floatp_value(x), + print "Gyroscope: GX: ", sensorObj.floatp_value(x), print " GY: ", sensorObj.floatp_value(y), print " GZ: ", sensorObj.floatp_value(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 " MZ: ", sensorObj.floatp_value(z) print "Temperature: ", sensor.getTemperature() print - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/mq2.py b/examples/python/mq2.py old mode 100644 new mode 100755 index 3073fda1..aa6d3560 --- a/examples/python/mq2.py +++ b/examples/python/mq2.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGas -# Attach gas sensor to AIO0 -myMQ2 = upmGas.MQ2(0); +def main(): + # Attach gas sensor to AIO0 + myMQ2 = upmGas.MQ2(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 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, including functions from myMQ2 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMQ2 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGas.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of dots as averages + mybuffer = upmGas.uint16Array(128) + while(1): + samplelen = myMQ2.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = myMQ2.findThreshold(threshContext, 30, mybuffer, samplelen) + myMQ2.printGraph(threshContext, 5) + if(thresh): + print "Threshold is ", thresh -threshContext = upmGas.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of dots as averages -mybuffer = upmGas.uint16Array(128) -while(1): - samplelen = myMQ2.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = myMQ2.findThreshold(threshContext, 30, mybuffer, samplelen) - myMQ2.printGraph(threshContext, 5) - if(thresh): - print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq3.py b/examples/python/mq3.py old mode 100644 new mode 100755 index c464cfc3..6311963f --- a/examples/python/mq3.py +++ b/examples/python/mq3.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGas -# Attach gas sensor to AIO0 -myMQ3 = upmGas.MQ3(0) +def main(): + # Attach gas sensor to AIO0 + myMQ3 = upmGas.MQ3(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 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, including functions from myMQ3 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMQ3 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGas.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of dots as averages + mybuffer = upmGas.uint16Array(128) + while(1): + samplelen = myMQ3.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = myMQ3.findThreshold(threshContext, 30, mybuffer, samplelen) + myMQ3.printGraph(threshContext, 5) + if(thresh): + print "Threshold is ", thresh -threshContext = upmGas.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of dots as averages -mybuffer = upmGas.uint16Array(128) -while(1): - samplelen = myMQ3.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = myMQ3.findThreshold(threshContext, 30, mybuffer, samplelen) - myMQ3.printGraph(threshContext, 5) - if(thresh): - print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq303a.py b/examples/python/mq303a.py old mode 100644 new mode 100755 index de71bcf5..0f5fc4f6 --- a/examples/python/mq303a.py +++ b/examples/python/mq303a.py @@ -26,50 +26,52 @@ import time, sys, signal, atexit # Load alcohol sensor module import pyupm_mq303a as upmMq303a -# Instantiate an mq303a sensor on analog pin A0 -# This device uses a heater powered from an analog I/O pin. -# If using A0 as the data pin, then you need to use A1, as the heater -# pin (if using a grove mq303a). For A1, we can use the D15 gpio, -# setup as an output, and drive it low to power the heater. -myAlcoholSensor = upmMq303a.MQ303A(0, 15) +def main(): + # Instantiate an mq303a sensor on analog pin A0 + # This device uses a heater powered from an analog I/O pin. + # If using A0 as the data pin, then you need to use A1, as the heater + # pin (if using a grove mq303a). For A1, we can use the D15 gpio, + # setup as an output, and drive it low to power the heater. + myAlcoholSensor = upmMq303a.MQ303A(0, 15) + ## 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 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, including functions from myAlcoholSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myAlcoholSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + print "Enabling heater and waiting 2 minutes for warmup." + # give time updates every 30 seconds until 2 minutes have passed + # for the alcohol sensor to warm up + def warmup(iteration): + totalSeconds = (30 * iteration) + time.sleep(30) + print totalSeconds, "seconds have passed" + warmup(1) + warmup(2) + warmup(3) + warmup(4) -print "Enabling heater and waiting 2 minutes for warmup." + notice = ("This sensor may need to warm " + "until the value drops below about 450.") + print notice -# give time updates every 30 seconds until 2 minutes have passed -# for the alcohol sensor to warm up -def warmup(iteration): - totalSeconds = (30 * iteration) - time.sleep(30) - print totalSeconds, "seconds have passed" -warmup(1) -warmup(2) -warmup(3) -warmup(4) + # Print the detected alcohol value every second + while(1): + val = myAlcoholSensor.value() + msg = "Alcohol detected " + msg += "(higher means stronger alcohol): " + print msg + str(val) + time.sleep(1) -notice = ("This sensor may need to warm " -"until the value drops below about 450.") -print notice - -# Print the detected alcohol value every second -while(1): - val = myAlcoholSensor.value() - msg = "Alcohol detected " - msg += "(higher means stronger alcohol): " - print msg + str(val) - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/mq4.py b/examples/python/mq4.py old mode 100644 new mode 100755 index 579246ba..a4dd4372 --- a/examples/python/mq4.py +++ b/examples/python/mq4.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGAS -# Attach gas sensor to Analog A0 -sensor = upmGAS.MQ4(0) +def main(): + # Attach gas sensor to Analog A0 + sensor = upmGAS.MQ4(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 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, including functions from sensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from sensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGAS.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of asteriskss as averages + mybuffer = upmGAS.uint16Array(128) + while(1): + samplelen = sensor.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) + sensor.printGraph(threshContext, 5) + # if(thresh): + # print "Threshold is ", thresh -threshContext = upmGAS.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of asteriskss as averages -mybuffer = upmGAS.uint16Array(128) -while(1): - samplelen = sensor.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) - sensor.printGraph(threshContext, 5) -# if(thresh): -# print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq5.py b/examples/python/mq5.py old mode 100644 new mode 100755 index 5e7deb84..67e0f58f --- a/examples/python/mq5.py +++ b/examples/python/mq5.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGas -# Attach gas sensor to AIO0 -myMQ5 = upmGas.MQ5(0) +def main(): + # Attach gas sensor to AIO0 + myMQ5 = upmGas.MQ5(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 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, including functions from myMQ5 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMQ5 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGas.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of dots as averages + mybuffer = upmGas.uint16Array(128) + while(1): + samplelen = myMQ5.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = myMQ5.findThreshold(threshContext, 30, mybuffer, samplelen) + myMQ5.printGraph(threshContext, 5) + if(thresh): + print "Threshold is ", thresh -threshContext = upmGas.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of dots as averages -mybuffer = upmGas.uint16Array(128) -while(1): - samplelen = myMQ5.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = myMQ5.findThreshold(threshContext, 30, mybuffer, samplelen) - myMQ5.printGraph(threshContext, 5) - if(thresh): - print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq6.py b/examples/python/mq6.py old mode 100644 new mode 100755 index 8788e232..cb34d40a --- a/examples/python/mq6.py +++ b/examples/python/mq6.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGAS -# Attach gas sensor to Analog A0 -sensor = upmGAS.MQ6(0) +def main(): + # Attach gas sensor to Analog A0 + sensor = upmGAS.MQ6(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 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, including functions from sensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from sensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGAS.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of asteriskss as averages + mybuffer = upmGAS.uint16Array(128) + while(1): + samplelen = sensor.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) + sensor.printGraph(threshContext, 5) + # if(thresh): + # print "Threshold is ", thresh -threshContext = upmGAS.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of asteriskss as averages -mybuffer = upmGAS.uint16Array(128) -while(1): - samplelen = sensor.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) - sensor.printGraph(threshContext, 5) -# if(thresh): -# print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq7.py b/examples/python/mq7.py old mode 100644 new mode 100755 index 62a90565..b01df389 --- a/examples/python/mq7.py +++ b/examples/python/mq7.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGAS -# Attach gas sensor to Analog A0 -sensor = upmGAS.MQ7(0) +def main(): + # Attach gas sensor to Analog A0 + sensor = upmGAS.MQ7(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 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, including functions from sensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from sensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGAS.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of asteriskss as averages + mybuffer = upmGAS.uint16Array(128) + while(1): + samplelen = sensor.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) + sensor.printGraph(threshContext, 5) + # if(thresh): + # print "Threshold is ", thresh -threshContext = upmGAS.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of asteriskss as averages -mybuffer = upmGAS.uint16Array(128) -while(1): - samplelen = sensor.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) - sensor.printGraph(threshContext, 5) -# if(thresh): -# print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq8.py b/examples/python/mq8.py old mode 100644 new mode 100755 index 5380018f..483c4da6 --- a/examples/python/mq8.py +++ b/examples/python/mq8.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGAS -# Attach gas sensor to Analog A0 -sensor = upmGAS.MQ8(0) +def main(): + # Attach gas sensor to Analog A0 + sensor = upmGAS.MQ8(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 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, including functions from sensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from sensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGAS.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of asteriskss as averages + mybuffer = upmGAS.uint16Array(128) + while(1): + samplelen = sensor.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) + sensor.printGraph(threshContext, 5) + # if(thresh): + # print "Threshold is ", thresh -threshContext = upmGAS.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of asteriskss as averages -mybuffer = upmGAS.uint16Array(128) -while(1): - samplelen = sensor.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = sensor.findThreshold(threshContext, 30, mybuffer, samplelen) - sensor.printGraph(threshContext, 5) -# if(thresh): -# print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/mq9.py b/examples/python/mq9.py old mode 100644 new mode 100755 index f39cf396..48d720f0 --- a/examples/python/mq9.py +++ b/examples/python/mq9.py @@ -24,39 +24,41 @@ import time, sys, signal, atexit import pyupm_gas as upmGas -# Attach gas sensor to AIO0 -myMQ9 = upmGas.MQ9(0) +def main(): + # Attach gas sensor to AIO0 + myMQ9 = upmGas.MQ9(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 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, including functions from myMQ9 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myMQ9 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + threshContext = upmGas.thresholdContext() + threshContext.averageReading = 0 + threshContext.runningAverage = 0 + threshContext.averagedOver = 2 + # Infinite loop, ends when script is cancelled + # Repeatedly, take a sample every 2 microseconds; + # find the average of 128 samples; and + # print a running graph of dots as averages + mybuffer = upmGas.uint16Array(128) + while(1): + samplelen = myMQ9.getSampledWindow(2, 128, mybuffer) + if samplelen: + thresh = myMQ9.findThreshold(threshContext, 30, mybuffer, samplelen) + myMQ9.printGraph(threshContext, 5) + if(thresh): + print "Threshold is ", thresh -threshContext = upmGas.thresholdContext() -threshContext.averageReading = 0 -threshContext.runningAverage = 0 -threshContext.averagedOver = 2 - -# Infinite loop, ends when script is cancelled -# Repeatedly, take a sample every 2 microseconds; -# find the average of 128 samples; and -# print a running graph of dots as averages -mybuffer = upmGas.uint16Array(128) -while(1): - samplelen = myMQ9.getSampledWindow(2, 128, mybuffer) - if samplelen: - thresh = myMQ9.findThreshold(threshContext, 30, mybuffer, samplelen) - myMQ9.printGraph(threshContext, 5) - if(thresh): - print "Threshold is ", thresh +if __name__ == '__main__': + main() diff --git a/examples/python/nlgpio16.py b/examples/python/nlgpio16.py old mode 100644 new mode 100755 index 7be815d1..97b60cd3 --- a/examples/python/nlgpio16.py +++ b/examples/python/nlgpio16.py @@ -24,28 +24,32 @@ import sys, signal, atexit import pyupm_nlgpio16 as sensorObj -# Instantiate a NLGPIO16 Module on the default UART (/dev/ttyACM0) -sensor = sensorObj.NLGPIO16() +def main(): + # Instantiate a NLGPIO16 Module on the default UART (/dev/ttyACM0) + sensor = sensorObj.NLGPIO16() -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# get the Version -print "Device Version:", sensor.getVersion() -# read the gpio at pin 3 -print "GPIO 3 Value:", sensor.gpioRead(3) -# read the analog voltage at pin 5 -print "Analog 5 Voltage:", sensor.analogReadVolts(5) -# set the gpio at pin 14 to HIGH -sensor.gpioSet(14) + # get the Version + print "Device Version:", sensor.getVersion() + # read the gpio at pin 3 + print "GPIO 3 Value:", sensor.gpioRead(3) + # read the analog voltage at pin 5 + print "Analog 5 Voltage:", sensor.analogReadVolts(5) + # set the gpio at pin 14 to HIGH + sensor.gpioSet(14) + +if __name__ == '__main__': + main() diff --git a/examples/python/nmea_gps.py b/examples/python/nmea_gps.py old mode 100644 new mode 100755 index 7b54a733..38a32452 --- a/examples/python/nmea_gps.py +++ b/examples/python/nmea_gps.py @@ -24,26 +24,30 @@ import time, sys, signal, atexit import pyupm_nmea_gps as sensorObj -# Instantiate a NMEAGPS sensor on uart 0 at 9600 baud with enable -# pin on D3 -sensor = sensorObj.NMEAGPS(0, 9600, 3) +def main(): + # Instantiate a NMEAGPS sensor on uart 0 at 9600 baud with enable + # pin on D3 + sensor = sensorObj.NMEAGPS(0, 9600, 3) -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# loop, dumping NMEA data out as fast as it comes in -while (sensor.dataAvailable(5000)): + # loop, dumping NMEA data out as fast as it comes in + while (sensor.dataAvailable(5000)): sys.stdout.write(sensor.readStr(256)) -print "Timed out" + print "Timed out" + +if __name__ == '__main__': + main() diff --git a/examples/python/nmea_gps_i2c.py b/examples/python/nmea_gps_i2c.py old mode 100644 new mode 100755 index b91fc6de..a9491795 --- a/examples/python/nmea_gps_i2c.py +++ b/examples/python/nmea_gps_i2c.py @@ -24,28 +24,31 @@ import time, sys, signal, atexit import pyupm_nmea_gps as sensorObj -# Instantiate a NMEA_GPS UBLOX based i2c sensor on i2c bus 0 at -# address 0x42 -sensor = sensorObj.NMEAGPS(0, 0x42) +def main(): + # Instantiate a NMEA_GPS UBLOX based i2c sensor on i2c bus 0 at + # address 0x42 + sensor = sensorObj.NMEAGPS(0, 0x42) -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# loop, dumping NMEA data out as fast as it comes in -while (True): + # loop, dumping NMEA data out as fast as it comes in + while (True): if (sensor.dataAvailable(0)): - sys.stdout.write(sensor.readStr(256)) + sys.stdout.write(sensor.readStr(256)) else: - time.sleep(.1) + time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/nunchuck.py b/examples/python/nunchuck.py old mode 100644 new mode 100755 index f7bc2615..7cf22368 --- a/examples/python/nunchuck.py +++ b/examples/python/nunchuck.py @@ -24,50 +24,52 @@ import time, sys, signal, atexit import pyupm_nunchuck as upmNunchuck -# Instantiate a nunchuck controller bus 0 on I2C -myNunchuck = upmNunchuck.NUNCHUCK(0) +def main(): + # Instantiate a nunchuck controller bus 0 on I2C + myNunchuck = upmNunchuck.NUNCHUCK(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 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, including functions from myNunchuck + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myNunchuck -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # always do this first + print "Initializing... " + if (not myNunchuck.init()): + print "nunchuck->init() failed." + sys.exit(0); + def buttonStateStr(buttonState): + return "pressed" if buttonState else "not pressed" -# always do this first -print "Initializing... " -if (not myNunchuck.init()): - print "nunchuck->init() failed." - sys.exit(0); + # Print the X and Y input values every second + while(1): + myNunchuck.update() -def buttonStateStr(buttonState): - return "pressed" if buttonState else "not pressed" + outputStr = "stickX: {0}, stickY: {1}".format( + myNunchuck.stickX, myNunchuck.stickY) + print outputStr + outputStr = "accelX: {0}, accelY: {1}, accelZ: {2}".format( + myNunchuck.accelX, myNunchuck.accelY, myNunchuck.accelZ) + print outputStr -# Print the X and Y input values every second -while(1): - myNunchuck.update() + outputStr = "button C: {0}".format( + buttonStateStr(myNunchuck.buttonC)) + print outputStr + outputStr = "button Z: {0}".format( + buttonStateStr(myNunchuck.buttonZ)) + print outputStr - outputStr = "stickX: {0}, stickY: {1}".format( - myNunchuck.stickX, myNunchuck.stickY) - print outputStr - outputStr = "accelX: {0}, accelY: {1}, accelZ: {2}".format( - myNunchuck.accelX, myNunchuck.accelY, myNunchuck.accelZ) - print outputStr + time.sleep(.1) - outputStr = "button C: {0}".format( - buttonStateStr(myNunchuck.buttonC)) - print outputStr - outputStr = "button Z: {0}".format( - buttonStateStr(myNunchuck.buttonZ)) - print outputStr - - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/o2.py b/examples/python/o2.py old mode 100644 new mode 100755 index 55c34849..f29c9daf --- a/examples/python/o2.py +++ b/examples/python/o2.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_o2 as upmO2 -# This was tested with the O2 Oxygen Concentration Sensor Module -# Instantiate a O2 on analog pin A0 -myO2 = upmO2.O2(0) +def main(): + # This was tested with the O2 Oxygen Concentration Sensor Module + # Instantiate a O2 on analog pin A0 + myO2 = upmO2.O2(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myO2 + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myO2 -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + print "The output voltage is: {0}mV".format( + myO2.voltageValue()) + time.sleep(.1) -while(1): - print "The output voltage is: {0}mV".format( - myO2.voltageValue()) - - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/oled_ssd1308.py b/examples/python/oled_ssd1308.py old mode 100644 new mode 100755 index 9ea1443d..af4bf5b0 --- a/examples/python/oled_ssd1308.py +++ b/examples/python/oled_ssd1308.py @@ -25,71 +25,75 @@ import time, signal, sys import pyupm_i2clcd as upmLCD -myLCD = upmLCD.SSD1308(0, 0x3C); +def main(): + myLCD = upmLCD.SSD1308(0, 0x3C); -logoArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 192, 192, 192, 224, -224, 224, 224, 240, 240, 248, 248, 120, 120, 120, 120, 60, 60, 60, 60, 60, -62, 30, 30, 30, 30, 30, 30, 30, 31, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 31, 31, 31, 31, 31, -30, 62, 62, 62, 62, 126, 126, 124, 124, 252, 252, 248, 248, 240, 240, 240, -224, 224, 224, 192, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, -128, 0, 56, 56, 28, 30, 14, 15, 15, 7, 7, 7, 7, 3, 3, 1, 1, 1, 1, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 192, 193, 195, 195, -195, 7, 15, 15, 63, 127, 255, 255, 255, 254, 252, 252, 240, 192, 0, 0, 0, -0, 0, 0, 0, 0, 128, 192, 192, 240, 248, 124, 124, 60, 0, 0, 0, 0, 159, 159, -159, 159, 159, 159, 159, 159, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, -128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, -0, 0, 0, 0, 254, 254, 254, 254, 254, 254, 254, 254, 128, 128, 128, 128, -128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 192, 192, 192, 192, 192, 192, 128, -128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, -0, 0, 0, 0, 3, 7, 3, 3, 3, 0, 0, 0, 0, 0, 1, 1, 255, 255, 255, 255, 255, -255, 255, 0, 0, 224, 248, 252, 252, 255, 127, 15, 15, 3, 1, 0, 0, 0, 0, 0, -0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, -255, 255, 255, 255, 255, 15, 15, 15, 15, 15, 15, 255, 255, 255, 255, 255, -255, 255, 252, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 15, 15, -15, 15, 15, 224, 224, 252, 254, 255, 255, 255, 255, 159, 159, 143, 143, -135, 135, 143, 159, 255, 255, 255, 255, 255, 255, 252, 248, 0, 0, 0, 255, -255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, -224, 248, 248, 255, 255, 255, 255, 255, 127, 15, 255, 255, 255, 255, 255, -255, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, -255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, -0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, -255, 255, 255, 255, 255, 192, 192, 192, 192, 192, 31, 31, 255, 255, 255, -255, 255, 255, 231, 231, 199, 199, 199, 199, 199, 199, 199, 199, 231, 231, -231, 231, 199, 135, 0, 0, 0, 63, 255, 255, 255, 255, 255, 255, 255, 0, 0, -0, 0, 224, 240, 248, 248, 252, 254, 255, 255, 255, 127, 63, 63, 31, 15, 7, -7, 1, 0, 0, 63, 63, 255, 255, 255, 255, 255, 240, 192, 192, 128, 0, 0, 0, -0, 0, 0, 0, 0, 1, 3, 3, 7, 7, 7, 7, 7, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, -0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 3, 3, 7, 7, 7, -7, 7, 7, 7, 7, 7, 0, 0, 0, 1, 3, 3, 3, 7, 7, 7, 7, 15, 15, 15, 15, 7, 7, 7, -7, 7, 3, 3, 3, 1, 0, 0, 0, 0, 1, 3, 3, 7, 135, 135, 135, 192, 192, 0, 0, 7, -7, 3, 3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 15, 15, -31, 127, 127, 127, 255, 255, 252, 252, 252, 248, 240, 240, 240, 224, 224, -224, 192, 192, 192, 192, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 192, 192, 192, 192, 192, -224, 224, 224, 224, 240, 240, 240, 240, 248, 248, 248, 248, 252, 252, 252, -254, 254, 255, 255, 255, 255, 255, 255, 127, 127, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -3, 3, 3, 7, 7, 7, 15, 15, 31, 31, 31, 63, 63, 63, 63, 63, 127, 127, 127, -127, 127, 255, 255, 255, 255, 254, 254, 254, 254, 254, 254, 254, 254, 254, -254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, -255, 255, 255, 255, 255, 255, 255, 127, 127, 127, 127, 127, 127, 127, 127, -63, 63, 63, 63, 63, 31, 31, 31, 31, 31, 15, 15, 15, 15, 7, 7, 7, 7, 3, 3, -3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0] + logoArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 192, 192, 192, 224, + 224, 224, 224, 240, 240, 248, 248, 120, 120, 120, 120, 60, 60, 60, 60, 60, + 62, 30, 30, 30, 30, 30, 30, 30, 31, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 31, 31, 31, 31, 31, + 30, 62, 62, 62, 62, 126, 126, 124, 124, 252, 252, 248, 248, 240, 240, 240, + 224, 224, 224, 192, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, + 128, 0, 56, 56, 28, 30, 14, 15, 15, 7, 7, 7, 7, 3, 3, 1, 1, 1, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 192, 193, 195, 195, + 195, 7, 15, 15, 63, 127, 255, 255, 255, 254, 252, 252, 240, 192, 0, 0, 0, + 0, 0, 0, 0, 0, 128, 192, 192, 240, 248, 124, 124, 60, 0, 0, 0, 0, 159, 159, + 159, 159, 159, 159, 159, 159, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, + 0, 0, 0, 0, 254, 254, 254, 254, 254, 254, 254, 254, 128, 128, 128, 128, + 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 192, 192, 192, 192, 192, 192, 128, + 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, + 0, 0, 0, 0, 3, 7, 3, 3, 3, 0, 0, 0, 0, 0, 1, 1, 255, 255, 255, 255, 255, + 255, 255, 0, 0, 224, 248, 252, 252, 255, 127, 15, 15, 3, 1, 0, 0, 0, 0, 0, + 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, + 255, 255, 255, 255, 255, 15, 15, 15, 15, 15, 15, 255, 255, 255, 255, 255, + 255, 255, 252, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 15, 15, + 15, 15, 15, 224, 224, 252, 254, 255, 255, 255, 255, 159, 159, 143, 143, + 135, 135, 143, 159, 255, 255, 255, 255, 255, 255, 252, 248, 0, 0, 0, 255, + 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, + 224, 248, 248, 255, 255, 255, 255, 255, 127, 15, 255, 255, 255, 255, 255, + 255, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, + 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, + 255, 255, 255, 255, 255, 192, 192, 192, 192, 192, 31, 31, 255, 255, 255, + 255, 255, 255, 231, 231, 199, 199, 199, 199, 199, 199, 199, 199, 231, 231, + 231, 231, 199, 135, 0, 0, 0, 63, 255, 255, 255, 255, 255, 255, 255, 0, 0, + 0, 0, 224, 240, 248, 248, 252, 254, 255, 255, 255, 127, 63, 63, 31, 15, 7, + 7, 1, 0, 0, 63, 63, 255, 255, 255, 255, 255, 240, 192, 192, 128, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 3, 3, 7, 7, 7, 7, 7, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, + 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 3, 3, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 0, 0, 0, 1, 3, 3, 3, 7, 7, 7, 7, 15, 15, 15, 15, 7, 7, 7, + 7, 7, 3, 3, 3, 1, 0, 0, 0, 0, 1, 3, 3, 7, 135, 135, 135, 192, 192, 0, 0, 7, + 7, 3, 3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 15, 15, + 31, 127, 127, 127, 255, 255, 252, 252, 252, 248, 240, 240, 240, 224, 224, + 224, 192, 192, 192, 192, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 192, 192, 192, 192, 192, + 224, 224, 224, 224, 240, 240, 240, 240, 248, 248, 248, 248, 252, 252, 252, + 254, 254, 255, 255, 255, 255, 255, 255, 127, 127, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 3, 3, 3, 7, 7, 7, 15, 15, 31, 31, 31, 63, 63, 63, 63, 63, 127, 127, 127, + 127, 127, 255, 255, 255, 255, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 255, 255, 255, 255, 255, 255, 255, 127, 127, 127, 127, 127, 127, 127, 127, + 63, 63, 63, 63, 63, 31, 31, 31, 31, 31, 15, 15, 15, 15, 7, 7, 7, 7, 3, 3, + 3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0] -intelLogo = upmLCD.uint8Array(len(logoArr)) + intelLogo = upmLCD.uint8Array(len(logoArr)) -for x in range(len(logoArr)): - intelLogo.__setitem__(x, logoArr[x]) -myLCD.clear() -myLCD.draw(intelLogo, 1024) + for x in range(len(logoArr)): + intelLogo.__setitem__(x, logoArr[x]) + myLCD.clear() + myLCD.draw(intelLogo, 1024) -del intelLogo -del myLCD -print "Exiting" + del intelLogo + del myLCD + print "Exiting" + +if __name__ == '__main__': + main() diff --git a/examples/python/oled_ssd1327.py b/examples/python/oled_ssd1327.py old mode 100644 new mode 100755 index be19a958..e6001b56 --- a/examples/python/oled_ssd1327.py +++ b/examples/python/oled_ssd1327.py @@ -25,165 +25,169 @@ import time, signal, sys import pyupm_i2clcd as upmLCD -myLCD = upmLCD.SSD1327(0, 0x3C); +def main(): + myLCD = upmLCD.SSD1327(0, 0x3C); -logoArr = [0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x08, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x60, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x06, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x01, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x01, 0xC0, 0x07, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x03, 0x80, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x07, 0x80, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x07, 0x80, 0x01, 0xC0, -0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, -0x07, 0x80, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x20, 0x0F, 0x80, 0x01, 0xE0, -0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, -0x0F, 0x00, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, -0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, -0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, -0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, -0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x38, 0x0F, 0x00, 0x01, 0xE0, -0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, -0x0F, 0x80, 0x01, 0xE0, 0x38, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x3C, 0x0F, 0x80, 0x01, 0xE0, -0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, -0x0F, 0x80, 0x03, 0xE0, 0x78, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x1E, 0x07, 0x80, 0x03, 0xE0, -0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, -0x07, 0x80, 0x03, 0xE0, 0xF0, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x1F, 0x07, 0x80, 0x03, 0xC1, -0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, -0x87, 0xC0, 0x07, 0xC1, 0xF0, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x0F, 0x83, 0xC0, 0x07, 0x83, -0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, -0xC3, 0xC0, 0x07, 0x87, 0xE0, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x07, 0xE1, 0xE0, 0x07, 0x0F, -0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, -0xF0, 0xE0, 0x0F, 0x0F, 0x80, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x01, 0xF8, 0xF0, 0x0E, 0x1F, -0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, -0xF8, 0x70, 0x1C, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0xFC, 0x30, 0x18, 0x7E, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x7F, 0x18, 0x30, 0xFC, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x1F, 0x88, 0x21, 0xF0, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x0F, 0xC4, 0x47, 0xE0, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x0F, 0x80, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0xF8, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0xE0, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, -0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x6C, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, -0x00, 0x00, 0x60, 0x00, 0x7E, 0x3F, 0x0F, 0xC3, -0xF0, 0xFA, 0x0F, 0xDF, 0xE1, 0x9F, 0xEC, 0x7E, -0xE6, 0x73, 0x9C, 0xE7, 0x39, 0xCE, 0x1C, 0xDF, -0xE1, 0xB9, 0xEC, 0xE7, 0xE0, 0x61, 0xD8, 0x66, -0x1B, 0x86, 0x1C, 0x06, 0x61, 0xB0, 0x6D, 0xC3, -0x7C, 0x7F, 0xFF, 0xFF, 0xFF, 0x06, 0x0F, 0x86, -0x61, 0xB0, 0x6D, 0x83, 0x3E, 0x7F, 0xFF, 0xFF, -0xFF, 0x06, 0x07, 0xC6, 0x61, 0xB0, 0x6D, 0x83, -0xC3, 0x61, 0x18, 0x46, 0x03, 0x86, 0x18, 0x66, -0x61, 0xB0, 0x6D, 0xC3, 0xFE, 0x7F, 0x9F, 0xE7, -0xF9, 0xFE, 0x1F, 0xE6, 0x3F, 0x9F, 0xEC, 0xFE, -0x7E, 0x3F, 0x0F, 0xC3, 0xF0, 0xFA, 0x0F, 0xC6, -0x3F, 0x9F, 0xEC, 0x7E, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, -0x00, 0x20, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x44, 0x00, 0x00, 0x20, 0x82, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0xF3, -0xCF, 0x70, 0x9E, 0x79, 0xE7, 0x80, 0x00, 0x00, -0x00, 0x00, 0x7D, 0x9E, 0x68, 0x20, 0xB2, 0xC8, -0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x9E, -0x6F, 0x20, 0xB2, 0xF9, 0xE7, 0x80, 0x00, 0x00, -0x00, 0x00, 0x46, 0x9A, 0x61, 0x20, 0xB2, 0xCB, -0x60, 0x80, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xF3, -0xCF, 0x30, 0x9E, 0x79, 0xE7, 0x90, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x7C, 0x02, 0x00, 0x00, 0x82, 0x60, 0x00, 0x00, -0xF8, 0x00, 0x00, 0x40, 0x40, 0x02, 0x00, 0x00, -0x83, 0x60, 0x00, 0x00, 0x8C, 0x00, 0x00, 0x40, -0x60, 0xB7, 0x79, 0xE7, 0x81, 0xC7, 0x92, 0x70, -0x89, 0xE7, 0x9E, 0x78, 0x7C, 0xE2, 0xC9, 0x2C, -0x81, 0xCC, 0xD2, 0x40, 0xFB, 0x21, 0xB2, 0x48, -0x40, 0x62, 0xF9, 0x2C, 0x80, 0x8C, 0xD2, 0x40, -0x8B, 0xE7, 0xB0, 0x48, 0x40, 0xE2, 0xC9, 0x2C, -0x80, 0x84, 0xD2, 0x40, 0x8B, 0x2D, 0x92, 0x48, -0x7D, 0xB3, 0x79, 0x27, 0x80, 0x87, 0x9E, 0x40, -0x8D, 0xE7, 0x9E, 0x48, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + logoArr = [0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x08, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x60, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x06, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, 0xC0, 0x07, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x80, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x80, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x07, 0x80, 0x01, 0xC0, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, + 0x07, 0x80, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x20, 0x0F, 0x80, 0x01, 0xE0, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, + 0x0F, 0x00, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, + 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, + 0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, + 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, + 0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x38, 0x0F, 0x00, 0x01, 0xE0, + 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, + 0x0F, 0x80, 0x01, 0xE0, 0x38, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x3C, 0x0F, 0x80, 0x01, 0xE0, + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, + 0x0F, 0x80, 0x03, 0xE0, 0x78, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x1E, 0x07, 0x80, 0x03, 0xE0, + 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, + 0x07, 0x80, 0x03, 0xE0, 0xF0, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x1F, 0x07, 0x80, 0x03, 0xC1, + 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, + 0x87, 0xC0, 0x07, 0xC1, 0xF0, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0F, 0x83, 0xC0, 0x07, 0x83, + 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, + 0xC3, 0xC0, 0x07, 0x87, 0xE0, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x07, 0xE1, 0xE0, 0x07, 0x0F, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, + 0xF0, 0xE0, 0x0F, 0x0F, 0x80, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0xF8, 0xF0, 0x0E, 0x1F, + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0xF8, 0x70, 0x1C, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xFC, 0x30, 0x18, 0x7E, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x7F, 0x18, 0x30, 0xFC, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x1F, 0x88, 0x21, 0xF0, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0F, 0xC4, 0x47, 0xE0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x0F, 0x80, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xF8, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0xE0, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x6C, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, + 0x00, 0x00, 0x60, 0x00, 0x7E, 0x3F, 0x0F, 0xC3, + 0xF0, 0xFA, 0x0F, 0xDF, 0xE1, 0x9F, 0xEC, 0x7E, + 0xE6, 0x73, 0x9C, 0xE7, 0x39, 0xCE, 0x1C, 0xDF, + 0xE1, 0xB9, 0xEC, 0xE7, 0xE0, 0x61, 0xD8, 0x66, + 0x1B, 0x86, 0x1C, 0x06, 0x61, 0xB0, 0x6D, 0xC3, + 0x7C, 0x7F, 0xFF, 0xFF, 0xFF, 0x06, 0x0F, 0x86, + 0x61, 0xB0, 0x6D, 0x83, 0x3E, 0x7F, 0xFF, 0xFF, + 0xFF, 0x06, 0x07, 0xC6, 0x61, 0xB0, 0x6D, 0x83, + 0xC3, 0x61, 0x18, 0x46, 0x03, 0x86, 0x18, 0x66, + 0x61, 0xB0, 0x6D, 0xC3, 0xFE, 0x7F, 0x9F, 0xE7, + 0xF9, 0xFE, 0x1F, 0xE6, 0x3F, 0x9F, 0xEC, 0xFE, + 0x7E, 0x3F, 0x0F, 0xC3, 0xF0, 0xFA, 0x0F, 0xC6, + 0x3F, 0x9F, 0xEC, 0x7E, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, + 0x00, 0x20, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x44, 0x00, 0x00, 0x20, 0x82, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0xF3, + 0xCF, 0x70, 0x9E, 0x79, 0xE7, 0x80, 0x00, 0x00, + 0x00, 0x00, 0x7D, 0x9E, 0x68, 0x20, 0xB2, 0xC8, + 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x9E, + 0x6F, 0x20, 0xB2, 0xF9, 0xE7, 0x80, 0x00, 0x00, + 0x00, 0x00, 0x46, 0x9A, 0x61, 0x20, 0xB2, 0xCB, + 0x60, 0x80, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xF3, + 0xCF, 0x30, 0x9E, 0x79, 0xE7, 0x90, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x7C, 0x02, 0x00, 0x00, 0x82, 0x60, 0x00, 0x00, + 0xF8, 0x00, 0x00, 0x40, 0x40, 0x02, 0x00, 0x00, + 0x83, 0x60, 0x00, 0x00, 0x8C, 0x00, 0x00, 0x40, + 0x60, 0xB7, 0x79, 0xE7, 0x81, 0xC7, 0x92, 0x70, + 0x89, 0xE7, 0x9E, 0x78, 0x7C, 0xE2, 0xC9, 0x2C, + 0x81, 0xCC, 0xD2, 0x40, 0xFB, 0x21, 0xB2, 0x48, + 0x40, 0x62, 0xF9, 0x2C, 0x80, 0x8C, 0xD2, 0x40, + 0x8B, 0xE7, 0xB0, 0x48, 0x40, 0xE2, 0xC9, 0x2C, + 0x80, 0x84, 0xD2, 0x40, 0x8B, 0x2D, 0x92, 0x48, + 0x7D, 0xB3, 0x79, 0x27, 0x80, 0x87, 0x9E, 0x40, + 0x8D, 0xE7, 0x9E, 0x48, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] -SeeedLogo = upmLCD.uint8Array(len(logoArr)) + SeeedLogo = upmLCD.uint8Array(len(logoArr)) -for x in range(len(logoArr)): - SeeedLogo.__setitem__(x, logoArr[x]) + for x in range(len(logoArr)): + SeeedLogo.__setitem__(x, logoArr[x]) -# If you don't set the display to be white, the seeed logo will appear jagged -myLCD.setGrayLevel(12) -myLCD.draw(SeeedLogo, 96 * 96 / 8); + # If you don't set the display to be white, the seeed logo will appear jagged + myLCD.setGrayLevel(12) + myLCD.draw(SeeedLogo, 96 * 96 / 8); -for i in range(12): - myLCD.setCursor(i, 0) - myLCD.setGrayLevel(i) - myLCD.write('Hello World') + for i in range(12): + myLCD.setCursor(i, 0) + myLCD.setGrayLevel(i) + myLCD.write('Hello World') -print "Exiting" + print "Exiting" + +if __name__ == '__main__': + main() diff --git a/examples/python/otp538u.py b/examples/python/otp538u.py old mode 100644 new mode 100755 index a7713b13..4525f944 --- a/examples/python/otp538u.py +++ b/examples/python/otp538u.py @@ -24,35 +24,37 @@ import time, sys, signal, atexit import pyupm_otp538u as upmOtp538u -# analog voltage, usually 3.3 or 5.0 -OTP538U_AREF = 5.0 +def main(): + # analog voltage, usually 3.3 or 5.0 + OTP538U_AREF = 5.0 -# Instantiate a OTP538U on analog pins A0 and A1 -# A0 is used for the Ambient Temperature and A1 is used for the -# Object temperature. -myTempIR = upmOtp538u.OTP538U(0, 1, OTP538U_AREF) + # Instantiate a OTP538U on analog pins A0 and A1 + # A0 is used for the Ambient Temperature and A1 is used for the + # Object temperature. + myTempIR = upmOtp538u.OTP538U(0, 1, OTP538U_AREF) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, including functions from myTempIR + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, including functions from myTempIR -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + outputStr = ("Ambient temp: {0}" + " C, Object temp: {1}" + " C".format(myTempIR.ambientTemperature(), + myTempIR.objectTemperature())) + print outputStr + time.sleep(1) -while(1): - outputStr = ("Ambient temp: {0}" - " C, Object temp: {1}" - " C".format(myTempIR.ambientTemperature(), - myTempIR.objectTemperature())) - print outputStr - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/ozwdump.py b/examples/python/ozwdump.py old mode 100644 new mode 100755 index 0e6a12d5..c735e0d0 --- a/examples/python/ozwdump.py +++ b/examples/python/ozwdump.py @@ -24,76 +24,80 @@ import time, sys, signal, atexit import pyupm_ozw as sensorObj -# Instantiate an OZW instance -sensor = sensorObj.OZWDUMP() +def main(): + # Instantiate an OZW instance + sensor = sensorObj.OZWDUMP() -# This function lets you run code on exit -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) + # Register exit handlers + atexit.register(exitHandler) -defaultDev = "/dev/ttyACM0" -if (len(sys.argv) > 1): + defaultDev = "/dev/ttyACM0" + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -# The first thing to do is create options, then lock them when done. -sensor.optionsCreate() -sensor.optionsLock() + # The first thing to do is create options, then lock them when done. + sensor.optionsCreate() + sensor.optionsLock() -# Next, initialize it. -print "Initializing, this may take awhile depending on your ZWave network" + # Next, initialize it. + print "Initializing, this may take awhile depending on your ZWave network" -sensor.init(defaultDev) + sensor.init(defaultDev) -print "Initialization complete" + print "Initialization complete" -print "Dumping nodes..." + print "Dumping nodes..." -sensor.dumpNodes(True) + sensor.dumpNodes(True) -# The following is example output of dumpNodes: -# -# Dumping nodes... -# Node 1: Z-Stick Gen5 -# Node 2: Smart Switch 6 -# Index: 0, Type: bool, Label: Switch, Value: False -# Index: 2, Type: float, Label: Energy, Value: 1.190 kWh -# Index: 3, Type: float, Label: Previous Reading, Value: 1.190 kWh -# Index: 4, Type: int32, Label: Interval, Value: 1521 seconds -# Index: 5, Type: float, Label: Power, Value: 0.000 W -# Index: 6, Type: float, Label: Voltage, Value: 121.256 V -# Index: 7, Type: float, Label: Current, Value: 0.000 A -# Index: 8, Type: bool, Label: Exporting, Value: False -# Index: 45, Type: list, Label: Day, Value: Friday -# Index: 46, Type: byte, Label: Hour, Value: 5 -# Index: 47, Type: byte, Label: Minute, Value: 53 -# Node 3: Multi Sensor -# Index: 0, Type: bool, Label: Sensor, Value: True -# Index: 1, Type: float, Label: Temperature, Value: 72.8 F -# Index: 2, Type: float, Label: Luminance, Value: 4 lux -# Index: 3, Type: float, Label: Relative Humidity, Value: 22 % -# Index: 17, Type: byte, Label: Battery Level, Value: 98 % -# Node 5: Minimote -# Node 6: Smart Energy Switch -# Index: 0, Type: bool, Label: Switch, Value: False -# Index: 2, Type: float, Label: Power, Value: 0.000 W -# Index: 3, Type: float, Label: Energy, Value: 1.609 kWh -# Index: 4, Type: float, Label: Previous Reading, Value: 1.609 kWh -# Index: 5, Type: int32, Label: Interval, Value: 1521 seconds -# Index: 6, Type: float, Label: Power, Value: 0.000 W -# Index: 7, Type: float, Label: Previous Reading, Value: 1.609 W -# Index: 8, Type: int32, Label: Interval, Value: 1521 seconds -# Index: 9, Type: bool, Label: Exporting, Value: False -# Node 7: Smart Energy Switch -# Index: 0, Type: bool, Label: Switch, Value: False -# Index: 2, Type: float, Label: Power, Value: 0.000 W -# Index: 3, Type: float, Label: Energy, Value: 0.000 kWh -# Index: 4, Type: float, Label: Previous Reading, Value: 0.000 kWh -# Index: 5, Type: int32, Label: Interval, Value: 1521 seconds -# Index: 6, Type: float, Label: Power, Value: 0.000 W -# Index: 7, Type: float, Label: Previous Reading, Value: 0.000 W -# Index: 8, Type: int32, Label: Interval, Value: 1521 seconds -# Index: 9, Type: bool, Label: Exporting, Value: False + # The following is example output of dumpNodes: + # + # Dumping nodes... + # Node 1: Z-Stick Gen5 + # Node 2: Smart Switch 6 + # Index: 0, Type: bool, Label: Switch, Value: False + # Index: 2, Type: float, Label: Energy, Value: 1.190 kWh + # Index: 3, Type: float, Label: Previous Reading, Value: 1.190 kWh + # Index: 4, Type: int32, Label: Interval, Value: 1521 seconds + # Index: 5, Type: float, Label: Power, Value: 0.000 W + # Index: 6, Type: float, Label: Voltage, Value: 121.256 V + # Index: 7, Type: float, Label: Current, Value: 0.000 A + # Index: 8, Type: bool, Label: Exporting, Value: False + # Index: 45, Type: list, Label: Day, Value: Friday + # Index: 46, Type: byte, Label: Hour, Value: 5 + # Index: 47, Type: byte, Label: Minute, Value: 53 + # Node 3: Multi Sensor + # Index: 0, Type: bool, Label: Sensor, Value: True + # Index: 1, Type: float, Label: Temperature, Value: 72.8 F + # Index: 2, Type: float, Label: Luminance, Value: 4 lux + # Index: 3, Type: float, Label: Relative Humidity, Value: 22 % + # Index: 17, Type: byte, Label: Battery Level, Value: 98 % + # Node 5: Minimote + # Node 6: Smart Energy Switch + # Index: 0, Type: bool, Label: Switch, Value: False + # Index: 2, Type: float, Label: Power, Value: 0.000 W + # Index: 3, Type: float, Label: Energy, Value: 1.609 kWh + # Index: 4, Type: float, Label: Previous Reading, Value: 1.609 kWh + # Index: 5, Type: int32, Label: Interval, Value: 1521 seconds + # Index: 6, Type: float, Label: Power, Value: 0.000 W + # Index: 7, Type: float, Label: Previous Reading, Value: 1.609 W + # Index: 8, Type: int32, Label: Interval, Value: 1521 seconds + # Index: 9, Type: bool, Label: Exporting, Value: False + # Node 7: Smart Energy Switch + # Index: 0, Type: bool, Label: Switch, Value: False + # Index: 2, Type: float, Label: Power, Value: 0.000 W + # Index: 3, Type: float, Label: Energy, Value: 0.000 kWh + # Index: 4, Type: float, Label: Previous Reading, Value: 0.000 kWh + # Index: 5, Type: int32, Label: Interval, Value: 1521 seconds + # Index: 6, Type: float, Label: Power, Value: 0.000 W + # Index: 7, Type: float, Label: Previous Reading, Value: 0.000 W + # Index: 8, Type: int32, Label: Interval, Value: 1521 seconds + # Index: 9, Type: bool, Label: Exporting, Value: False + +if __name__ == '__main__': + main() diff --git a/examples/python/pn532-writeurl.py b/examples/python/pn532-writeurl.py old mode 100644 new mode 100755 index b3abc410..61719b89 --- a/examples/python/pn532-writeurl.py +++ b/examples/python/pn532-writeurl.py @@ -24,82 +24,85 @@ import time, sys, signal, atexit import pyupm_pn532 as upmPn532 -# Instantiate an PN532 on I2C bus 0 (default) using gpio 3 for the -# IRQ, and gpio 2 for the reset pin. -myNFC = upmPn532.PN532(3, 2) +def main(): + # Instantiate an PN532 on I2C bus 0 (default) using gpio 3 for the + # IRQ, and gpio 2 for the reset pin. + myNFC = upmPn532.PN532(3, 2) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# This lets you run code on exit -def exitHandler(): - print "Exiting" - sys.exit(0) + # This lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) + if (not myNFC.init()): + print "init() failed" + sys.exit(0) -if (not myNFC.init()): - print "init() failed" - sys.exit(0) + vers = myNFC.getFirmwareVersion() -vers = myNFC.getFirmwareVersion() + if (vers): + print "Got firmware version: %08x" % vers + else: + print "Could not identify PN532" + sys.exit(0) -if (vers): - print "Got firmware version: %08x" % vers -else: - print "Could not identify PN532" - sys.exit(0) + # Now scan and identify any cards that come in range (1 for now) -# Now scan and identify any cards that come in range (1 for now) + # Retry forever + myNFC.setPassiveActivationRetries(0xff) -# Retry forever -myNFC.setPassiveActivationRetries(0xff) + myNFC.SAMConfig() -myNFC.SAMConfig() + uidSize = upmPn532.uint8Array(0) + uid = upmPn532.uint8Array(7) -uidSize = upmPn532.uint8Array(0) -uid = upmPn532.uint8Array(7) + # the URL we want to add as an NDEF record + # NOTE: this cannot exceed 34 characters. + url = "iotdk.intel.com" -# the URL we want to add as an NDEF record -# NOTE: this cannot exceed 34 characters. -url = "iotdk.intel.com" + foundCard = False -foundCard = False - -while (not foundCard): - for i in range(7): - uid.__setitem__(i, 0) - if (myNFC.readPassiveTargetID(upmPn532.PN532.BAUD_MIFARE_ISO14443A, + while (not foundCard): + for i in range(7): + uid.__setitem__(i, 0) + if (myNFC.readPassiveTargetID(upmPn532.PN532.BAUD_MIFARE_ISO14443A, uid, uidSize, 2000)): - # found a card - print "Found a card: UID len", uidSize.__getitem__(0) - print "UID: ", - for i in range(uidSize.__getitem__(0)): - print "%02x" % uid.__getitem__(i), - print - print "SAK: %02x" % myNFC.getSAK() - print "ATQA: %04x" % myNFC.getATQA() - print - foundCard = True - else: - print "Waiting for a card...\n" + # found a card + print "Found a card: UID len", uidSize.__getitem__(0) + print "UID: ", + for i in range(uidSize.__getitem__(0)): + print "%02x" % uid.__getitem__(i), + print + print "SAK: %02x" % myNFC.getSAK() + print "ATQA: %04x" % myNFC.getATQA() + print + foundCard = True + else: + print "Waiting for a card...\n" -if (uidSize.__getitem__(0) != 7): + if (uidSize.__getitem__(0) != 7): print "This example will only write an NDEF URI to preformatted" print "Mifare Ultralight or NTAG2XX tags" sys.exit(1) -# 48 bytes is maximum data area on ultralight cards, so we use that -# as the maximum datasize here. Obviously if you have a bigger -# card, you can write more data. -if (not myNFC.ntag2xx_WriteNDEFURI(upmPn532.PN532.NDEF_URIPREFIX_HTTP, url, 48)): + # 48 bytes is maximum data area on ultralight cards, so we use that + # as the maximum datasize here. Obviously if you have a bigger + # card, you can write more data. + if (not myNFC.ntag2xx_WriteNDEFURI(upmPn532.PN532.NDEF_URIPREFIX_HTTP, url, 48)): # failure print "Failed to write NDEF record tag." sys.exit(1) -print "Success, URL record written to tag." + print "Success, URL record written to tag." + +if __name__ == '__main__': + main() diff --git a/examples/python/pn532.py b/examples/python/pn532.py old mode 100644 new mode 100755 index bb000d4b..7a877e04 --- a/examples/python/pn532.py +++ b/examples/python/pn532.py @@ -24,62 +24,64 @@ import time, sys, signal, atexit import pyupm_pn532 as upmPn532 -# Instantiate an PN532 on I2C bus 0 (default) using gpio 3 for the -# IRQ, and gpio 2 for the reset pin. -myNFC = upmPn532.PN532(3, 2) +def main(): + # Instantiate an PN532 on I2C bus 0 (default) using gpio 3 for the + # IRQ, and gpio 2 for the reset pin. + myNFC = upmPn532.PN532(3, 2) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# This lets you run code on exit -def exitHandler(): - print "Exiting" - sys.exit(0) + # This lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) + if (not myNFC.init()): + print "init() failed" + sys.exit(0) -if (not myNFC.init()): - print "init() failed" - sys.exit(0) + vers = myNFC.getFirmwareVersion() -vers = myNFC.getFirmwareVersion() + if (vers): + print "Got firmware version: %08x" % vers + else: + print "Could not identify PN532" + sys.exit(0) -if (vers): - print "Got firmware version: %08x" % vers -else: - print "Could not identify PN532" - sys.exit(0) + # Now scan and identify any cards that come in range (1 for now) -# Now scan and identify any cards that come in range (1 for now) + # Retry forever + myNFC.setPassiveActivationRetries(0xff) -# Retry forever -myNFC.setPassiveActivationRetries(0xff) + myNFC.SAMConfig() -myNFC.SAMConfig() + uidSize = upmPn532.uint8Array(0) + uid = upmPn532.uint8Array(7) -uidSize = upmPn532.uint8Array(0) -uid = upmPn532.uint8Array(7) - - -while (1): - for i in range(7): - uid.__setitem__(i, 0) - if (myNFC.readPassiveTargetID(upmPn532.PN532.BAUD_MIFARE_ISO14443A, + while (1): + for i in range(7): + uid.__setitem__(i, 0) + if (myNFC.readPassiveTargetID(upmPn532.PN532.BAUD_MIFARE_ISO14443A, uid, uidSize, 2000)): - # found a card - print "Found a card: UID len", uidSize.__getitem__(0) - print "UID: ", - for i in range(uidSize.__getitem__(0)): - print "%02x" % uid.__getitem__(i), - print - print "SAK: %02x" % myNFC.getSAK() - print "ATQA: %04x" % myNFC.getATQA() - print - time.sleep(1) - else: - print "Waiting for a card...\n" + # found a card + print "Found a card: UID len", uidSize.__getitem__(0) + print "UID: ", + for i in range(uidSize.__getitem__(0)): + print "%02x" % uid.__getitem__(i), + print + print "SAK: %02x" % myNFC.getSAK() + print "ATQA: %04x" % myNFC.getATQA() + print + time.sleep(1) + else: + print "Waiting for a card...\n" + +if __name__ == '__main__': + main() diff --git a/examples/python/ppd42ns.py b/examples/python/ppd42ns.py old mode 100644 new mode 100755 index 86e037d5..ba1a3390 --- a/examples/python/ppd42ns.py +++ b/examples/python/ppd42ns.py @@ -24,33 +24,35 @@ import time, sys, signal, atexit import pyupm_ppd42ns as upmPpd42ns -# Instantiate a dust sensor on digital pin D8 -myDustSensor = upmPpd42ns.PPD42NS(8) +def main(): + # Instantiate a dust sensor on digital pin D8 + myDustSensor = upmPpd42ns.PPD42NS(8) + ## 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 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, including functions from myDustSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myDustSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + notice = ("This program will give readings " + "every 30 seconds until you stop it") + print notice + while(1): + data = myDustSensor.getData() + # we need to sleep for a bit for the data to print out + time.sleep(.1) + print "Low pulse occupancy: " + str(data.lowPulseOccupancy) + print "Ratio: " + str(data.ratio) + print "Concentration: " + str(data.concentration) -notice = ("This program will give readings " -"every 30 seconds until you stop it") -print notice - -while(1): - data = myDustSensor.getData() - # we need to sleep for a bit for the data to print out - time.sleep(.1) - print "Low pulse occupancy: " + str(data.lowPulseOccupancy) - print "Ratio: " + str(data.ratio) - print "Concentration: " + str(data.concentration) +if __name__ == '__main__': + main() diff --git a/examples/python/relay.py b/examples/python/relay.py old mode 100644 new mode 100755 index cf232956..c6111e37 --- a/examples/python/relay.py +++ b/examples/python/relay.py @@ -23,22 +23,26 @@ import time import pyupm_grove as grove -# Create the relay switch object using GPIO pin 0 -relay = grove.Relay(0) +def main(): + # Create the relay switch object using GPIO pin 0 + relay = grove.Relay(0) -# Close and then open the relay switch 3 times, -# waiting one second each time. The LED on the relay switch -# will light up when the switch is on (closed). -# The switch will also make a noise between transitions. -for i in range (0,3): - relay.on() - if relay.isOn(): - print relay.name(), 'is on' - time.sleep(1) - relay.off() - if relay.isOff(): - print relay.name(), 'is off' - time.sleep(1) + # Close and then open the relay switch 3 times, + # waiting one second each time. The LED on the relay switch + # will light up when the switch is on (closed). + # The switch will also make a noise between transitions. + for i in range (0,3): + relay.on() + if relay.isOn(): + print relay.name(), 'is on' + time.sleep(1) + relay.off() + if relay.isOff(): + print relay.name(), 'is off' + time.sleep(1) -# Delete the relay switch object -del relay + # Delete the relay switch object + del relay + +if __name__ == '__main__': + main() diff --git a/examples/python/rfr359f.py b/examples/python/rfr359f.py old mode 100644 new mode 100755 index 349821db..d3b2aa00 --- a/examples/python/rfr359f.py +++ b/examples/python/rfr359f.py @@ -24,29 +24,31 @@ import time, sys, signal, atexit import pyupm_rfr359f as upmRfr359f -# Instantiate an RFR359F digital pin D2 -# This was tested on the Grove IR Distance Interrupter -myDistInterrupter = upmRfr359f.RFR359F(2) +def main(): + # Instantiate an RFR359F digital pin D2 + # This was tested on the Grove IR Distance Interrupter + myDistInterrupter = upmRfr359f.RFR359F(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 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, including functions from myDistInterrupter + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myDistInterrupter -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myDistInterrupter.objectDetected()): + print "Object detected" + else: + print "Area is clear" + time.sleep(.1) - -while(1): - if (myDistInterrupter.objectDetected()): - print "Object detected" - else: - print "Area is clear" - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/rgbringcoder.py b/examples/python/rgbringcoder.py old mode 100644 new mode 100755 index 5c0b1fb1..af95b90a --- a/examples/python/rgbringcoder.py +++ b/examples/python/rgbringcoder.py @@ -24,67 +24,70 @@ import time, sys, signal, atexit import pyupm_rgbringcoder as upmRGBRingCoder -# There are a lot of pins to hook up. These pins are valid for the -# Edison board, but may need to be adjusted for other platforms. +def main(): + # There are a lot of pins to hook up. These pins are valid for the + # Edison board, but may need to be adjusted for other platforms. -# In order: -# enable - 4 -# latch - 10 -# clear - 11 -# clock - 2 -# data - 9 -# switch - 7 + # In order: + # enable - 4 + # latch - 10 + # clear - 11 + # clock - 2 + # data - 9 + # switch - 7 -# red pwm - 3 -# green pwm - 5 -# blue pwm - 6 + # red pwm - 3 + # green pwm - 5 + # blue pwm - 6 -# encA - 12 -# encB - 13 -ringCoder = upmRGBRingCoder.RGBRingCoder(4, 10, 11, 2, 9, 7, 12, 13, 3, - 5, 6) + # encA - 12 + # encB - 13 + ringCoder = upmRGBRingCoder.RGBRingCoder(4, 10, 11, 2, 9, 7, 12, 13, 3, + 5, 6) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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, -# including functions from ringCoder -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit, + # including functions from ringCoder + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) + spin = 0x0001; + oldState = False; + oldPos = 0; -spin = 0x0001; -oldState = False; -oldPos = 0; + # Lets go green + ringCoder.setRGBLED(0.99, 0.01, 0.99); -# Lets go green -ringCoder.setRGBLED(0.99, 0.01, 0.99); - -while(1): + while(1): # you spin me round... if ((spin & 0xffff) == 0): - spin = 0x0001 - + spin = 0x0001 + ringCoder.setRingLEDS(spin) spin <<= 1 # check button state bstate = ringCoder.getButtonState() if (bstate != oldState): - print "Button state changed from", oldState, " to ", bstate - oldState = bstate - + print "Button state changed from", oldState, " to ", bstate + oldState = bstate + # check encoder position epos = ringCoder.getEncoderPosition() if (epos != oldPos): - print "Encoder position changed from", oldPos, "to", epos - oldPos = epos + print "Encoder position changed from", oldPos, "to", epos + oldPos = epos time.sleep(0.1) + +if __name__ == '__main__': + main() diff --git a/examples/python/rhusb.py b/examples/python/rhusb.py old mode 100644 new mode 100755 index 70198e09..067325d0 --- a/examples/python/rhusb.py +++ b/examples/python/rhusb.py @@ -24,38 +24,39 @@ import time, sys, signal, atexit import pyupm_rhusb as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an RHUSB instance on defaultDev -sensor = sensorObj.RHUSB(defaultDev) + # Instantiate an RHUSB instance on defaultDev + sensor = sensorObj.RHUSB(defaultDev) -# output the firmware ID -print "Firmware ID:", sensor.getFirmwareID() -print + # output the firmware ID + print "Firmware ID:", sensor.getFirmwareID() + print -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() @@ -66,4 +67,7 @@ while (1): print "Humidity:", sensor.getHumidity(), "%" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/rotary.py b/examples/python/rotary.py old mode 100644 new mode 100755 index 98396d46..770fc256 --- a/examples/python/rotary.py +++ b/examples/python/rotary.py @@ -23,23 +23,26 @@ from time import sleep import pyupm_grove as grove -# New knob on AIO pin 0 -knob = grove.Rotary(0) +def main(): + # New knob on AIO pin 0 + knob = grove.Rotary(0) -# Loop indefinitely -while True: + # Loop indefinitely + while True: + # Read values + abs = knob.abs_value() + absdeg = knob.abs_deg() + absrad = knob.abs_rad() - # Read values - abs = knob.abs_value() - absdeg = knob.abs_deg() - absrad = knob.abs_rad() + rel = knob.rel_value() + reldeg = knob.rel_deg() + relrad = knob.rel_rad() - rel = knob.rel_value() - reldeg = knob.rel_deg() - relrad = knob.rel_rad() + print "Abs values: %4d" % int(abs) , " raw %4d" % int(absdeg), "deg = %5.2f" % absrad , " rad ", + print "Rel values: %4d" % int(rel) , " raw %4d" % int(reldeg), "deg = %5.2f" % relrad , " rad" - print "Abs values: %4d" % int(abs) , " raw %4d" % int(absdeg), "deg = %5.2f" % absrad , " rad ", - print "Rel values: %4d" % int(rel) , " raw %4d" % int(reldeg), "deg = %5.2f" % relrad , " rad" + # Sleep for 2.5 s + sleep(2.5) - # Sleep for 2.5 s - sleep(2.5) +if __name__ == '__main__': + main() diff --git a/examples/python/rotaryencoder.py b/examples/python/rotaryencoder.py old mode 100644 new mode 100755 index 89738fd7..161eb3e7 --- a/examples/python/rotaryencoder.py +++ b/examples/python/rotaryencoder.py @@ -24,26 +24,28 @@ import time, sys, signal, atexit import pyupm_rotaryencoder as upmRotaryEncoder -# Instantiate a Grove Rotary Encoder, using signal pins D2 and D3 -myRotaryEncoder = upmRotaryEncoder.RotaryEncoder(2, 3); +def main(): + # Instantiate a Grove Rotary Encoder, using signal pins D2 and D3 + myRotaryEncoder = upmRotaryEncoder.RotaryEncoder(2, 3); + ## 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 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, including functions from myRotaryEncoder + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myRotaryEncoder -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Read the value every second and detect motion + while(1): + print "Position: {0}".format(myRotaryEncoder.position()) + time.sleep(.1) - -# Read the value every second and detect motion -while(1): - print "Position: {0}".format(myRotaryEncoder.position()) - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/rpr220.py b/examples/python/rpr220.py old mode 100644 new mode 100755 index edf14ca2..688479b8 --- a/examples/python/rpr220.py +++ b/examples/python/rpr220.py @@ -24,33 +24,35 @@ import time, sys, signal, atexit import pyupm_rpr220 as upmRpr220 -# This example uses a simple method to determine current status +def main(): + # This example uses a simple method to determine current status -# Instantiate an RPR220 digital pin D2 -# This was tested on the Grove IR Reflective Sensor -myReflectiveSensor = upmRpr220.RPR220(2) + # Instantiate an RPR220 digital pin D2 + # This was tested on the Grove IR Reflective Sensor + myReflectiveSensor = upmRpr220.RPR220(2) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myReflectiveSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myReflectiveSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myReflectiveSensor.blackDetected()): + print "Black detected" + else: + print "Black NOT detected" + time.sleep(.1) -while(1): - if (myReflectiveSensor.blackDetected()): - print "Black detected" - else: - print "Black NOT detected" - - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/sainsmartks.py b/examples/python/sainsmartks.py old mode 100644 new mode 100755 index 7763de9b..47d8863c --- a/examples/python/sainsmartks.py +++ b/examples/python/sainsmartks.py @@ -24,31 +24,34 @@ import time, sys, signal, atexit import pyupm_i2clcd as sainsmartObj -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # 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, -# including functions from ringCoder -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit, + # including functions from ringCoder + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Instantiate a Sainsmart LCD Keypad Shield using default pins -lcd = sainsmartObj.SAINSMARTKS() + # Instantiate a Sainsmart LCD Keypad Shield using default pins + lcd = sainsmartObj.SAINSMARTKS() -lcd.setCursor(0,0) -lcd.write("Sainsmart KS") -lcd.setCursor(1,2) -lcd.write("Hello World") + lcd.setCursor(0,0) + lcd.write("Sainsmart KS") + lcd.setCursor(1,2) + lcd.write("Hello World") -# output current key value every second. -while(1): - print "Button value: ", lcd.getRawKeyValue() - time.sleep(1) + # output current key value every second. + while(1): + print "Button value: ", lcd.getRawKeyValue() + time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/scam.py b/examples/python/scam.py old mode 100644 new mode 100755 index fcbfc56b..9165df56 --- a/examples/python/scam.py +++ b/examples/python/scam.py @@ -25,37 +25,41 @@ import sys import pyupm_scam as upmscam -# Instantiate a Serial Camera on UART 0 -camera = upmscam.SCAM(0) +def main(): + # Instantiate a Serial Camera on UART 0 + camera = upmscam.SCAM(0) -# make sure port is initialized properly. 115200 baud is the default. -if (not camera.setupTty()): - print "Failed to setup tty port parameters" - sys.exit(1) + # make sure port is initialized properly. 115200 baud is the default. + if (not camera.setupTty()): + print "Failed to setup tty port parameters" + sys.exit(1) -if (camera.init()): + if (camera.init()): print "Initialized..." -else: + else: print "init() failed" -if (camera.preCapture()): + if (camera.preCapture()): print "preCapture succeeded..." -else: + else: print "preCapture failed." -if (camera.doCapture()): + if (camera.doCapture()): print "doCapture succeeded..." -else: + else: 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..." if (camera.storeImage("image.jpg")): - print "storeImage succeeded..." + print "storeImage succeeded..." else: - print "storeImage failed." + print "storeImage failed." -print "Exiting." -sys.exit(0) + print "Exiting." + sys.exit(0) + +if __name__ == '__main__': + main() diff --git a/examples/python/sht1x.py b/examples/python/sht1x.py old mode 100644 new mode 100755 index f14c7c6b..ad7956f3 --- a/examples/python/sht1x.py +++ b/examples/python/sht1x.py @@ -24,30 +24,34 @@ import time, sys, signal, atexit import pyupm_sht1x as sensorObj -# Instantiate a SHT1X sensor using D2 as the clock, and D3 as the -# data pin. -sensor = sensorObj.SHT1X(2, 3) +def main(): + # Instantiate a SHT1X sensor using D2 as the clock, and D3 as the + # data pin. + sensor = sensorObj.SHT1X(2, 3) -## 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every 2 seconds, update and print values -while (True): + # Every 2 seconds, update and print values + while (True): sensor.update() print "Temperature:", sensor.getTemperature(), "C" print "Humidity: ", sensor.getHumidity(), "RH" print - time.sleep(2) + time.sleep(2) + +if __name__ == '__main__': + main() diff --git a/examples/python/si114x.py b/examples/python/si114x.py old mode 100644 new mode 100755 index 4264620b..19ba0529 --- a/examples/python/si114x.py +++ b/examples/python/si114x.py @@ -24,43 +24,45 @@ import time, sys, signal, atexit import pyupm_si114x as upmSi114x -# Instantiate a SI114x UV Sensor on I2C bus 0 -myUVSensor = upmSi114x.SI114X(0) +def main(): + # Instantiate a SI114x UV Sensor on I2C bus 0 + myUVSensor = upmSi114x.SI114X(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myUVSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myUVSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # First initialize it + myUVSensor.initialize() + print "UV Index Scale:" + print "---------------" + print "11+ Extreme" + print "8-10 Very High" + print "6-7 High" + print "3-5 Moderate" + print "0-2 Low\n" -# First initialize it -myUVSensor.initialize() + # update every second and print the currently measured UV Index + while (1): + # update current value(s) + myUVSensor.update() -print "UV Index Scale:" -print "---------------" -print "11+ Extreme" -print "8-10 Very High" -print "6-7 High" -print "3-5 Moderate" -print "0-2 Low\n" + # print detected value + print "UV Index:", myUVSensor.getUVIndex() -# update every second and print the currently measured UV Index -while (1): - # update current value(s) - myUVSensor.update() + time.sleep(1) - # print detected value - print "UV Index:", myUVSensor.getUVIndex() - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/slide.py b/examples/python/slide.py old mode 100644 new mode 100755 index 0bc5be7c..7738f284 --- a/examples/python/slide.py +++ b/examples/python/slide.py @@ -23,17 +23,20 @@ from time import sleep import pyupm_slide as slide -# New Grove Slider on AIO pin 0 -slider = slide.Slide(0) +def main(): + # New Grove Slider on AIO pin 0 + slider = slide.Slide(0) -# Loop indefinitely -while True: + # Loop indefinitely + while True: + # Read values + raw = slider.raw_value() + volts = slider.voltage_value() - # Read values - raw = slider.raw_value() - volts = slider.voltage_value() + print "Slider value: ", raw , " = %.2f" % volts , " V" - print "Slider value: ", raw , " = %.2f" % volts , " V" + # Sleep for 2.5 s + sleep(2.5) - # Sleep for 2.5 s - sleep(2.5) +if __name__ == '__main__': + main() diff --git a/examples/python/sm130.py b/examples/python/sm130.py old mode 100644 new mode 100755 index ce6ae1bc..7a624d61 --- a/examples/python/sm130.py +++ b/examples/python/sm130.py @@ -24,40 +24,44 @@ import time, sys, signal, atexit import pyupm_sm130 as sensorObj -# Instantiate a UART based SM130 RFID Module using defaults -sensor = sensorObj.SM130() +def main(): + # Instantiate a UART based SM130 RFID Module using defaults + sensor = sensorObj.SM130() -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Set the baud rate, 19200 baud is the default. -if (sensor.setBaudRate(19200)): - print "Failed to set baud rate" - sys.exit(0) + # Set the baud rate, 19200 baud is the default. + if (sensor.setBaudRate(19200)): + print "Failed to set baud rate" + sys.exit(0) -print "Resetting..." -sensor.reset() + print "Resetting..." + sensor.reset() -print "Firmware revision: " + sensor.getFirmwareVersion() + print "Firmware revision: " + sensor.getFirmwareVersion() -print "Waiting up to 5 seconds for a tag..." + print "Waiting up to 5 seconds for a tag..." -if (sensor.waitForTag(5000)): + if (sensor.waitForTag(5000)): print "Found tag, UID:", print sensor.string2HexString(sensor.getUID()) print "Tag Type:", print sensor.tag2String(sensor.getTagType()) -else: + else: # error print "waitForTag failed: " + sensor.getLastErrorString() + +if __name__ == '__main__': + main() diff --git a/examples/python/speaker.py b/examples/python/speaker.py old mode 100644 new mode 100755 index 48e0eadd..e36c509f --- a/examples/python/speaker.py +++ b/examples/python/speaker.py @@ -24,11 +24,15 @@ import time, sys, signal, atexit import pyupm_speaker as upmspeaker -# Instantiate a Speaker on digital pin D2 -mySpeaker = upmspeaker.Speaker(2) +def main(): + # Instantiate a Speaker on digital pin D2 + mySpeaker = upmspeaker.Speaker(2) -# Play all 7 of the lowest notes -mySpeaker.playAll() + # Play all 7 of the lowest notes + mySpeaker.playAll() -# Play a medium C-sharp -mySpeaker.playSound('c', True, "med") + # Play a medium C-sharp + mySpeaker.playSound('c', True, "med") + +if __name__ == '__main__': + main() diff --git a/examples/python/stepmotor.py b/examples/python/stepmotor.py old mode 100644 new mode 100755 index 125ac711..b1c94c1f --- a/examples/python/stepmotor.py +++ b/examples/python/stepmotor.py @@ -21,44 +21,47 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_stepmotor as mylib -# Instantiate a StepMotor object on pins 2 (dir) and 3 (step) -stepper = mylib.StepMotor(2, 3) +def main(): + # Instantiate a StepMotor object on pins 2 (dir) and 3 (step) + stepper = mylib.StepMotor(2, 3) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# This lets you run code on exit -def exitHandler(): - print "Exiting" - sys.exit(0) + # This lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Rotating 1 revolution forward and back at 60 rpm." -stepper.setSpeed(60) -stepper.stepForward(200) -time.sleep(1) -stepper.stepBackward(200) -time.sleep(1) + print "Rotating 1 revolution forward and back at 60 rpm." + stepper.setSpeed(60) + stepper.stepForward(200) + time.sleep(1) + stepper.stepBackward(200) + time.sleep(1) -print "Rotating 1 revolution forward and back at 150 rpm." -stepper.setSpeed(150) -stepper.stepForward(200) -time.sleep(1) -stepper.stepBackward(200) -time.sleep(1) + print "Rotating 1 revolution forward and back at 150 rpm." + stepper.setSpeed(150) + stepper.stepForward(200) + time.sleep(1) + stepper.stepBackward(200) + time.sleep(1) -print "Rotating 1 revolution forward and back at 300 rpm." -stepper.setSpeed(300) -stepper.stepForward(200) -time.sleep(1) -stepper.stepBackward(200) -time.sleep(1) + print "Rotating 1 revolution forward and back at 300 rpm." + stepper.setSpeed(300) + stepper.stepForward(200) + time.sleep(1) + stepper.stepBackward(200) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/sx1276-fsk.py b/examples/python/sx1276-fsk.py old mode 100644 new mode 100755 index 68996997..da8fe1fb --- a/examples/python/sx1276-fsk.py +++ b/examples/python/sx1276-fsk.py @@ -24,66 +24,70 @@ import time, sys, signal, atexit import pyupm_sx1276 as sensorObj -# Instantiate an SX1276 using default parameters -sensor = sensorObj.SX1276() +def main(): + # Instantiate an SX1276 using default parameters + sensor = sensorObj.SX1276() -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Specify an argument to go into receive mode. Default is transmit" + print "Specify an argument to go into receive mode. Default is transmit" -# 915Mhz -sensor.setChannel(915000000) + # 915Mhz + sensor.setChannel(915000000) -# FSK configuration (rx and tx must be configured the same): -# Tx output power = 14 dBm -# FSK freq deviation = 25000 Hz -# FSK bandwidth = 50000 bps -# FSK AFC bandwidth = 83333 Hz -# FSK datarate = 50000 bps -# FSK preamble len = 5 -# FSK fixed length payload = false -# FSK CRC check = true -# FSK (rx) continuous Rx mode = False + # FSK configuration (rx and tx must be configured the same): + # Tx output power = 14 dBm + # FSK freq deviation = 25000 Hz + # FSK bandwidth = 50000 bps + # FSK AFC bandwidth = 83333 Hz + # FSK datarate = 50000 bps + # FSK preamble len = 5 + # FSK fixed length payload = false + # FSK CRC check = true + # FSK (rx) continuous Rx mode = False -sensor.setTxConfig(sensor.MODEM_FSK, 14, 25000, 0, - 50000, 0, 5, False, True, False, 0, False) - -sensor.setRxConfig(sensor.MODEM_FSK, 50000, 50000, - 0, 83333, 5, 0, False, 0, True, - False, 0, False, True) + sensor.setTxConfig(sensor.MODEM_FSK, 14, 25000, 0, + 50000, 0, 5, False, True, False, 0, False) -count = 0 + sensor.setRxConfig(sensor.MODEM_FSK, 50000, 50000, + 0, 83333, 5, 0, False, 0, True, + False, 0, False, True) -while True: + count = 0 + + while True: if (len(sys.argv) > 1): - # receive mode - print "Attempting to receive..." - rv = sensor.setRx(3000) - if (rv): - print "setRx returned ", rv - else: - print "Received Buffer: ", sensor.getRxBufferStr(); - # go back to sleep when done + # receive mode + print "Attempting to receive..." + rv = sensor.setRx(3000) + if (rv): + print "setRx returned ", rv + else: + print "Received Buffer: ", sensor.getRxBufferStr(); + # go back to sleep when done - sensor.setSleep() - time.sleep(.25) + sensor.setSleep() + time.sleep(.25) else: - # transmit mode - buffer = "Ping " + str(count) - count += 1 - print "Sending..." + buffer - sensor.sendStr(buffer, 3000) - sensor.setSleep(); - time.sleep(1); + # transmit mode + buffer = "Ping " + str(count) + count += 1 + print "Sending..." + buffer + sensor.sendStr(buffer, 3000) + sensor.setSleep(); + time.sleep(1); + +if __name__ == '__main__': + main() diff --git a/examples/python/sx1276-lora.py b/examples/python/sx1276-lora.py old mode 100644 new mode 100755 index 05d97009..afa25bcd --- a/examples/python/sx1276-lora.py +++ b/examples/python/sx1276-lora.py @@ -24,65 +24,69 @@ import time, sys, signal, atexit import pyupm_sx1276 as sensorObj -# Instantiate an SX1276 using default parameters -sensor = sensorObj.SX1276() +def main(): + # Instantiate an SX1276 using default parameters + sensor = sensorObj.SX1276() -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Specify an argument to go into receive mode. Default is transmit" + print "Specify an argument to go into receive mode. Default is transmit" -# 915Mhz -sensor.setChannel(915000000) + # 915Mhz + sensor.setChannel(915000000) -# LORA configuration (rx and tx must be configured the same): -# Tx output power = 14 dBm -# LORA bandwidth = 125000 (can also be 250K and 500K) -# LORA spreading factor = 7 -# LORA coding rate = 1 (4/5) -# LORA preamble len = 8 -# LORA symbol timeout = 5 -# LORA fixed payload = false -# LORA IQ inversion = false -# LORA (rx) continuous Rx mode = true + # LORA configuration (rx and tx must be configured the same): + # Tx output power = 14 dBm + # LORA bandwidth = 125000 (can also be 250K and 500K) + # LORA spreading factor = 7 + # LORA coding rate = 1 (4/5) + # LORA preamble len = 8 + # LORA symbol timeout = 5 + # LORA fixed payload = false + # LORA IQ inversion = false + # LORA (rx) continuous Rx mode = true -sensor.setTxConfig(sensor.MODEM_LORA, 14, 0, 125000, - 7, 1, 8, False, True, False, 0, False) - -sensor.setRxConfig(sensor.MODEM_LORA, 125000, 7, - 1, 0, 8, 5, False, 0, True, False, 0, False, True) - -count = 0 + sensor.setTxConfig(sensor.MODEM_LORA, 14, 0, 125000, + 7, 1, 8, False, True, False, 0, False) -while True: + sensor.setRxConfig(sensor.MODEM_LORA, 125000, 7, + 1, 0, 8, 5, False, 0, True, False, 0, False, True) + + count = 0 + + while True: if (len(sys.argv) > 1): - # receive mode - print "Attempting to receive..." - rv = sensor.setRx(3000) - if (rv): - print "setRx returned ", rv - else: - print "Received Buffer: ", sensor.getRxBufferStr(); - # go back to sleep when done + # receive mode + print "Attempting to receive..." + rv = sensor.setRx(3000) + if (rv): + print "setRx returned ", rv + else: + print "Received Buffer: ", sensor.getRxBufferStr(); + # go back to sleep when done - sensor.setSleep() - time.sleep(.25) + sensor.setSleep() + time.sleep(.25) else: - # transmit mode - buffer = "Ping " + str(count) - count += 1 - print "Sending..." + buffer - sensor.sendStr(buffer, 3000) - sensor.setSleep(); - time.sleep(1); + # transmit mode + buffer = "Ping " + str(count) + count += 1 + print "Sending..." + buffer + sensor.sendStr(buffer, 3000) + sensor.setSleep(); + time.sleep(1); + +if __name__ == '__main__': + main() diff --git a/examples/python/sx6119.py b/examples/python/sx6119.py old mode 100644 new mode 100755 index a8498365..9d736117 --- a/examples/python/sx6119.py +++ b/examples/python/sx6119.py @@ -24,27 +24,31 @@ import sys import pyupm_sx6119 as upmSx6119 -# Instantiate a SX6119 on digital pins 2 (power) and 3 (seek) -# This example was tested on the Grove FM Receiver. -myFM_receiver_obj = upmSx6119.SX6119(2, 3) +def main(): + # Instantiate a SX6119 on digital pins 2 (power) and 3 (seek) + # This example was tested on the Grove FM Receiver. + myFM_receiver_obj = upmSx6119.SX6119(2, 3) -# if an argument was specified (any argument), seek to the next -# station, else just toggle the power. + # if an argument was specified (any argument), seek to the next + # station, else just toggle the power. -print "Supply any argument to the command line to seek to the" -print "next station." -print "Running the example without an argument will toggle the" -print "power on or off.\n" + print "Supply any argument to the command line to seek to the" + print "next station." + print "Running the example without an argument will toggle the" + print "power on or off.\n" -doSeek = False + doSeek = False -if (len(sys.argv) > 1): - doSeek = True + if (len(sys.argv) > 1): + doSeek = True -# depending on what was selected, do it -if (doSeek): - myFM_receiver_obj.seek() -else: - myFM_receiver_obj.togglePower() + # depending on what was selected, do it + if (doSeek): + myFM_receiver_obj.seek() + else: + myFM_receiver_obj.togglePower() -print "Exiting"; + print "Exiting"; + +if __name__ == '__main__': + main() diff --git a/examples/python/t3311.py b/examples/python/t3311.py old mode 100644 new mode 100755 index 0c568df3..7f91aa12 --- a/examples/python/t3311.py +++ b/examples/python/t3311.py @@ -24,40 +24,41 @@ import time, sys, signal, atexit import pyupm_t3311 as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Initializing..." + print "Initializing..." -# Instantiate an T3311 instance, using MODBUS slave address 1, and -# default comm parameters (9600, 8, N, 2) -sensor = sensorObj.T3311(defaultDev, 1) + # Instantiate an T3311 instance, using MODBUS slave address 1, and + # default comm parameters (9600, 8, N, 2) + sensor = sensorObj.T3311(defaultDev, 1) -# output the serial number and firmware revision -print "Serial Number:", sensor.getSerialNumber() -print "Firmware Revision: {0}.{1}".format(sensor.getFirmwareMajor(), - sensor.getFirmwareMinor()) -print + # output the serial number and firmware revision + print "Serial Number:", sensor.getSerialNumber() + print "Firmware Revision: {0}.{1}".format(sensor.getFirmwareMajor(), + sensor.getFirmwareMinor()) + print -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() @@ -73,18 +74,21 @@ while (1): # with FW revisions > 2.44, extended computed data is available if (sensor.extendedDataAvailable()): - print "Dew Point Temperature:", sensor.getDewPointTemperature(), - print "C /", sensor.getDewPointTemperature(True), "F" + print "Dew Point Temperature:", sensor.getDewPointTemperature(), + print "C /", sensor.getDewPointTemperature(True), "F" - print "Absolute Humidity:", sensor.getAbsoluteHumidity(), "g/m3" + print "Absolute Humidity:", sensor.getAbsoluteHumidity(), "g/m3" - print "Specific Humidity:", sensor.getSpecificHumidity(), - print "g/kg" + print "Specific Humidity:", sensor.getSpecificHumidity(), + print "g/kg" - print "Mixing Ratio:", sensor.getMixingRatio(), "g/kg" + print "Mixing Ratio:", sensor.getMixingRatio(), "g/kg" - print "Specific Enthalpy:", sensor.getSpecificEnthalpy(), - print "kJ/kg" + print "Specific Enthalpy:", sensor.getSpecificEnthalpy(), + print "kJ/kg" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/t8100.py b/examples/python/t8100.py old mode 100644 new mode 100755 index 2f14651d..659d38a0 --- a/examples/python/t8100.py +++ b/examples/python/t8100.py @@ -24,57 +24,58 @@ import time, sys, signal, atexit import pyupm_t8100 as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# You will need to edit this example to conform to your site and your -# devices, specifically the Device Object Instance ID passed to the -# constructor, and the arguments to initMaster() that are -# appropriate for your BACnet network. + # You will need to edit this example to conform to your site and your + # devices, specifically the Device Object Instance ID passed to the + # constructor, and the arguments to initMaster() that are + # appropriate for your BACnet network. -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an T8100 object for an T8100 device that has 568000 -# as it's unique Device Object Instance ID. NOTE: You will -# certainly want to change this to the correct value for your -# device(s). -sensor = sensorObj.T8100(568000) + # Instantiate an T8100 object for an T8100 device that has 568000 + # as it's unique Device Object Instance ID. NOTE: You will + # certainly want to change this to the correct value for your + # device(s). + sensor = sensorObj.T8100(568000) -# Initialize our BACnet master, if it has not already been -# initialized, with the device and baudrate, choosing 1000001 as -# our unique Device Object Instance ID, 2 as our MAC address and -# using default values for maxMaster and maxInfoFrames -sensor.initMaster(defaultDev, 38400, 1000001, 2) + # Initialize our BACnet master, if it has not already been + # initialized, with the device and baudrate, choosing 1000001 as + # our unique Device Object Instance ID, 2 as our MAC address and + # using default values for maxMaster and maxInfoFrames + sensor.initMaster(defaultDev, 38400, 1000001, 2) -# Uncomment to enable debugging output -# sensor.setDebug(True); + # Uncomment to enable debugging output + # sensor.setDebug(True); -# output the serial number and firmware revision -print -print "Device Description:", sensor.getDeviceDescription() -print "Device Location:", sensor.getDeviceLocation() -print + # output the serial number and firmware revision + print + print "Device Description:", sensor.getDeviceDescription() + print "Device Location:", sensor.getDeviceLocation() + print -# update and print available values every 5 seconds -while (1): + # update and print available values every 5 seconds + while (1): # update our values sensor.update(); @@ -94,4 +95,7 @@ while (1): print sensor.getRelayState() print - time.sleep(5) + time.sleep(5) + +if __name__ == '__main__': + main() diff --git a/examples/python/ta12200.py b/examples/python/ta12200.py old mode 100644 new mode 100755 index 7fce6abb..4c6bcf7f --- a/examples/python/ta12200.py +++ b/examples/python/ta12200.py @@ -24,31 +24,33 @@ import time, sys, signal, atexit import pyupm_ta12200 as upmTa12200 -# Instantiate a TA12-200 sensor on analog pin A0 -myElectricitySensor = upmTa12200.TA12200(0) +def main(): + # Instantiate a TA12-200 sensor on analog pin A0 + myElectricitySensor = upmTa12200.TA12200(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myElectricitySensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myElectricitySensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # get the data every 50 milliseconds + while(1): + maxVal = myElectricitySensor.highestValue() + current = myElectricitySensor.milliAmps(maxVal) + outputStr = "Max ADC Value: %s, current: %smA" % (maxVal, current) + print outputStr + time.sleep(.1) -# get the data every 50 milliseconds -while(1): - maxVal = myElectricitySensor.highestValue() - current = myElectricitySensor.milliAmps(maxVal) - - outputStr = "Max ADC Value: %s, current: %smA" % (maxVal, current) - print outputStr - time.sleep(.1) +if __name__ == '__main__': + main() diff --git a/examples/python/tb7300.py b/examples/python/tb7300.py old mode 100644 new mode 100755 index 93e879d3..6ce55ca5 --- a/examples/python/tb7300.py +++ b/examples/python/tb7300.py @@ -24,67 +24,68 @@ import time, sys, signal, atexit import pyupm_tb7300 as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# You will need to edit this example to conform to your site and your -# devices, specifically the Device Object Instance ID passed to the -# constructor, and the arguments to initMaster() that are -# appropriate for your BACnet network. + # You will need to edit this example to conform to your site and your + # devices, specifically the Device Object Instance ID passed to the + # constructor, and the arguments to initMaster() that are + # appropriate for your BACnet network. -defaultDev = "/dev/ttyUSB0" + defaultDev = "/dev/ttyUSB0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an TB7300 object for an TB7300 device that has 73001 -# as it's unique Device Object Instance ID. NOTE: You will -# certainly want to change this to the correct value for your -# device(s). -sensor = sensorObj.TB7300(73001) + # Instantiate an TB7300 object for an TB7300 device that has 73001 + # as it's unique Device Object Instance ID. NOTE: You will + # certainly want to change this to the correct value for your + # device(s). + sensor = sensorObj.TB7300(73001) -# Initialize our BACnet master, if it has not already been -# initialized, with the device and baudrate, choosing 1000001 as -# our unique Device Object Instance ID, 2 as our MAC address and -# using default values for maxMaster and maxInfoFrames -sensor.initMaster(defaultDev, 38400, 1000001, 2) + # Initialize our BACnet master, if it has not already been + # initialized, with the device and baudrate, choosing 1000001 as + # our unique Device Object Instance ID, 2 as our MAC address and + # using default values for maxMaster and maxInfoFrames + sensor.initMaster(defaultDev, 38400, 1000001, 2) -# Uncomment to enable debugging output -# sensor.setDebug(True); + # Uncomment to enable debugging output + # sensor.setDebug(True); -# output the serial number and firmware revision -print -print "Device Name:", sensor.getDeviceName() -print "Device Description:", sensor.getDeviceDescription() -print "Device Location:", sensor.getDeviceLocation() -print + # output the serial number and firmware revision + print + print "Device Name:", sensor.getDeviceName() + print "Device Description:", sensor.getDeviceDescription() + print "Device Location:", sensor.getDeviceLocation() + print -print "Fan Mode:", sensor.getMultiStateValueText(sensorObj.TB7300.MV_Fan_Mode) -print "Fan Status:", -print sensor.getMultiStateValueText(sensorObj.TB7300.MV_Fan_Status) -print "System Mode:", -print sensor.getMultiStateValueText(sensorObj.TB7300.MV_System_Mode) -print "Service Alarm:", -print sensor.getBinaryInputText(sensorObj.TB7300.BI_Service_Alarm) -print + print "Fan Mode:", sensor.getMultiStateValueText(sensorObj.TB7300.MV_Fan_Mode) + print "Fan Status:", + print sensor.getMultiStateValueText(sensorObj.TB7300.MV_Fan_Status) + print "System Mode:", + print sensor.getMultiStateValueText(sensorObj.TB7300.MV_System_Mode) + print "Service Alarm:", + print sensor.getBinaryInputText(sensorObj.TB7300.BI_Service_Alarm) + print -# update and print the room temperature every 5 seconds -while (1): + # update and print the room temperature every 5 seconds + while (1): # update our values sensor.update(); @@ -93,4 +94,7 @@ while (1): print "C /", sensor.getTemperature(True), "F" print - time.sleep(5) + time.sleep(5) + +if __name__ == '__main__': + main() diff --git a/examples/python/tcs3414cs.py b/examples/python/tcs3414cs.py old mode 100644 new mode 100755 index 7b7fae0d..ad8806eb --- a/examples/python/tcs3414cs.py +++ b/examples/python/tcs3414cs.py @@ -24,32 +24,34 @@ import time, sys, signal, atexit import pyupm_tcs3414cs as upmTcs3414cs -# Instantiate the color sensor on I2C -myColorSensor = upmTcs3414cs.TCS3414CS() +def main(): + # Instantiate the color sensor on I2C + myColorSensor = upmTcs3414cs.TCS3414CS() + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + # This lets you run code on exit, + # including functions from myColorSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This lets you run code on exit, -# including functions from myColorSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + myrgb = upmTcs3414cs.tcs3414sc_rgb_t() + # Print out the r, g, b, and clr value every 0.5 seconds + while(1): + myColorSensor.readRGB(myrgb) + print "{0}, {1}, {2}, {3}".format(myrgb.r, + myrgb.g, myrgb.b, myrgb.clr) -myrgb = upmTcs3414cs.tcs3414sc_rgb_t() + time.sleep(.5) -# Print out the r, g, b, and clr value every 0.5 seconds -while(1): - myColorSensor.readRGB(myrgb) - print "{0}, {1}, {2}, {3}".format(myrgb.r, - myrgb.g, myrgb.b, myrgb.clr) - - time.sleep(.5) +if __name__ == '__main__': + main() diff --git a/examples/python/teams.py b/examples/python/teams.py old mode 100644 new mode 100755 index 8acfa092..0092e2fc --- a/examples/python/teams.py +++ b/examples/python/teams.py @@ -24,35 +24,36 @@ import time, sys, signal, atexit import pyupm_teams as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Initializing..." + print "Initializing..." -# Instantiate an TEAMS instance, using A0 for temperature, and -# 165.0 ohms for the rResistor value (for the libelium 4-20ma -# interface) -sensor = sensorObj.TEAMS(0, 165.0) + # Instantiate an TEAMS instance, using A0 for temperature, and + # 165.0 ohms for the rResistor value (for the libelium 4-20ma + # interface) + sensor = sensorObj.TEAMS(0, 165.0) -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() # is the sensor connected? (current >= 4ma) print "Is Connected:", sensor.isConnected() - + # print computed current on the loop. This includes the offset, # if one was set by setOffsetMilliamps(). print "Milliamps:", sensor.getRawMilliamps() @@ -62,4 +63,7 @@ while (1): print sensor.getTemperature(True), "F" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/temperature.py b/examples/python/temperature.py old mode 100644 new mode 100755 index 7182349b..ba19850e --- a/examples/python/temperature.py +++ b/examples/python/temperature.py @@ -24,18 +24,22 @@ import time import pyupm_temperature as upm -# Create the temperature sensor object using AIO pin 0 -temp = upm.Temperature(0) -print temp.name() +def main(): + # Create the temperature sensor object using AIO pin 0 + temp = upm.Temperature(0) + print temp.name() -# Read the temperature ten times, printing both the Celsius and -# equivalent Fahrenheit temperature, waiting one second between readings -for i in range(0, 10): - celsius = temp.value() - fahrenheit = celsius * 9.0/5.0 + 32.0; - print "%d degrees Celsius, or %d degrees Fahrenheit" \ - % (celsius, fahrenheit) - time.sleep(1) + # Read the temperature ten times, printing both the Celsius and + # equivalent Fahrenheit temperature, waiting one second between readings + for i in range(0, 10): + celsius = temp.value() + fahrenheit = celsius * 9.0/5.0 + 32.0; + print "%d degrees Celsius, or %d degrees Fahrenheit" \ + % (celsius, fahrenheit) + time.sleep(1) -# Delete the temperature sensor object -del temp + # Delete the temperature sensor object + del temp + +if __name__ == '__main__': + main() diff --git a/examples/python/tex00.py b/examples/python/tex00.py old mode 100644 new mode 100755 index da427960..bd38eb67 --- a/examples/python/tex00.py +++ b/examples/python/tex00.py @@ -24,42 +24,46 @@ import time, sys, signal, atexit import pyupm_tex00 as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -print "Initializing..." + print "Initializing..." -# Instantiate an TEX00 instance, using A0 for the analog input. In -# this example, we are using a 10K Ohm balance resistor and a TED -# (10k type 2) thermistor. -sensor = sensorObj.TEX00(0, 10000, sensorObj.TEX00.STYPE_THERMISTOR_TED) + # Instantiate an TEX00 instance, using A0 for the analog input. In + # this example, we are using a 10K Ohm balance resistor and a TED + # (10k type 2) thermistor. + sensor = sensorObj.TEX00(0, 10000, sensorObj.TEX00.STYPE_THERMISTOR_TED) -print "Minimum temperature:", sensor.getTemperatureRangeMin(), "C" -print "Maximum temperature:", sensor.getTemperatureRangeMax(), "C" -print + print "Minimum temperature:", sensor.getTemperatureRangeMin(), "C" + print "Maximum temperature:", sensor.getTemperatureRangeMax(), "C" + print -# update and print available values every second -while (1): + # update and print available values every second + while (1): # update our values from the sensor sensor.update() if (sensor.isOutOfRange()): - print "Temperature out of range" + print "Temperature out of range" else: - # we show both C and F for temperature - print "Temperature:", sensor.getTemperature(), "C /", - print sensor.getTemperature(True), "F" + # we show both C and F for temperature + print "Temperature:", sensor.getTemperature(), "C /", + print sensor.getTemperature(True), "F" print - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/tm1637.py b/examples/python/tm1637.py old mode 100644 new mode 100755 index 8c757444..0a9f1888 --- a/examples/python/tm1637.py +++ b/examples/python/tm1637.py @@ -23,32 +23,36 @@ import time, signal import pyupm_tm1637 as tm1637 -# Register exit handler for normal Ctrl+C exit -def SIGINTHandler(signum, frame): - raise SystemExit -signal.signal(signal.SIGINT, SIGINTHandler) +def main(): + # Register exit handler for normal Ctrl+C exit + def SIGINTHandler(signum, frame): + raise SystemExit + signal.signal(signal.SIGINT, SIGINTHandler) -# Create a display object on pins 0 CLK and 1 DIO -display = tm1637.TM1637(0, 1) -dots = True + # Create a display object on pins 0 CLK and 1 DIO + display = tm1637.TM1637(0, 1) + dots = True -# Get local time -myTime = time.localtime(time.time()) -print time.strftime("System time: %H:%M", myTime) -print ("You can adjust your time zone by setting the TZ environment variable.") + # Get local time + myTime = time.localtime(time.time()) + print time.strftime("System time: %H:%M", myTime) + print ("You can adjust your time zone by setting the TZ environment variable.") -# Draw a box for 3 seconds using 7-segment encoding -display.write(0x39, 0x09, 0x09, 0x0f) -time.sleep(3) + # Draw a box for 3 seconds using 7-segment encoding + display.write(0x39, 0x09, 0x09, 0x0f) + time.sleep(3) -# Loop indefinitely -while True: - # Update and display time - timeString = time.strftime("%H%M", time.localtime(time.time())) - display.write(timeString) - # Toggle colon - display.setColon(dots) - dots = not dots + # Loop indefinitely + while True: + # Update and display time + timeString = time.strftime("%H%M", time.localtime(time.time())) + display.write(timeString) + # Toggle colon + display.setColon(dots) + dots = not dots - # Sleep for 1 s - time.sleep(1) + # Sleep for 1 s + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/tp401.py b/examples/python/tp401.py old mode 100644 new mode 100755 index 55195087..5ec4d303 --- a/examples/python/tp401.py +++ b/examples/python/tp401.py @@ -23,32 +23,35 @@ from time import sleep import pyupm_gas as TP401 -# Give a qualitative meaning to the value from the sensor -def airQuality(value): - if(value < 50): return "Fresh Air" - if(value < 200): return "Normal Indoor Air" - if(value < 400): return "Low Pollution" - if(value < 600): return "High Pollution - Action Recommended" - return "Very High Pollution - Take Action Immediately" +def main(): + # Give a qualitative meaning to the value from the sensor + def airQuality(value): + if(value < 50): return "Fresh Air" + if(value < 200): return "Normal Indoor Air" + if(value < 400): return "Low Pollution" + if(value < 600): return "High Pollution - Action Recommended" + return "Very High Pollution - Take Action Immediately" -# New Grove Air Quality Sensor on AIO pin 0 -airSensor = TP401.TP401(0) + # New Grove Air Quality Sensor on AIO pin 0 + airSensor = TP401.TP401(0) -# Wait for sensor to warm up -print "Sensor is warming up for 3 minutes..." -for i in range (1, 4): - sleep(60) - print i, "minute(s) passed." -print "Sensor is ready!" + # Wait for sensor to warm up + print "Sensor is warming up for 3 minutes..." + for i in range (1, 4): + sleep(60) + print i, "minute(s) passed." + print "Sensor is ready!" -# Loop indefinitely -while True: + # Loop indefinitely + while True: + # Read values (consecutive reads might vary slightly) + value = airSensor.getSample() + ppm = airSensor.getPPM() - # Read values (consecutive reads might vary slightly) - value = airSensor.getSample() - ppm = airSensor.getPPM() + print "raw: %4d" % value , " ppm: %5.2f " % ppm , airQuality(value) - print "raw: %4d" % value , " ppm: %5.2f " % ppm , airQuality(value) + # Sleep for 2.5 s + sleep(2.5) - # Sleep for 2.5 s - sleep(2.5) +if __name__ == '__main__': + main() diff --git a/examples/python/tsl2561.py b/examples/python/tsl2561.py old mode 100644 new mode 100755 index 35a33367..c1ad67c4 --- a/examples/python/tsl2561.py +++ b/examples/python/tsl2561.py @@ -24,25 +24,27 @@ import time, sys, signal, atexit import pyupm_tsl2561 as upmTsl2561 -# Instantiate a digital light sensor TSL2561 on I2C -myDigitalLightSensor = upmTsl2561.TSL2561() +def main(): + # Instantiate a digital light sensor TSL2561 on I2C + myDigitalLightSensor = upmTsl2561.TSL2561() + ## 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 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, including functions from myDigitalLightSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myDigitalLightSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + print "Light value is " + str(myDigitalLightSensor.getLux()) + time.sleep(1) - -while(1): - print "Light value is " + str(myDigitalLightSensor.getLux()) - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/ttp223.py b/examples/python/ttp223.py old mode 100644 new mode 100755 index 7d1c847e..e9ccf47a --- a/examples/python/ttp223.py +++ b/examples/python/ttp223.py @@ -23,17 +23,21 @@ import time import pyupm_ttp223 as ttp223 -# Create the TTP223 touch sensor object using GPIO pin 0 -touch = ttp223.TTP223(0) +def main(): + # Create the TTP223 touch sensor object using GPIO pin 0 + touch = ttp223.TTP223(0) -# Check whether or not a finger is near the touch sensor and -# print accordingly, waiting one second between readings -while 1: - if touch.isPressed(): - print touch.name(), 'is pressed' - else: - print touch.name(), 'is not pressed' - time.sleep(1) + # Check whether or not a finger is near the touch sensor and + # print accordingly, waiting one second between readings + while 1: + if touch.isPressed(): + print touch.name(), 'is pressed' + else: + print touch.name(), 'is not pressed' + time.sleep(1) -# Delete the touch sensor object -del touch + # Delete the touch sensor object + del touch + +if __name__ == '__main__': + main() diff --git a/examples/python/tzemt400.py b/examples/python/tzemt400.py old mode 100644 new mode 100755 index d70bb9f2..7b10b85f --- a/examples/python/tzemt400.py +++ b/examples/python/tzemt400.py @@ -24,37 +24,38 @@ import time, sys, signal, atexit import pyupm_ozw as sensorObj -# This function lets you run code on exit -def exitHandler(): - print "Exiting..." - sys.exit(0) +def main(): + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) + # Register exit handlers + atexit.register(exitHandler) -defaultDev = "/dev/ttyACM0" -if (len(sys.argv) > 1): + defaultDev = "/dev/ttyACM0" + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev + print "Using device", defaultDev -# Instantiate a TZEMT400 instance, on device node 13. You will -# almost certainly need to change this to reflect your own network. -# Use the ozwdump example to see what nodes are available. -sensor = sensorObj.TZEMT400(13) + # Instantiate a TZEMT400 instance, on device node 13. You will + # almost certainly need to change this to reflect your own network. + # Use the ozwdump example to see what nodes are available. + sensor = sensorObj.TZEMT400(13) -# The first thing to do is create options, then lock them when done. -sensor.optionsCreate() -sensor.optionsLock() + # The first thing to do is create options, then lock them when done. + sensor.optionsCreate() + sensor.optionsLock() -# Next, initialize it. -print "Initializing, this may take awhile depending on your ZWave network" + # Next, initialize it. + print "Initializing, this may take awhile depending on your ZWave network" -sensor.init(defaultDev) -print "Initialization complete" + sensor.init(defaultDev) + print "Initialization complete" -print "Querying data..." + print "Querying data..." -while (True): + while (True): sensor.update() print "Temperature:", sensor.getTemperature(), "C /", @@ -80,3 +81,6 @@ while (True): print time.sleep(5) + +if __name__ == '__main__': + main() diff --git a/examples/python/uln200xa.py b/examples/python/uln200xa.py old mode 100644 new mode 100755 index e926e468..905c618d --- a/examples/python/uln200xa.py +++ b/examples/python/uln200xa.py @@ -21,46 +21,48 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import time, sys, signal, atexit import pyupm_uln200xa as upmULN200XA -# Instantiate a Stepper motor on a ULN200XA Darlington Motor Driver -# This was tested with the Grove Geared Step Motor with Driver +def main(): + # Instantiate a Stepper motor on a ULN200XA Darlington Motor Driver + # This was tested with the Grove Geared Step Motor with Driver -# Instantiate a ULN2003XA stepper object -myUln200xa = upmULN200XA.ULN200XA(4096, 8, 9, 10, 11) + # Instantiate a ULN2003XA stepper object + myUln200xa = upmULN200XA.ULN200XA(4096, 8, 9, 10, 11) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -# This lets you run code on exit, -# including functions from myUln200xa -def exitHandler(): - print "Exiting" - sys.exit(0) + # This lets you run code on exit, + # including functions from myUln200xa + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) + myUln200xa.setSpeed(5) # 5 RPMs + myUln200xa.setDirection(upmULN200XA.ULN200XA.DIR_CW) -myUln200xa.setSpeed(5) # 5 RPMs -myUln200xa.setDirection(upmULN200XA.ULN200XA.DIR_CW) + print "Rotating 1 revolution clockwise." + myUln200xa.stepperSteps(4096) -print "Rotating 1 revolution clockwise." -myUln200xa.stepperSteps(4096) + print "Sleeping for 2 seconds..." + time.sleep(2) -print "Sleeping for 2 seconds..." -time.sleep(2) + print "Rotating 1/2 revolution counter clockwise." + myUln200xa.setDirection(upmULN200XA.ULN200XA.DIR_CCW) + myUln200xa.stepperSteps(2048) -print "Rotating 1/2 revolution counter clockwise." -myUln200xa.setDirection(upmULN200XA.ULN200XA.DIR_CCW) -myUln200xa.stepperSteps(2048) + # release + myUln200xa.release() -# release -myUln200xa.release() + # exitHandler is called automatically -# exitHandler is called automatically +if __name__ == '__main__': + main() diff --git a/examples/python/urm37-uart.py b/examples/python/urm37-uart.py old mode 100644 new mode 100755 index 8e6ee80d..d848d78f --- a/examples/python/urm37-uart.py +++ b/examples/python/urm37-uart.py @@ -24,27 +24,31 @@ import time, sys, signal, atexit import pyupm_urm37 as sensorObj -# Instantiate a URM37 sensor on UART 0, with the reset pin on D2 -sensor = sensorObj.URM37(0, 2) +def main(): + # Instantiate a URM37 sensor on UART 0, with the reset pin on D2 + sensor = sensorObj.URM37(0, 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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every half a second, sample the URM37 and output the measured -# distance in cm, and temperature in degrees C + # Every half a second, sample the URM37 and output the measured + # distance in cm, and temperature in degrees C -while (1): + while (1): print "Detected distance (cm):", sensor.getDistance() print "Temperature (C):", sensor.getTemperature() - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/urm37.py b/examples/python/urm37.py old mode 100644 new mode 100755 index fa977aa9..cf2357bd --- a/examples/python/urm37.py +++ b/examples/python/urm37.py @@ -24,27 +24,31 @@ import time, sys, signal, atexit import pyupm_urm37 as sensorObj -# Instantiate a URM37 sensor on analog pin A0, reset pin on D2, -# trigger pin on D3 with an analog reference voltage of 5.0 -sensor = sensorObj.URM37(0, 2, 3, 5.0) +def main(): + # Instantiate a URM37 sensor on analog pin A0, reset pin on D2, + # trigger pin on D3 with an analog reference voltage of 5.0 + sensor = sensorObj.URM37(0, 2, 3, 5.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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Every half a second, sample the URM37 and output the measured -# distance in cm. + # Every half a second, sample the URM37 and output the measured + # distance in cm. -while (1): + while (1): print "Detected distance (cm):", sensor.getDistance() - time.sleep(.5) + time.sleep(.5) + +if __name__ == '__main__': + main() diff --git a/examples/python/using_carrays.py b/examples/python/using_carrays.py deleted file mode 100644 index 730cb365..00000000 --- a/examples/python/using_carrays.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python - -# Author: Brendan Le Foll -# Copyright (c) 2014 Intel Corporation. -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE - -import pyupm_mic - -mymic = pyupm_mic.Microphone(1) -# careful this is an unitialised array with no bounds checking! -x = pyupm_mic.uint16Array(3) -mymic.getSampledWindow(100, 3, x) - diff --git a/examples/python/vcap.py b/examples/python/vcap.py old mode 100644 new mode 100755 index dfd23a46..0caa7156 --- a/examples/python/vcap.py +++ b/examples/python/vcap.py @@ -24,44 +24,47 @@ import time, sys, signal, atexit import pyupm_vcap as sensorObj -## Exit handlers ## -# This function stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit +def main(): + ## Exit handlers ## + # This function 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 -def exitHandler(): - print "Exiting..." - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting..." + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -defaultDev = "/dev/video0" + defaultDev = "/dev/video0" -# if an argument was specified, use it as the device instead -if (len(sys.argv) > 1): + # if an argument was specified, use it as the device instead + if (len(sys.argv) > 1): defaultDev = sys.argv[1] -print "Using device", defaultDev -print "Initializing..." + print "Using device", defaultDev + print "Initializing..." -# Instantiate an VCAP instance, using the specified video device -sensor = sensorObj.VCAP(defaultDev) + # Instantiate an VCAP instance, using the specified video device + sensor = sensorObj.VCAP(defaultDev) -# enable some debug/verbose output -sensor.setDebug(True); + # enable some debug/verbose output + sensor.setDebug(True); -# This is just a hint. The kernel can change this to a lower -# resolution that the hardware supports. Use getWidth() and -# getHeight() methods to see what the kernel actually chose if you -# care. -sensor.setResolution(1920, 1080); + # This is just a hint. The kernel can change this to a lower + # resolution that the hardware supports. Use getWidth() and + # getHeight() methods to see what the kernel actually chose if you + # care. + sensor.setResolution(1920, 1080); -# capture an image -sensor.captureImage(); + # capture an image + sensor.captureImage(); -# convert and save it as a jpeg -sensor.saveImage("video-img1.jpg"); + # convert and save it as a jpeg + sensor.saveImage("video-img1.jpg"); +if __name__ == '__main__': + main() diff --git a/examples/python/vdiv.py b/examples/python/vdiv.py old mode 100644 new mode 100755 index 03a6a014..2e886564 --- a/examples/python/vdiv.py +++ b/examples/python/vdiv.py @@ -24,31 +24,33 @@ import time, sys, signal, atexit import pyupm_vdiv as upmvdiv -# Instantiate a Voltage Divider sensor on analog pin A0 -myVoltageDivider = upmvdiv.VDiv(0) +def main(): + # Instantiate a Voltage Divider sensor on analog pin A0 + myVoltageDivider = upmvdiv.VDiv(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myVoltageDivider + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myVoltageDivider -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + val = myVoltageDivider.value(100) + 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): - val = myVoltageDivider.value(100) - 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) +if __name__ == '__main__': + main() diff --git a/examples/python/water.py b/examples/python/water.py old mode 100644 new mode 100755 index ff7f73b9..eee34e07 --- a/examples/python/water.py +++ b/examples/python/water.py @@ -24,28 +24,30 @@ import time, sys, signal, atexit import pyupm_water as upmwater -# Instantiate a Water sensor on digital pin D2 -myWaterSensor = upmwater.Water(2) +def main(): + # Instantiate a Water sensor on digital pin D2 + myWaterSensor = upmwater.Water(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 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, including functions from myWaterSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myWaterSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myWaterSensor.isWet()): + print "Sensor is wet" + else: + print "Sensor is dry" + time.sleep(1) - -while(1): - if (myWaterSensor.isWet()): - print "Sensor is wet" - else: - print "Sensor is dry" - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/waterlevel.py b/examples/python/waterlevel.py old mode 100644 new mode 100755 index 18309e48..35c9c9fe --- a/examples/python/waterlevel.py +++ b/examples/python/waterlevel.py @@ -24,31 +24,33 @@ import time, sys, signal, atexit import pyupm_waterlevel as upmWaterlevel -# The was tested with the Water Level Sensor -# Instantiate a Water Level Sensor on digital pin D2 -myWaterLevel = upmWaterlevel.WaterLevel(2) +def main(): + # The was tested with the Water Level Sensor + # Instantiate a Water Level Sensor on digital pin D2 + myWaterLevel = upmWaterlevel.WaterLevel(2) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myWaterLevel + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myWaterLevel -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myWaterLevel.isSubmerged()): + print "Sensor is submerged in liquid" + else: + print "Liquid is below water level sensor" + time.sleep(1) -while(1): - if (myWaterLevel.isSubmerged()): - print "Sensor is submerged in liquid" - else: - print "Liquid is below water level sensor" - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/wfs.py b/examples/python/wfs.py old mode 100644 new mode 100755 index ce7f70af..b5aa0e94 --- a/examples/python/wfs.py +++ b/examples/python/wfs.py @@ -24,41 +24,43 @@ import time, sys, signal, atexit import pyupm_wfs as upmwfs -# Instantiate a Water Flow Sensor on digital pin D2 -myWaterFlow = upmwfs.WFS(2) +def main(): + # Instantiate a Water Flow Sensor on digital pin D2 + myWaterFlow = upmwfs.WFS(2) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myWaterFlow + def exitHandler(): + myWaterFlow.stopFlowCounter() + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myWaterFlow -def exitHandler(): - myWaterFlow.stopFlowCounter() - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # set the flow counter to 0 and start counting + myWaterFlow.clearFlowCounter() + 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 -myWaterFlow.clearFlowCounter() -myWaterFlow.startFlowCounter() + fr = myWaterFlow.flowRate() -while (1): - # we grab these (millis and flowCount) just for display - # purposes in this example - millis = myWaterFlow.getMillis() - flowCount = myWaterFlow.flowCounter() + # 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) - fr = myWaterFlow.flowRate() - - # 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) +if __name__ == '__main__': + main() diff --git a/examples/python/wheelencoder.py b/examples/python/wheelencoder.py old mode 100644 new mode 100755 index b61cc872..d136b801 --- a/examples/python/wheelencoder.py +++ b/examples/python/wheelencoder.py @@ -24,27 +24,31 @@ import time, sys, signal, atexit import pyupm_wheelencoder as sensorObj -# Instantiate a DFRobot Wheel Encoder on digital pin D2 -sensor = sensorObj.WheelEncoder(2) +def main(): + # Instantiate a DFRobot Wheel Encoder on digital pin D2 + sensor = sensorObj.WheelEncoder(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 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# set the counter to 0 and start counting -sensor.clearCounter(); -sensor.startCounter(); + # set the counter to 0 and start counting + sensor.clearCounter(); + sensor.startCounter(); -while (1): + while (1): print "Millis:", sensor.getMillis(), "Count:", sensor.counter() - time.sleep(1) + time.sleep(1) + +if __name__ == '__main__': + main() diff --git a/examples/python/wt5001.py b/examples/python/wt5001.py old mode 100644 new mode 100755 index 315799cc..c1c251b5 --- a/examples/python/wt5001.py +++ b/examples/python/wt5001.py @@ -24,84 +24,83 @@ import time, signal, sys import pyupm_wt5001 as upmWt5001 -# Instantiate a WT5001 serial MP3 player on uart 0. -# This example was tested on the Grove Serial MP3 module. -myMP3Player = upmWt5001.WT5001(0) +def main(): + # Instantiate a WT5001 serial MP3 player on uart 0. + # This example was tested on the Grove Serial MP3 module. + myMP3Player = upmWt5001.WT5001(0) + def printUsage(progname): + print ("Usage: python " + progname + " \n" + "Commands:\n" + "0 - stop playing\n" + "1 - start playing track 1\n" + "2 - pause/un-pause playback\n" + "3 - next track\n" + "4 - previous track") -def printUsage(progname): - print ("Usage: python " + progname + " \n" - "Commands:\n" - "0 - stop playing\n" - "1 - start playing track 1\n" - "2 - pause/un-pause playback\n" - "3 - next track\n" - "4 - previous track") + cmd = -1; + if (len(sys.argv) > 1): + cmd = int(sys.argv[1]) + if (not myMP3Player.setupTty(upmWt5001.cvar.int_B9600)): + print "Failed to setup tty port parameters" + sys.exit(0) -cmd = -1; -if (len(sys.argv) > 1): - cmd = int(sys.argv[1]) + if cmd == 0: + myMP3Player.stop() + elif cmd == 1: + myMP3Player.play(upmWt5001.WT5001.SD, 1) + elif cmd == 2: + myMP3Player.pause() + elif cmd == 3: + myMP3Player.next() + elif cmd == 4: + myMP3Player.previous() + else: + # nothing, just output usage, and info below + printUsage(sys.argv[0]) -if (not myMP3Player.setupTty(upmWt5001.cvar.int_B9600)): - print "Failed to setup tty port parameters" - sys.exit(0) + # print out some information + vol = upmWt5001.uint8Array(0) + myMP3Player.getVolume(vol) + print "The current volume is: " + str(vol.__getitem__(0)) -if cmd == 0: - myMP3Player.stop() -elif cmd == 1: - myMP3Player.play(upmWt5001.WT5001.SD, 1) -elif cmd == 2: - myMP3Player.pause() -elif cmd == 3: - myMP3Player.next() -elif cmd == 4: - myMP3Player.previous() -else: - # nothing, just output usage, and info below - printUsage(sys.argv[0]) + ps = upmWt5001.uint8Array(0) + myMP3Player.getPlayState(ps) + print "The current play state is: " + str(ps.__getitem__(0)) + numf = upmWt5001.uint16Array(0) + myMP3Player.getNumFiles(upmWt5001.WT5001.SD, numf) + print "The number of files on the SD card is: " + str(numf.__getitem__(0)) -# print out some information -vol = upmWt5001.uint8Array(0) -myMP3Player.getVolume(vol) -print "The current volume is: " + str(vol.__getitem__(0)) + curf = upmWt5001.uint16Array(0) + myMP3Player.getCurrentFile(curf) + print "The current file is: " + str(curf.__getitem__(0)) -ps = upmWt5001.uint8Array(0) -myMP3Player.getPlayState(ps) -print "The current play state is: " + str(ps.__getitem__(0)) + # set the date + myMP3Player.setDate(2015, 3, 14) -numf = upmWt5001.uint16Array(0) -myMP3Player.getNumFiles(upmWt5001.WT5001.SD, numf) -print "The number of files on the SD card is: " + str(numf.__getitem__(0)) + # set the time + myMP3Player.setTime(9, 26, 53) -curf = upmWt5001.uint16Array(0) -myMP3Player.getCurrentFile(curf) -print "The current file is: " + str(curf.__getitem__(0)) + year = upmWt5001.uint16Array(0) + month = upmWt5001.uint8Array(0) + day = upmWt5001.uint8Array(0) + myMP3Player.getDate(year, month, day) + mp3date = str(month.__getitem__(0)) + "/" + mp3date += (str(day.__getitem__(0)) + "/") + mp3date += str(year.__getitem__(0)) + print "The device date is: " + mp3date -# set the date -myMP3Player.setDate(2015, 3, 14) + hour = upmWt5001.uint8Array(0) + minute = upmWt5001.uint8Array(0) + second = upmWt5001.uint8Array(0) + myMP3Player.getTime(hour, minute, second) + mp3time = str(hour.__getitem__(0)) + ":" + mp3time += (str(minute.__getitem__(0)) + ":") + mp3time += str(second.__getitem__(0)) + print "The device time is: " + mp3time -# set the time -myMP3Player.setTime(9, 26, 53) - - -year = upmWt5001.uint16Array(0) -month = upmWt5001.uint8Array(0) -day = upmWt5001.uint8Array(0) - -myMP3Player.getDate(year, month, day) -mp3date = str(month.__getitem__(0)) + "/" -mp3date += (str(day.__getitem__(0)) + "/") -mp3date += str(year.__getitem__(0)) -print "The device date is: " + mp3date - -hour = upmWt5001.uint8Array(0) -minute = upmWt5001.uint8Array(0) -second = upmWt5001.uint8Array(0) -myMP3Player.getTime(hour, minute, second) -mp3time = str(hour.__getitem__(0)) + ":" -mp3time += (str(minute.__getitem__(0)) + ":") -mp3time += str(second.__getitem__(0)) -print "The device time is: " + mp3time +if __name__ == '__main__': + main() diff --git a/examples/python/xbee.py b/examples/python/xbee.py old mode 100644 new mode 100755 index 3ca37207..43a2e0d3 --- a/examples/python/xbee.py +++ b/examples/python/xbee.py @@ -24,60 +24,59 @@ import time, sys, signal, atexit import pyupm_xbee as sensorObj -# Instantiate a XBee Module on UART 0 -sensor = sensorObj.XBee(0) +def main(): + # Instantiate a XBee Module on UART 0 + sensor = sensorObj.XBee(0) -## Exit handlers ## -# This stops python from printing a stacktrace when you hit control-C -def SIGINTHandler(signum, frame): - raise SystemExit + ## Exit handlers ## + # 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 -def exitHandler(): - print "Exiting" - sys.exit(0) + # This function lets you run code on exit + def exitHandler(): + print "Exiting" + sys.exit(0) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Set the baud rate, 9600 baud is the default. -if (sensor.setBaudRate(9600)): - print "Failed to set baud rate" - sys.exit(0) + # Set the baud rate, 9600 baud is the default. + if (sensor.setBaudRate(9600)): + print "Failed to set baud rate" + 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 firmware revision, serial number\n" + "and the current IP address (if set) are queried.\n\n") + print usageStr -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 firmware revision, serial number\n" -"and the current IP address (if set) are queried.\n\n") -print usageStr - -# simple helper function to send a command and wait for a response -def sendCommand(sensor, cmd): + # 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 cmd += "\r" - sensor.writeDataStr(cmd) + sensor.writeDataStr(cmd) resp = "" - while sensor.dataAvailable(2000): - resp += sensor.readDataStr(1024) + while sensor.dataAvailable(2000): + resp += sensor.readDataStr(1024) if not resp: - print "Timed out waiting for response" + print "Timed out waiting for response" else: - resp = sensor.stringCR2LF(resp) - print "Returned (", len(resp), "bytes):" - print resp + resp = sensor.stringCR2LF(resp) + print "Returned (", len(resp), "bytes):" + print resp - -if (len(sys.argv) > 1): + if (len(sys.argv) > 1): # enable command mode sensor.commandMode() - print "Sending command line argument (" + sys.argv[1] + ")..." - sendCommand(sensor, sys.argv[1]) -else: + print "Sending command line argument (" + sys.argv[1] + ")..." + sendCommand(sensor, sys.argv[1]) + else: # enable command mode sensor.commandMode() # query the verbose firmware revision @@ -96,22 +95,24 @@ else: # A comprehensive list of commands and command modes is # available from the datasheet at: # ftp1.digi.com/support/documentation/90002180_L.pdf - + # For the XBee S1 # A comprehensive list of commands and command modes is # available from the datasheet at: # http://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf - + # For the XBee WiFi module: # An example using AT commands to connect to an AP, with a # private Key using WPA2: - + # Connect to AP with SSID 'mySSID': # ATIDmySSID - + # Provide the private key 'secret': # ATPKsecret - + # Use WPA2 encryption # ATEE2 +if __name__ == '__main__': + main() diff --git a/examples/python/yg1006.py b/examples/python/yg1006.py old mode 100644 new mode 100755 index 6f21c1dc..85d645f8 --- a/examples/python/yg1006.py +++ b/examples/python/yg1006.py @@ -24,29 +24,31 @@ import time, sys, signal, atexit import pyupm_yg1006 as upmYG1006 -# Instantiate a flame sensor on digital pin D2 -myFlameSensor = upmYG1006.YG1006(2) +def main(): + # Instantiate a flame sensor on digital pin D2 + myFlameSensor = upmYG1006.YG1006(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 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, including functions from myFlameSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, including functions from myFlameSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + while(1): + if (myFlameSensor.flameDetected()): + print "Flame detected." + else: + print "No flame detected." + time.sleep(1) -while(1): - if (myFlameSensor.flameDetected()): - print "Flame detected." - else: - print "No flame detected." - - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/examples/python/zfm20-register.py b/examples/python/zfm20-register.py old mode 100644 new mode 100755 index 589a4dfc..79224c93 --- a/examples/python/zfm20-register.py +++ b/examples/python/zfm20-register.py @@ -24,109 +24,108 @@ import time, sys, signal, atexit import pyupm_zfm20 as upmZfm20 -# Instantiate a ZFM20 Fingerprint reader on UART 0 -myFingerprintSensor = upmZfm20.ZFM20(0) +def main(): + # Instantiate a ZFM20 Fingerprint reader on UART 0 + myFingerprintSensor = upmZfm20.ZFM20(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myFingerprintSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myFingerprintSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # make sure port is initialized properly. 57600 baud is the default. + if (not myFingerprintSensor.setupTty(upmZfm20.cvar.int_B57600)): + print "Failed to setup tty port parameters" + sys.exit(1) + # This example demonstrates registering a fingerprint on the zfm20 + # module. The procedure is as follows: + # + # 1. get an image, store it in characteristics buffer 1 + # 2. get another image, store it in characteristics buffer 2 + # 3. store the image, assuming the two fingerprints match -# make sure port is initialized properly. 57600 baud is the default. -if (not myFingerprintSensor.setupTty(upmZfm20.cvar.int_B57600)): - print "Failed to setup tty port parameters" - sys.exit(1) + # first, we need to register our address and password + myFingerprintSensor.setPassword(upmZfm20.ZFM20_DEFAULT_PASSWORD) + myFingerprintSensor.setAddress(upmZfm20.ZFM20_DEFAULT_ADDRESS) -# This example demonstrates registering a fingerprint on the zfm20 -# module. The procedure is as follows: -# -# 1. get an image, store it in characteristics buffer 1 -# 2. get another image, store it in characteristics buffer 2 -# 3. store the image, assuming the two fingerprints match + # now verify the password. If this fails, any other commands + # will be ignored, so we just bail. + if (myFingerprintSensor.verifyPassword()): + print "Password verified." + else: + print "Password verification failed." + sys.exit(1) -# first, we need to register our address and password + print " " -myFingerprintSensor.setPassword(upmZfm20.ZFM20_DEFAULT_PASSWORD) -myFingerprintSensor.setAddress(upmZfm20.ZFM20_DEFAULT_ADDRESS) + # get the first image + print "Place a finger on the sensor." + while (myFingerprintSensor.generateImage() != upmZfm20.ZFM20.ERR_OK): + pass -# now verify the password. If this fails, any other commands -# will be ignored, so we just bail. -if (myFingerprintSensor.verifyPassword()): - print "Password verified." -else: - print "Password verification failed." - sys.exit(1) + # in theory, we have an image + print "Image captured, converting..." + rv = myFingerprintSensor.image2Tz(1) -print " " + if (rv != upmZfm20.ZFM20.ERR_OK): + print "Image conversion failed with error code %d" % rv + sys.exit(1) -# get the first image -print "Place a finger on the sensor." -while (myFingerprintSensor.generateImage() != upmZfm20.ZFM20.ERR_OK): - pass + print "Image conversion succeeded, remove finger." + time.sleep(1) -# in theory, we have an image -print "Image captured, converting..." + while (myFingerprintSensor.generateImage() != upmZfm20.ZFM20.ERR_NO_FINGER): + pass -rv = myFingerprintSensor.image2Tz(1) + print " " + print "Now place the same finger on the sensor." -if (rv != upmZfm20.ZFM20.ERR_OK): - print "Image conversion failed with error code %d" % rv - sys.exit(1) + while (myFingerprintSensor.generateImage() == upmZfm20.ZFM20.ERR_NO_FINGER): + pass -print "Image conversion succeeded, remove finger." -time.sleep(1) + print "Image captured, converting..." -while (myFingerprintSensor.generateImage() != upmZfm20.ZFM20.ERR_NO_FINGER): - pass + # save this one in slot 2 + rv = myFingerprintSensor.image2Tz(2) + if (rv != upmZfm20.ZFM20.ERR_OK): + print "Image conversion failed with error code %d" % rv + sys.exit(1) -print " " -print "Now place the same finger on the sensor." + print "Image conversion succeeded, remove finger." + print " " -while (myFingerprintSensor.generateImage() == upmZfm20.ZFM20.ERR_NO_FINGER): - pass + print "Storing fingerprint at id 1" -print "Image captured, converting..." + # create the model + rv = myFingerprintSensor.createModel() + if (rv != upmZfm20.ZFM20.ERR_OK): + if (rv == upmZfm20.ZFM20.ERR_FP_ENROLLMISMATCH): + print "Fingerprints did not match." + else: + print "createModel failed with error code %d" % rv + sys.exit(1) -# save this one in slot 2 -rv = myFingerprintSensor.image2Tz(2) -if (rv != upmZfm20.ZFM20.ERR_OK): - print "Image conversion failed with error code %d" % rv - sys.exit(1) + # now store it, we hard code the id (second arg) to 1 here + rv = myFingerprintSensor.storeModel(1, 1) + if (rv != upmZfm20.ZFM20.ERR_OK): + print "storeModel failed with error code %d" % rv + sys.exit(1) -print "Image conversion succeeded, remove finger." -print " " - -print "Storing fingerprint at id 1" - -# create the model -rv = myFingerprintSensor.createModel() -if (rv != upmZfm20.ZFM20.ERR_OK): - if (rv == upmZfm20.ZFM20.ERR_FP_ENROLLMISMATCH): - print "Fingerprints did not match." - else: - print "createModel failed with error code %d" % rv - sys.exit(1) - -# now store it, we hard code the id (second arg) to 1 here -rv = myFingerprintSensor.storeModel(1, 1) -if (rv != upmZfm20.ZFM20.ERR_OK): - print "storeModel failed with error code %d" % rv - sys.exit(1) - -print " " -print "Fingerprint stored at id 1." + print " " + print "Fingerprint stored at id 1." +if __name__ == '__main__': + main() diff --git a/examples/python/zfm20.py b/examples/python/zfm20.py old mode 100644 new mode 100755 index e813e474..b27bf622 --- a/examples/python/zfm20.py +++ b/examples/python/zfm20.py @@ -24,67 +24,69 @@ import time, sys, signal, atexit import pyupm_zfm20 as upmZfm20 -# Instantiate a ZFM20 Fingerprint reader on UART 0 -myFingerprintSensor = upmZfm20.ZFM20(0) +def main(): + # Instantiate a ZFM20 Fingerprint reader on UART 0 + myFingerprintSensor = upmZfm20.ZFM20(0) + ## Exit handlers ## + # This stops python from printing a stacktrace when you hit control-C + def SIGINTHandler(signum, frame): + raise SystemExit -## Exit handlers ## -# 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, + # including functions from myFingerprintSensor + def exitHandler(): + print "Exiting" + sys.exit(0) -# This function lets you run code on exit, -# including functions from myFingerprintSensor -def exitHandler(): - print "Exiting" - sys.exit(0) + # Register exit handlers + atexit.register(exitHandler) + signal.signal(signal.SIGINT, SIGINTHandler) -# Register exit handlers -atexit.register(exitHandler) -signal.signal(signal.SIGINT, SIGINTHandler) + # make sure port is initialized properly. 57600 baud is the default. + if (not myFingerprintSensor.setupTty(upmZfm20.cvar.int_B57600)): + print "Failed to setup tty port parameters" + sys.exit(1) + # how many valid stored templates (fingerprints) do we have? + print "Total stored templates: %d" % myFingerprintSensor.getNumTemplates() + print " " -# make sure port is initialized properly. 57600 baud is the default. -if (not myFingerprintSensor.setupTty(upmZfm20.cvar.int_B57600)): - print "Failed to setup tty port parameters" - sys.exit(1) + # now spin waiting for a fingerprint to successfully image + print "Waiting for finger print..." -# how many valid stored templates (fingerprints) do we have? -print "Total stored templates: %d" % myFingerprintSensor.getNumTemplates() -print " " + while (myFingerprintSensor.generateImage() == upmZfm20.ZFM20.ERR_NO_FINGER): + pass -# now spin waiting for a fingerprint to successfully image -print "Waiting for finger print..." + # in theory, we have an image + print "Image captured, converting..." -while (myFingerprintSensor.generateImage() == upmZfm20.ZFM20.ERR_NO_FINGER): - pass + rv = myFingerprintSensor.image2Tz(1) + if (rv != upmZfm20.ZFM20.ERR_OK): + print "Image conversion failed with error code %d" % rv + sys.exit(1) -# in theory, we have an image -print "Image captured, converting..." + print "Image conversion succeeded." + print "Searching database..." -rv = myFingerprintSensor.image2Tz(1) -if (rv != upmZfm20.ZFM20.ERR_OK): - print "Image conversion failed with error code %d" % rv - sys.exit(1) + myid = upmZfm20.uint16Array(0) + myid.__setitem__(0, 0) + myscore = upmZfm20.uint16Array(0) + myscore.__setitem__(0, 0) -print "Image conversion succeeded." -print "Searching database..." + # we search for a print matching slot 1, where we stored our last + # converted fingerprint + rv = myFingerprintSensor.search(1, myid, myscore) + if (rv != upmZfm20.ZFM20.ERR_OK): + if (rv == upmZfm20.ZFM20.ERR_FP_NOTFOUND): + print "Finger Print not found" + sys.exit(0) + else: + print "Search failed with error code %d" % rv + sys.exit(1) -myid = upmZfm20.uint16Array(0) -myid.__setitem__(0, 0) -myscore = upmZfm20.uint16Array(0) -myscore.__setitem__(0, 0) + print "Fingerprint found!" + print "ID: %d, Score: %d" % (myid.__getitem__(0), myscore.__getitem__(0)) -# we search for a print matching slot 1, where we stored our last -# converted fingerprint -rv = myFingerprintSensor.search(1, myid, myscore) -if (rv != upmZfm20.ZFM20.ERR_OK): - if (rv == upmZfm20.ZFM20.ERR_FP_NOTFOUND): - print "Finger Print not found" - sys.exit(0) - else: - print "Search failed with error code %d" % rv - sys.exit(1) - -print "Fingerprint found!" -print "ID: %d, Score: %d" % (myid.__getitem__(0), myscore.__getitem__(0)) +if __name__ == '__main__': + main() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0d92f798..909415b0 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -449,7 +449,7 @@ if (BUILDDOC AND BUILDSWIGPYTHON) # BUILDDOC not set but still building python modules, generate an empty # pyupm_doxy2swig.i file (overwriting if necessary) elseif (BUILDSWIGPYTHON) - message (STATUS "Generating empty ${CMAKE_CURRENT_BINARY_DIR}/pyupm_doxy2swig.i") + message (STATUS "BUILDDOC=${BUILDDOC}, python modules will not contain cxx documentation") file (WRITE ${CMAKE_CURRENT_BINARY_DIR}/pyupm_doxy2swig.i "// Empty doxy2swig stub") endif (BUILDDOC AND BUILDSWIGPYTHON) diff --git a/src/lp8860/javaupm_lp8860.i b/src/lp8860/javaupm_lp8860.i index 5479cbde..4512305c 100644 --- a/src/lp8860/javaupm_lp8860.i +++ b/src/lp8860/javaupm_lp8860.i @@ -6,3 +6,14 @@ %} %include "lp8860.hpp" + +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("javaupm_lp8860"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%} diff --git a/src/ms5611/javaupm_ms5611.i b/src/ms5611/javaupm_ms5611.i index fcfb434e..6afd595c 100644 --- a/src/ms5611/javaupm_ms5611.i +++ b/src/ms5611/javaupm_ms5611.i @@ -6,3 +6,14 @@ %} %include "ms5611.hpp" + +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("javaupm_ms5611"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%} diff --git a/src/si1132/javaupm_si1132.i b/src/si1132/javaupm_si1132.i index 3b0786a7..e35c2dae 100644 --- a/src/si1132/javaupm_si1132.i +++ b/src/si1132/javaupm_si1132.i @@ -2,16 +2,28 @@ %include "../upm.i" %include "../upm/javaupm_interfaces.i" +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("javaupm_si1132"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%} + %{ #include "si1132.hpp" %} /* -%include "../upm/iModuleStatus.hpp" -%include "../upm/iLightSensor.hpp" +%include "../upm/iModuleStatus.hpp" +%include "../upm/iLightSensor.hpp" %feature("director") IModuleStatus; %feature("director") ILightSensor; */ %include "si1132.hpp" + diff --git a/src/smartdrive/javaupm_smartdrive.i b/src/smartdrive/javaupm_smartdrive.i index e7183a9b..b316075b 100644 --- a/src/smartdrive/javaupm_smartdrive.i +++ b/src/smartdrive/javaupm_smartdrive.i @@ -6,3 +6,14 @@ %} %include "smartdrive.hpp" + +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("javaupm_smartdrive"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%} diff --git a/src/upm/javaupm_interfaces.i b/src/upm/javaupm_interfaces.i index 42b94505..962750ad 100644 --- a/src/upm/javaupm_interfaces.i +++ b/src/upm/javaupm_interfaces.i @@ -7,9 +7,20 @@ %{ #include "../upm/iLightSensor.hpp" - #include "../upm/iLightController.hpp" + #include "../upm/iLightController.hpp" %} -%include "iModuleStatus.hpp" -%include "iLightSensor.hpp" -%include "iLightController.hpp" +%include "iModuleStatus.hpp" +%include "iLightSensor.hpp" +%include "iLightController.hpp" + +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("javaupm_interfaces"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%} diff --git a/src/upm/javaupm_light_sensor.i b/src/upm/javaupm_light_sensor.i index d285ee83..2c153f44 100644 --- a/src/upm/javaupm_light_sensor.i +++ b/src/upm/javaupm_light_sensor.i @@ -5,11 +5,22 @@ %} /* -%include "../upm/iModuleStatus.hpp" +%include "../upm/iModuleStatus.hpp" */ -%include "iLightSensor.hpp" +%include "iLightSensor.hpp" %feature("director") IModuleStatus; %feature("director") ILightSensor; %include "iLightSensor.hpp" + +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("javaupm_light_sensor"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 62c39ebb..136349be 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,11 +7,42 @@ if (BUILDSWIGJAVA) ${CMAKE_CURRENT_SOURCE_DIR}/check_autoloadlibrary.py WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - add_test (NAME check_samplenames COMMAND ${PYTHON_EXECUTABLE} - ${CMAKE_CURRENT_SOURCE_DIR}/check_samplenames.py + add_test (NAME check_examplenames_java COMMAND ${PYTHON_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/check_examplenames.py java WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) add_test (NAME check_clean COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/check_clean.py WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) endif () + +if (BUILDSWIGNODE) + add_test (NAME check_examplenames_js COMMAND ${PYTHON_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/check_examplenames.py js + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) +endif (BUILDSWIGNODE) + +if (BUILDSWIGPYTHON) + add_test (NAME check_examplenames_python COMMAND ${PYTHON_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/check_examplenames.py python + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + + if (PYTHON2INTERP_FOUND) + add_test (NAME check_load_modules_python2 COMMAND ${PYTHON2_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/check_pythonload.py + ${CMAKE_BINARY_DIR}/src/*/python${PYTHON2_VERSION_MAJOR}.${PYTHON2_VERSION_MINOR}/*.py + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/) + + add_test (NAME check_load_examples_python2 COMMAND ${PYTHON2_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/check_pythonload.py + ${CMAKE_SOURCE_DIR}/examples/python/*.py + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/) + endif (PYTHON2INTERP_FOUND) + + if (PYTHON3INTERP_FOUND) + add_test (NAME check_load_modules_python3 COMMAND ${PYTHON3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/check_pythonload.py + ${CMAKE_BINARY_DIR}/src/*/python${PYTHON3_VERSION_MAJOR}.${PYTHON3_VERSION_MINOR}/*.py + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/) + endif (PYTHON3INTERP_FOUND) +endif (BUILDSWIGPYTHON) diff --git a/tests/check_autoloadlibrary.py b/tests/check_autoloadlibrary.py index 29bf490f..4cf3d8e4 100755 --- a/tests/check_autoloadlibrary.py +++ b/tests/check_autoloadlibrary.py @@ -31,7 +31,8 @@ class AutoLoadLibrary(u.TestCase): with open(os.path.join(subdir, fileName), "r") as f: if not snippet in f.read(): - broken_modules.append(moduleName) + broken_modules.append('%s: %s' % \ + (moduleName, os.path.join(subdir, fileName))) self.assertEqual( len(broken_modules), 0, "\nThe following modules do not contain the standard auto load library code:\n" + \ diff --git a/tests/check_clean.py b/tests/check_clean.py index 2031803f..d724ebd5 100755 --- a/tests/check_clean.py +++ b/tests/check_clean.py @@ -21,6 +21,8 @@ class Clean(u.TestCase): if not ok: break for fileName in files: + # Only look at JAVA wrappers + if not fileName.endswith('JAVA_wrap.cxx'): continue if swigtypeStr in fileName: unclean.append(dirName) ok = False diff --git a/tests/check_examplenames.py b/tests/check_examplenames.py new file mode 100755 index 00000000..9b716214 --- /dev/null +++ b/tests/check_examplenames.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +import unittest +import re, fnmatch, os, sys + +# Example name map +sampleMappingFile = '../doxy/samples.mapping.txt' + +# Example directories +sampledir = {} +sampledir['cxx'] = '../examples/c++/' +sampledir['java'] = '../examples/java/' +sampledir['js'] = '../examples/javascript/' +sampledir['py'] = '../examples/python/' + +# Default to all targets +test_targets = ['java', 'js', 'py'] + +class SampleNames(unittest.TestCase): + def test_existing_samples(self): + # Dictionary for missing examples + missing = {} + + # If test target/s were provided on the command line, use them + if len(self.argv) > 0: + test_targets = self.argv + + # Iterate over the mapping file and check for per-language examples + with open (sampleMappingFile, "r") as f: + for line in f: + matched = {} + fullpaths = {} + # Split out the example names per target + for target in test_targets: + match = re.match('(.*.cxx).*\t(\S+.%s)' % target, line) + if match: + matched['cxx'] = match.group(1) + matched[target] = match.group(2) + + # Need at least two target files to check + if len(matched) < 2: continue + + # Fail if NO .cxx file to compare against + self.assertTrue('cxx' in matched) + + # Update the full path to each sample file + for k,v in matched.items(): + fullpaths[k] = os.path.join(sampledir[k], v) + + # Use cxx base filename as testname + basename = os.path.splitext(matched['cxx'])[0] + + missing[basename] = [] + + # Check for all example filenames + for target, filename in fullpaths.items(): + if not os.path.exists(filename): + missing[basename] += [os.path.split(filename)[-1]] + + # Prune out tests with no missing files + for k in missing.keys(): + if len(missing[k]) == 0: del missing[k] + + # Print sorted missing example filenames + sk_missing = missing.keys() + sk_missing.sort() + self.assertEqual(len(missing), 0, + '\n\nMissing examples:\n' + + '\n'.join(['%s: %s' % (k, ', '.join(missing[k])) for k in sk_missing])) + +if __name__ == '__main__': + # Allow passing from argv + SampleNames.argv = [] + for arg in sys.argv[1:]: + SampleNames.argv.append(sys.argv.pop()) + unittest.main() diff --git a/tests/check_pythonload.py b/tests/check_pythonload.py new file mode 100755 index 00000000..5daa9118 --- /dev/null +++ b/tests/check_pythonload.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +import unittest +import imp +import glob +import os, sys + +# Skip individual modules based on module name. For example, +# pyupm_ozw will skip pyupm_ozw.py. +blacklist = [ + # OpenZwave-dependent modules + 'pyupm_ozw', 'aeotecdw2e', 'tzemt400', 'aeotecdsb09104', + 'aeotecss6', 'aeotecsdg2', 'ozwdump', + # Requires mraa python module + 'curieimu', + # Requires modbus + 'h803x', 'hwxpxx', 't3311', + # Requires bacnet + 'e50hx', 'tb7300', 't8100', + # Requires PIL + 'make_oled_pic' + ] + +class loadModule(unittest.TestCase): + ''' The loadModule class loads all module which match a search string + provided via argv. If any of the target modules fails loading, this + class will assert and provide a list of failing modules.''' + def test_load_module(self): + # Python version provided on the command line + py_search_str = '../build/src/*/python2.7/*.py' + if len(self.argv) > 0: + py_search_str = self.argv[0] + + # Make sure the search string has a full path + full_py_search_str = os.path.realpath(py_search_str) + + # Get all python modules matching full_py_search_str + pyfiles = glob.glob(full_py_search_str) + + # Fail if no modules to test + self.assertNotEqual(len(pyfiles), 0, + 'Failed to find any %s modules in %s' % \ + (py_search_str, full_py_search_str)); + + # Test load each module + failures = {} + for pyfile in pyfiles: + module = os.path.splitext(os.path.basename(pyfile))[0] + + # Don't load blacklisted modules + if module in blacklist: + print('Skipping blacklisted %s ...' % pyfile) + continue + + try: + pyfile = imp.load_source(module, pyfile) + except Exception as x: + failures[pyfile] = x + + self.assertEqual(len(failures), 0, + '\n\nFailed to load %d modules:\n' % len(failures) + + '\n'.join(['%s: %s' % (k, ', '.join(failures[k])) for k in failures.keys()])) + +if __name__ == '__main__': + # Allow passing from argv + loadModule.argv = [] + for arg in sys.argv[1:]: + loadModule.argv.append(sys.argv.pop()) + unittest.main() diff --git a/tests/check_samplenames.py b/tests/check_samplenames.py deleted file mode 100755 index c1edcc2d..00000000 --- a/tests/check_samplenames.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/python - -import unittest as u -import re, fnmatch, os, sys - -sampleMappingFile = '../doxy/samples.mapping.txt' -cSamplesDir = '../examples/c++/' -javaSamplesDir = '../examples/java/' - - -class SampleNames(u.TestCase): - - def test_existing_samples(self): - missing_c_files = [] - missing_java_files = [] - - with open (sampleMappingFile, "r") as f: - for line in f: - sampleNames = line.split(); - - cSampleName = sampleNames[0] - if not cSampleName.endswith('.cxx'): - continue - - javaSampleName = sampleNames[1] - if not javaSampleName.endswith('.java'): - continue - - ok = False - for file in os.listdir(cSamplesDir): - if file == cSampleName: - ok = True - break - - if not ok: - missing_c_files.append(cSampleName) - - ok = False - for file in os.listdir(javaSamplesDir): - if file == javaSampleName: - ok = True - break - - if not ok: - missing_java_files.append(javaSampleName) - - self.assertEqual( len(missing_java_files) + len(missing_c_files), 0, - "\nThe following files are missing from samples:\n" + \ - "\n".join(missing_c_files) + "\n" + "\n".join(missing_java_files)) - -if __name__ == '__main__': - u.main() -