วัดและบันทึก ค่าความเข้มแสงด้วย Raspberry Pi + BH1750
คุณสมบัติ อีกอย่างนึงของ Raspberry Pi คือ สามารถติดต่อกับอุปกรณ์ผ่าน Bus i2c ได้ โดยวันนี้ผมจะลองนำ Raspberry Pi2 Model B ติดต่อกับเซ็นเซอร์วัดความเข้มแสง BH1750 เพื่อวัดความเข้มแสงที่ได้ พร้อมกับบันทึกข้อมูลที่ได้เป็นไฟล์ text
อุปกรณ์ที่ต้องใช้ ได้แก่ Raspberry Pi และ BH1750 ต่อวงจรดังรูป
เนื่องจาก BH1750 ใช้การติดต่อผ่าน Bus i2c เมื่อนำมาเชื่อมต่อกับ Raspberry Pi ต้องใช้ภาษา Python ในการเขียนโปรแกรม และต้องมีการติดตั้ง Libraryดังนี้
$ sudo apt-get install python3-smbus $ sudo apt-get install i2c-tools $ sudo reboot
เมื่อ Reboot เครื่องแล้ว ให้ Enable Bus i2c ของ Raspberry Pi ด้วยคำสั่ง
$ sudo raspi-config
จะปรากฎหน้าต่าง Raspberry Pi Software Configuration Tools ขึ้นมา จากนั้น เลือก Advance Option >> I2C >> Yes >> OK ดังรูป
เมื่อต่อวงจร และเปิดใช้งาน Bus I2C แล้ว ตรวจสอบการเชื่อมต่อ Bus i2C ด้วยคำสั่ง
$ sudo i2cdetect -y 1
หน้าจอจะแสดง การเชื่อมต่อของ Bus i2C ดังรูป (จากรูปอยู่ตำแหน่งที่ 23)
จากนั้น เขียน Script Python เพื่อวัดค่าความเข้มแสง ดังตัวอย่าง
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- encoding: utf-8 -*- | |
import time | |
import smbus | |
import datetime | |
bus = smbus.SMBus(1) #(512MB) | |
addr = 0x23 # i2c adress | |
while True: | |
data = bus.read_i2c_block_data(addr,0x11) | |
lum=(data[1] + (data[0]<<8) / 1.2) | |
date=str(datetime.datetime.now()) | |
print ("Lum = ",lum) | |
time.sleep(0.5) |
Run Program เพื่อทดสอบ
เมื่อวัดความเข้มแสงได้แล้ว ต่อไปจะเป็นการเขียนโปรแกรม เพื่อเก็บบันค่าความเข้มแสงที่วัดได้ ลงไฟล์ text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- encoding: utf-8 -*- | |
import time | |
import smbus | |
import datetime | |
bus = smbus.SMBus(1) #(512MB) | |
addr = 0x23 # i2c adress | |
while True: | |
data = bus.read_i2c_block_data(addr,0x11) | |
lum=(data[1] + (data[0]<<8) / 1.2) | |
date=str(datetime.datetime.now()) | |
time.sleep(0.5) | |
with open("BH1750.txt", "a") as text_file: | |
text_file.write("DetaTime: %s Luminosity: %.2f lx\n" % (date,lum,)) | |
time.sleep(0.5) |
ทดสอบโดยการ Run Program ทิ้งไว้ แล้วเปิดไฟล์ BH1750.txt เพื่อดูว่าข้อมูลถูกบันทึกหรือไม่ ถ้าโปรแกรมทำงานถูกต้อง ไฟล์จะทำการบันทึกข้อมูล ดังรูป
*********************************************************************************
Montien Ngamkaew
*********************************************************************************