電路圖
程式列表
Python - GP2Y0E03.py
"""
GP2Y0E03.py
Reference: https://github.com/xionic/GP2Y0E03-Python-Driver
-----------------
1:VDD: Power supply
2:Vout(A): Analog output voltage
3:GND: Ground
4:VIN(IO): I/O supplying voltage
5:GPIO1: Active / stand-by condition switching terminal
6:SCL: I2C clock
7:SDA: I2C data bus
"""
from micropython import const
from machine import I2C, Pin
# 7 highest bits
# ADDRESS = const(0x40)
SHIFT_ADDR = const(0x35)
DISTANCE_ADDR = const(0x5E)
# Distance Value=(Distance[11:4]*16+Distance[3:0])/16/2^n
# n : Shift Bit
StateControl = const(0xE8) # 0x00=Active state/0x01=Stand by state
SoftwareReset = const(0xEE) # 0x06=software reset
# Spot Size= C A
# Spot Symmetry=|(C A) 2*B|
RIGHT_EDGE_ADDR = const(0xF8) # Right Edge Coordinate (C)
LEFT_EDGE_ADDR = const(0xF9) # Left Edge Coordinate (A)
PEAK_EDGE_ADDR = const(0xFA) # Peak Coordinate (B)
class GP2Y0E03:
def __init__(self, i2c, address=0x40):
self.i2c = i2c
self.address = address
def _register8(self, register, value=None):
buf = bytearray(1)
self.i2c.send(register,self.address) # Write 1 byte
self.i2c.recv(buf,self.address) # read one byte
return buf
def _register16(self, register, value=None):
buf = bytearray(2)
self.i2c.send(register,self.address) # Write 1 byte
self.i2c.recv(buf,self.address) # read 2 byte
return buf
def read(self, raw=False):
shift = self._register8(SHIFT_ADDR)
value = self._register16(DISTANCE_ADDR)
print("value:%02X,%02X,shift:%02X"%(value[0],value[1],shift[0]))
# Distance in cm - see http://media.digikey.com/pdf/Data%20Sheets/Sharp%20PDFs/GP2Y0E03_Spec_Feb2013.pdf
dist = (((value[0]<< 4) | value[1])/16)/(2**shift[0])
return dist
Python - epy-Lite_GP2Y0E03.py
"""
epy-Lite_GP2Y0E03.py
Reference: https://github.com/xionic/GP2Y0E03-Python-Driver
ePy-Lite Sensor
-----------------
3V3 1:VDD: Power supply
2:Vout(A): Analog output voltage
GND 3:GND: Ground
3V3 4:VIN(IO): I/O supplying voltage
3V3 5:GPIO1: Active / stand-by condition switching terminal
P17_SCL0 6:SCL: I2C clock
P18_SDA0 7:SDA: I2C data bus
"""
from micropython import const
from machine import I2C, Pin
from machine import Switch #Get button KEY library
import utime
import GP2Y0E03
# Start Function
if __name__=="__main__":
KeyA = Switch('keya') #Create button A
i2c = I2C(0,I2C.MASTER,baudrate=100000) #Create I2C0 Master Mode, Baudrate=100kHz
sensor = GP2Y0E03.GP2Y0E03(i2c)
utime.sleep_ms(1000)
while True:
distance_cm = sensor.read()
if((distance_cm>=4)and(distance_cm<=50)) :
print("Distance %f cm"%(distance_cm))
else :
print("Distance out range")
if KeyA.value() == True: #Press A Key
break
utime.sleep_ms(500)
執行結果