Files
2025-07-10 21:59:56 +07:00

127 lines
3.9 KiB
Python

import as7265x
import smbus
import numpy as np
import os
from datetime import datetime
import RPi.GPIO as GPIO
import time
from luma.core.interface.serial import i2c
from luma.oled.device import ssd1306
from luma.core.render import canvas
from PIL import ImageFont
from tflite_runtime.interpreter import Interpreter
# AS7265X Configuration
i2c_bus = smbus.SMBus(1)
sensor = as7265x.AS7265X(i2c_bus)
x = ['410', '435', '460', '485', '510', '535', '560', '585',
'610', '645', '680', '705', '730', '760', '810', '860',
'900', '940']
# Button GPIO Configuration
BUTTON_PIN = 22 # Button use pin 22
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Pull-down resistor
# OLED Configuration
OLED_ADDRESS = 0x3C # I2C address of the OLED
serial = i2c(port=1, address=OLED_ADDRESS)
oled = ssd1306(serial)
# Load font (optional, system fonts or custom fonts can be used)
font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font = ImageFont.truetype(font_path, 12) if os.path.exists(font_path) else None
# Load the TFLite model
interpreter = Interpreter(model_path="coffee_random.tflite")
interpreter.allocate_tensors()
# Get input and output details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Define classes
classes = ['Bitter','Ideal','Strong','Underdevelop','Weak']
def predict(data):
# Convert data type
input_data = np.array([data]).astype(input_details[0]['dtype'])
# Set input tensor
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
final = np.argmax(output_data)
return classes[final]
def scan() -> None:
"""Scan function using AS7265X and Predict"""
display_message("Scanning...")
# Turn on all LED
sensor.begin()
sensor.enableBulb(as7265x.LED_WHITE)
sensor.enableBulb(as7265x.LED_IR)
sensor.enableBulb(as7265x.LED_UV)
sensor.setIntegrationCycles(1)
# Take measurements
sensor.takeMeasurements()
data = [
sensor.getCalibratedA(), sensor.getCalibratedB(), sensor.getCalibratedC(), sensor.getCalibratedD(),
sensor.getCalibratedE(), sensor.getCalibratedF(), sensor.getCalibratedG(), sensor.getCalibratedH(),
sensor.getCalibratedR(), sensor.getCalibratedI(), sensor.getCalibratedS(), sensor.getCalibratedJ(),
sensor.getCalibratedT(), sensor.getCalibratedU(), sensor.getCalibratedV(), sensor.getCalibratedW(),
sensor.getCalibratedK(), sensor.getCalibratedL()
]
sensor.disableBulb(as7265x.LED_WHITE)
sensor.disableBulb(as7265x.LED_IR)
sensor.disableBulb(as7265x.LED_UV)
prediction = predict(data)
# Save data as txt file
predict_message(prediction)
scan_message()
def predict_message(message: str) -> None:
with canvas(oled) as draw:
draw.text((5,5), "Prediction:", fill='white', font=font)
draw.text((5,25), message, fill='white', font=font)
time.sleep(3.25)
def display_message(message: str) -> None:
"""Display a message on the OLED."""
with canvas(oled) as draw:
draw.text((10, 25), message, fill="white", font=font)
time.sleep(2) # Display message for 2 seconds
def scan_message():
with canvas(oled) as draw:
draw.text((5,5), "Push button", fill='white', font=font)
draw.text((5,25), "to scan!", fill='white', font=font)
time.sleep(2)
print("Setup completed!")
display_message("Setup Completed!")
scan_message()
print("=" * 20)
print("Push a button to scan!")
try:
while True:
if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
print("Tombol ditekan!")
print("Memulai scan....")
scan()
print("Scan succeed!")
scan_message()
time.sleep(0.1) # Delay untuk menghindari pembacaan terlalu cepat
except KeyboardInterrupt:
print("Program dihentikan.")
finally:
GPIO.cleanup()