from machine import Pin,PWM,I2C
from ssd1306 import SSD1306_I2C
import framebuf, sys
from time import sleep
import utime
#Initialize oled display
pix_res_x = 128
pix_res_y = 64
def init_i2c(scl_pin, sda_pin):
# Initialize I2C device
i2c_dev = I2C(1, scl=Pin(scl_pin), sda=Pin(sda_pin), freq=200000)
i2c_addr = [hex(ii) for ii in i2c_dev.scan()]
if not i2c_addr:
print('No I2C Display Found')
sys.exit()
else:
print("I2C Address : {}".format(i2c_addr[0]))
print("I2C Configuration: {}".format(i2c_dev))
return i2c_dev
i2c_dev = init_i2c(scl_pin=27, sda_pin=26)
display = SSD1306_I2C(pix_res_x, pix_res_y, i2c_dev)
#Initializing the Ultrasonic and led2(Red led)
Trig=Pin(3,Pin.OUT)
Echo=Pin(2,Pin.IN)
LED2=PWM(Pin(28))
LED2.freq(1000)
LED2.duty_u16(0)
#Initializing the PIR sensor and led1(Green led)
PIR=Pin(16,Pin.IN,Pin.PULL_DOWN)
LED1=Pin(0,Pin.OUT)
#Function for detecting motion
def motion():
display.fill(0)
LED1.value(PIR.value())
if PIR.value()==1:
display.text("Motion Detected",1,1)
else:
display.text("No Motion!",1,1)
display.show()
utime.sleep(0.5)
#Function for measuring distance
def read_distance():
Trig.value(0)
utime.sleep_us(2)
Trig.value(1)
utime.sleep_us(5)
Trig.value(0)
while Echo.value()==0:
Time_taken_go=utime.ticks_us()
while Echo.value()==1:
Time_taken_received=utime.ticks_us()
timeTaken=Time_taken_received-Time_taken_go
distance=((0.0343*timeTaken)/2)
brightness=(65550/150)*distance
LED2.duty_u16(int(brightness))
message="distance:"+str(distance)
display.fill(0)
display.text(message,1,1)
display.show()
while True:
read_distance()
motion()
sleep(0.2)