Outils pour utilisateurs

Outils du site


python:gy-302

GY-302 lumière

connecté en I2C, donne en OSC sur 9001 /LUX

inspiration : https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/bh1750.py

#!/usr/bin/python
import smbus
import time
import spidev,time,liblo,sys

# Define some constants from the datasheet
DEVICE     = 0x23 # Default device I2C address
POWER_DOWN = 0x00 # No active state
POWER_ON   = 0x01 # Power on
RESET      = 0x07 # Reset data register value

# Start measurement at 4lx resolution. Time typically 16ms.
CONTINUOUS_LOW_RES_MODE = 0x13
# Start measurement at 1lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_1 = 0x10
# Start measurement at 0.5lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_1 = 0x20
# Start measurement at 0.5lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_2 = 0x21
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_LOW_RES_MODE = 0x23

bus = smbus.SMBus(0) # Rev 1 Pi uses 0
#bus = smbus.SMBus(1)  # Rev 2 Pi uses 1


PORTOSC=9001
IPOSC="localhost"

#if len(sys.argv) > 1 :
#  PORTOSC=sys.argv[1]
#if len(sys.argv) > 2 :
#  PORTOSC=sys.argv[1]
#  IPOSC=sys.argv[2]

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)

def readLight(addr=DEVICE):
  data = bus.read_i2c_block_data(addr,ONE_TIME_HIGH_RES_MODE_1)
  return convertToNumber(data)

def main():
# ouverture port OSC
  try:
    targetOSC = liblo.Address(IPOSC,PORTOSC)
  except liblo.AddressError, err:
    print str(err)
    sys.exit()

  while True:
    #print "Light Level : " + str(readLight()) + " lux"
    liblo.send(targetOSC,"/LUX", readLight())
    time.sleep(0.5)

if __name__=="__main__":
python/gy-302.txt · Dernière modification: 2017/04/11 15:13 (modification externe)