基於亞博k210+arduino 智慧垃圾桶(23工訓賽)

小鑫2002發表於2023-11-03
#2023 10 15 派大星改
# object classifier boot.py
# generated by maixhub.com
from fpioa_manager import *
from modules import ultrasonic
from fpioa_manager import fm
from Maix import GPIO
import math
import struct
import sensor, image, lcd, time
import KPU as kpu
import gc, sys
from Maix import GPIO
from machine import UART
from machine import Timer,PWM
#
#
i= 8
# 定義超聲波感測器的觸發引腳和迴響引腳
trig_pin = 0
echo_pin = 1

#控制串列埠通訊
board_info_tx=15
board_info_rx=17
# 將GPIO口初始化為輸入/輸出模式
fm.register(trig_pin, fm.fpioa.GPIO0)
fm.register(echo_pin, fm.fpioa.GPIO1)
trig = GPIO(GPIO.GPIO0, GPIO.OUT)
echo = GPIO(GPIO.GPIO1, GPIO.IN)
tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)               #控制2個雲臺舵機
S1 = PWM(tim, freq=50, duty=0, pin=21)
tim = Timer(Timer.TIMER1, Timer.CHANNEL0, mode=Timer.MODE_PWM)
S2 = PWM(tim, freq=50, duty=0, pin=23)

value = 0xFF
s = struct.pack('B', value)
list_of_values = [255]*3
s = struct.pack('3B', *list_of_values)                                       #串列埠通訊結束符

fm.register(board_info_tx,fm.fpioa.UART1_TX,force=True)
fm.register(board_info_rx,fm.fpioa.UART1_RX,force=True)
uart_A = UART(UART.UART1, 115200, 8, None, 1, timeout=1000, read_buf_len=4096)
#uart_A = UART(UART.UART1, 115200,read_buf_len=4096)


def Servo_1(servo,angle):
    S1.duty((angle+90)/180*10+2.5)              #豎直舵機
def Servo_2(servo,angle):
    S2.duty((angle+90)/270*10+2.5)              #水平舵機
#超聲波
def measure_distance():
    trig.value(0) # 傳送觸發訊號
    time.sleep_ms(2)
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)
    start_time = time.ticks_ms()
    while echo.value() == 0 and time.ticks_diff(time.ticks_ms(), start_time) < 3000:
        pass

    # 如果等待超時,返回錯誤程式碼 -1
    if time.ticks_diff(time.ticks_ms(), start_time) >= 3000:
        print("Error: no echo received!")
        return -1

    # 記錄迴響訊號的時間戳
    t1 = time.ticks_us()
    while echo.value() == 1:
        pass
    t2 = time.ticks_us()

    print(t2)
    # 計算距離(單位:釐米)
    duration = t2 - t1
    distance = duration * 0.017
    print(distance)
    if distance < 15:                                 #距離判斷
       write_str = ("t20.bco=63488")
       uart_A.write(write_str)
       print("滿載")
       uart_A.write(s)
    else:
       write_str = ("t20.bco=34784")
       uart_A.write(write_str)
       print("未滿載")
       uart_A.write(s)
    return






def lcd_show_except(e):
    import uio
    err_str = uio.StringIO()
    sys.print_exception(e, err_str)
    err_str = err_str.getvalue()
    img = image.Image(size=(224,224))
    img.draw_string(0, 10, err_str, scale=1, color=(0xff,0x00,0x00))
    lcd.display(img)
 #開機啟動
 ########################################################################################################################
def main(labels = None, model_addr="/sd/m.kmodel", sensor_window=(224, 224), lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False):
    sensor.reset()
    sensor.set_pixformat(sensor.RGB565)
    sensor.set_framesize(sensor.QVGA)
    sensor.set_windowing(sensor_window)
    sensor.set_hmirror(sensor_hmirror)
    sensor.set_vflip(sensor_vflip)
    sensor.run(1)

    lcd.init(type=1,invert=1)        #小LCD螢幕
    lcd.rotation(lcd_rotation)
    lcd.clear(lcd.WHITE)
    if not labels:
        with open('labels.txt','r') as f:
            exec(f.read())
    if not labels:
        print("no labels.txt")
        img = image.Image(size=(320, 240))
        img.draw_string(90, 110, "no labels.txt", color=(255, 0, 0), scale=2)
        lcd.display(img)
        return 1
    try:
        img = image.Image("startup.jpg")
        lcd.display(img)
    except Exception:
        img = image.Image(size=(320, 240))
        img.draw_string(90, 110, "loading model...", color=(255, 255, 255), scale=2)
        lcd.display(img)
    task = kpu.load(model_addr)
    try:
####################################迴圈######################################################################################
        a= 0
        while(a<3):
            print("啟動")
            write_str = ("page main")           #跳到計數主螢幕
            uart_A.write(write_str)
            uart_A.write(s)
            print(write_str)
            a+=1


        while(True):
            Servo_1(S1, i)
            Servo_2(S2, 0)
            time.sleep_ms(500)
            measure_distance()                 #滿載檢查
            print("滿載jianche ")
            write_str = ("n5.val=0")           #初始化串列埠螢幕
            uart_A.write(write_str)
            uart_A.write(s)
            print(write_str)
            while(True):

                img = sensor.snapshot()
                t = time.ticks_ms()
                fmap = kpu.forward(task, img)
                t = time.ticks_ms() - t
                plist=fmap[:]
                pmax=max(plist)                      #判斷最大置信度
                if pmax < 0.4:                       #檢測空物品
                    empty_str = "Not subject"
                    img.draw_string(0, 0, empty_str, scale=2)
                    lcd.display(img)
                    Servo_1(S1, i)
                    Servo_2(S2, 0)
                    break
                max_index=plist.index(pmax)
                img.draw_string(0,0, "%.2f : %s" %(pmax, labels[max_index].strip()), scale=2)
                img.draw_string(0, 200, "t:%dms" %(t), scale=2)
                lcd.display(img)


                if plist.index(pmax)==0 or plist.index(pmax)==6:  #fruit "vegetable"    廚餘垃圾
                    if pmax >= 0.5:

                            time.sleep_ms(50)      #等待垃圾掉落待靜止的時間
                            Servo_2(S2,90)
                            time.sleep_ms(1000)
                            Servo_1(S1,-20)
                            time.sleep_ms(1500)
                            #write_str = ()
                            Servo_1(S1,i)
                            time.sleep_ms(400)
                            Servo_2(S2,0)
                            time.sleep_ms(1000)
                            uart_A.write("t7.txt=\"廚餘垃圾\"")
                            print("廚餘垃圾ok")
                            uart_A.write(s)

                            time.sleep_ms(450)   #舵機歸位
                            Servo_1(S1,i)
                            time.sleep_ms(450)
                            break
                            #time.sleep_ms(500)      #等待垃圾掉落待靜止的時間

                if plist.index(pmax)== 1 or plist.index(pmax)==2 or plist.index(pmax)== 7:  #capsule      有害垃圾
                    if pmax >= 0.6:    #0.5

                            time.sleep_ms(50)      #時隔幾秒後繼續檢測垃圾
                            #Servo_2(S2,90)
                            #time.sleep_ms(500)
                            Servo_1(S1,-30)
                            time.sleep_ms(1500)
                            #write_str = ()
                            uart_A.write("t7.txt=\"有害垃圾\"")
                            print("有害垃圾ok")
                            uart_A.write(s)

                            time.sleep_ms(450)   #舵機歸位
                            Servo_1(S1,i)
                            Servo_2(S2,0)
                            time.sleep_ms(450)
                            break



                if plist.index(pmax)==4 or plist.index(pmax)==8:  #bottle        可回收垃圾
                    if pmax >= 0.5:

                            time.sleep_ms(50)      #等待垃圾掉落待靜止的時間
                            Servo_2(S2,180)
                            time.sleep_ms(1000)
                            Servo_1(S1,-20)
                            time.sleep_ms(1500)
                            #write_str = ()
                            Servo_1(S1,i)
                            time.sleep_ms(400)
                            Servo_2(S2,0)
                            time.sleep_ms(1000)
                            uart_A.write("t7.txt=\"可回收垃圾\"")
                            print("可回收垃圾ok")
                            uart_A.write(s)
                            time.sleep_ms(1200)   #舵機歸位
                            break



                if plist.index(pmax)==3 or plist.index(pmax)== 5 or plist.index(pmax)== 9:  #cigarette      其他垃圾
                    if pmax >= 0.7:  #0.5

                            time.sleep_ms(50)      #等待垃圾掉落待靜止的時間
                            Servo_2(S2,-90)
                            time.sleep_ms(1000)
                            Servo_1(S1,-20)
                            time.sleep_ms(1500)
                            #write_str = ()
                            Servo_1(S1,i)
                            time.sleep_ms(400)
                            Servo_2(S2,0)
                            time.sleep_ms(1000)

                            uart_A.write("t7.txt=\"其他垃圾\"")
                            print("其他垃圾ok")
                            uart_A.write(s)
                            time.sleep_ms(450)   #舵機歸位
                            Servo_1(S1,i)
                            Servo_2(S2,0)
                            time.sleep_ms(500)
                            break
        uart.deinit()                   # uart.deinit()和kpu.deinit(task)用於關閉UART和釋放模型資源。
        del uart
    except Exception as e:
        raise e
    finally:
        if not task is None:
            kpu.deinit(task)

if __name__ == "__main__":
  try :
      #labels = ["bottle", "brick", "capsule", "pill", "stone", "vegetable"]
      #labels = ["chuyu", "dainci", "jiaolang", "shitou", "shuiping", "taoci", "yaobaozhung", "yilaguan"]
      labels = ["chuyu", "dainci", "jiaolang", "shitou", "shuiping", "taoci", "xiaotudou", "yaobaozhung", "yilaguan", "zhuangtou"]
      main(labels=labels, model_addr="/sd/m.kmodel")
  except Exception as e:
      sys.print_exception(e)
      lcd_show_except(e)
  finally:
      gc.collect()

材料:陶晶馳串列埠屏,k210,雲臺,電動推杆,arduino uon ,超聲波,

超聲波程式碼:

 

import time
from fpioa_manager import fm
from Maix import GPIO

# 定義超聲波感測器的觸發引腳和迴響引腳
trig_pin = 0
echo_pin = 1

# 將GPIO口初始化為輸入/輸出模式
fm.register(trig_pin, fm.fpioa.GPIO0)
fm.register(echo_pin, fm.fpioa.GPIO1)
trig = GPIO(GPIO.GPIO0, GPIO.OUT)
echo = GPIO(GPIO.GPIO1, GPIO.IN)


def measure_distance():
    # 傳送觸發訊號
    trig.value(0)
    time.sleep_ms(2)
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)

    # 等待迴響訊號
    while echo.value() == 0:
        pass
    t1 = time.ticks_us()

    while echo.value() == 1:
        pass
    t2 = time.ticks_us()

    # 計算距離(單位:釐米)
    duration = t2 - t1
    distance = duration * 0.034 / 2
    return distance


while True:
    distance = measure_distance()
    print("Distance: %.2f cm" % distance)
    time.sleep(1)

拍照程式碼:

import sensor, lcd
from Maix import GPIO
from fpioa_manager import fm
from board import board_info
import os, sys
import time
import image

#### image size ####
set_windowing = (224, 224)

#### sensor config ####

sensor.reset(freq=22000000, dual_buff=False)
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) # 320x240
try:
    sensor.set_jb_quality(95)         # for IDE display quality
except Exception:
    pass # no IDE support
if set_windowing:
    sensor.set_windowing(set_windowing)



sensor.skip_frames()

#### lcd config ####
lcd.init(type=1, freq=15000000)
lcd.rotation(2)

#### boot key ####
boot_pin = 16 # board_info.BOOT_KEY
fm.register(boot_pin, fm.fpioa.GPIOHS0)
key = GPIO(GPIO.GPIOHS0, GPIO.PULL_UP)

######################################################

#### main ####
def capture_main(key):
    def draw_string(img, x, y, text, color, scale, bg=None , full_w = False):
        if bg:
            if full_w:
                full_w = img.width()
            else:
                full_w = len(text)*8*scale+4
            img.draw_rectangle(x-2,y-2, full_w, 16*scale, fill=True, color=bg)
        img = img.draw_string(x, y, text, color=color,scale=scale)
        return img

    def del_all_images():
        os.chdir("/sd")
        images_dir = "cap_images"
        if images_dir in os.listdir():
            os.chdir(images_dir)
            types = os.listdir()
            for t in types:
                os.chdir(t)
                files = os.listdir()
                for f in files:
                    os.remove(f)
                os.chdir("..")
                os.rmdir(t)
            os.chdir("..")
            os.rmdir(images_dir)

    # del_all_images()
    os.chdir("/sd")
    dirs = os.listdir()
    images_dir = "cap_images"
    last_dir = 0
    for d in dirs:
        if d.startswith(images_dir):
            if len(d) > 11:
                n = int(d[11:])
                if n > last_dir:
                    last_dir = n
    images_dir = "{}_{}".format(images_dir, last_dir+1)
    print("save to ", images_dir)
    if images_dir in os.listdir():
        img = image.Image()
        img = draw_string(img, 2, 200, "please del cap_images dir", color=lcd.WHITE,scale=1, bg=lcd.RED)
        lcd.display(img)
        sys.exit(1)
    os.mkdir(images_dir)
    last_cap_time = 0
    last_btn_status = 1
    save_dir = 0
    save_count = 0
    os.mkdir("{}/{}".format(images_dir, save_dir))
    while(True):
        img0 = sensor.snapshot()
        if set_windowing:
            img = image.Image()
            img = img.draw_image(img0, (img.width() - set_windowing[0])//2, img.height() - set_windowing[1])
        else:
            img = img0.copy()
        # img = img.resize(320, 240)
        if key.value() == 0:
            time.sleep_ms(30)
            if key.value() == 0 and (last_btn_status == 1) and (time.ticks_ms() - last_cap_time > 500):
                last_btn_status = 0
                last_cap_time = time.ticks_ms()
            else:
                if time.ticks_ms() - last_cap_time > 5000:
                    img = draw_string(img, 2, 200, "release to change type", color=lcd.WHITE,scale=1, bg=lcd.RED)
                else:
                    img = draw_string(img, 2, 200, "release to capture", color=lcd.WHITE,scale=1, bg=lcd.RED)
                    if time.ticks_ms() - last_cap_time > 2000:
                        img = draw_string(img, 2, 160, "keep push to change type", color=lcd.WHITE,scale=1, bg=lcd.RED)
        else:
            time.sleep_ms(30)
            if key.value() == 1 and (last_btn_status == 0):
                if time.ticks_ms() - last_cap_time > 5000:
                    img = draw_string(img, 2, 200, "change object type", color=lcd.WHITE,scale=1, bg=lcd.RED)
                    lcd.display(img)
                    time.sleep_ms(1000)
                    save_dir += 1
                    save_count = 0
                    dir_name = "{}/{}".format(images_dir, save_dir)
                    os.mkdir(dir_name)
                else:
                    draw_string(img, 2, 200, "capture image {}".format(save_count), color=lcd.WHITE,scale=1, bg=lcd.RED)
                    lcd.display(img)
                    f_name = "{}/{}/{}.jpg".format(images_dir, save_dir, save_count)
                    img0.save(f_name, quality=95)
                    save_count += 1
                last_btn_status = 1
        img = draw_string(img, 2, 0, "will save to {}/{}/{}.jpg".format(images_dir, save_dir, save_count), color=lcd.WHITE,scale=1, bg=lcd.RED, full_w=True)
        lcd.display(img)
        del img
        del img0


def main():
    try:
        capture_main(key)
    except Exception as e:
        print("error:", e)
        import uio
        s = uio.StringIO()
        sys.print_exception(e, s)
        s = s.getvalue()
        img = image.Image()
        img.draw_string(0, 0, s)
        lcd.display(img)
main()

紅外:

# Untitled - By: 淒雨冷夜孤人 - 週三 12月 2 2020

import sensor, image, lcd, time
import KPU as kpu
import gc, sys

import time,machine
from machine import Timer
from board import board_info
from fpioa_manager import *
from fpioa_manager import fm
from Maix import GPIO
from machine import UART
import utime
#↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓UART
fm.register(0, fm.fpioa.UART1_TX, force=True)
fm.register(1, fm.fpioa.UART1_RX, force=True)
uart_A = UART(UART.UART1, 1200, 8, 0, 0, timeout=1000, read_buf_len=4096)
fm.register(2,fm.fpioa.GPIO4)
fm.register(3,fm.fpioa.GPIO5)
tiggerPin=GPIO(GPIO.GPIO5, GPIO.OUT)
tiggerPin.value(1)
slaveReset=GPIO(GPIO.GPIO4, GPIO.OUT)
slaveReset.value(1)
time.sleep(1)
slaveReset.value(0)
time.sleep_ms(1)
slaveReset.value(1)
time.sleep(1)
def UARTsendMessgae(write_str):
    global tiggerPin
    uart_A.write(write_str)#串列埠A傳送
    #print(write_str)
    tiggerPin.value(0)
    utime.sleep_ms(1)
    tiggerPin.value(1)
#↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑UART
harmfulGarbage=("有害垃圾","battery",)#這些 陣列 的 [0] 位置用於讀出這些物品的類別 。[0]後的位置用於和識別結果比較以確定類別
kitchenGarbage=("廚餘垃圾","fruit","vegatable")
reuseableGarbage=("可回收垃圾","bottle", "can")
otherGarbage=("其它垃圾","cigaret","brick")
freq1=100   #頻率值

def angle_to_duty(angle,freq):#舵機角度換算為pwm佔空比
    ms=(angle*(2.47-0.45)/180)+0.45#2.47和0.45和0.45是實驗觀察調整得到的值,剛好使得輸入0~90~180時,舵機臂在最正確的角度
    duty=100*(ms/(1000/freq))
    return duty
#記錄系統時間以及時間差
t_1 = time.ticks_ms()
t_2 = time.ticks_ms()
ts=t_1-t_2

def detect(): #檢測畫面中的物品 並顯示畫面和資訊
    #全域性變數
    global t_1
    global t_2
    global ts
    t_2=t_1
    t_1 = time.ticks_ms()
    ts=t_1-t_2
    message[6]=str(ts)#這四行測得目前每張圖的間隔134ms左右
    img = sensor.snapshot()  #捕獲影像
    #t = time.ticks_ms()
    fmap = kpu.forward(task, img)    #對捕獲的影像進行物體檢測
    #t = time.ticks_ms() - t
    plist=list(fmap[:])#將fmap轉換為列表形式
    plist[1]=0 #第一元素置為0(無物品)
    pmax=max(plist)#找到最大的置信機率
    max_index=plist.index(pmax) #找到最大置信機率對應的物體類別的索引

    if(pmax>0.5):  #視為有效
        pass
    else:#視為無效(未檢測到)
        max_index=1
    imgDrawMessage(img)  #可附加資訊
    #img.draw_string(0,0, "%.2f : %s" %(pmax, labels[max_index].strip()), scale=2, color=(255, 0, 0))
    lcd.display(img)
    #print(labels[max_index])
    return labels[max_index]  #返回物體類別

def detectEnsureing(originResult):#多次識別,結果和第一次識別都一樣就確信識別結果正確,否則認為識別有錯
    garbageKind=originResult  #初始化,設定為傳入函式(第一次識別結果)
    for ensureingTimes in range(5):   #迴圈5次,多次識別
        nowResult=detect()
        if nowResult != originResult:    #與最初結果相比較
            garbageKind="no object"
            #print("not ensure!")
            break
    #print("ensure!")
    return garbageKind    #返回最初結果或“no,,,,”

message=[" "," "," "," "," "," "," "]
def imgDrawMessage(img):#把 需要與畫面一起顯示的資訊 畫在圖片上
    vPossion=0
    for displayMessage in message:
        img.draw_string(0,vPossion, b"%s" %(displayMessage.strip()), scale=2, color=(255, 0, 0),mono_space=1)
        vPossion+=30

actionCount=0;
dict = {"fruit":"水果", "battery":"電池", "bottle": "瓶子","can":"易拉罐","vegatable":"菜葉等","cigaret":"菸頭","brick":"磚瓦等"}
#["fruit", "no object", "battery", "bottle", "can", "vegatable", "cigaret", "brick"]
def action(garbageKind):#根據垃圾型別做出響應,舵機擺動
    global actionCount  #記錄運算元
    if garbageKind=="no object":
        return    #直接返回
    #lcd.draw_string(100, 100,garbageKind, lcd.RED)
    #time.sleep(1)
    #for kindEnsure in range(5)
    message[0]="處理中"  #訊息陣列0更新為 處理中
    #if garbageKind in harmfulGarbage:
    for delayTimes in range(10):
        detect()

    if (garbageKind in harmfulGarbage)and GarbageBin0.value():
        actionCount+=1   #記錄運算元
        message[1]=harmfulGarbage[0]  #將訊息陣列進行再次更新為對應的標籤
        detect()   #檢測標籤
        UARTsendMessgae(str(actionCount)+dict[garbageKind]+" "+"1"+"完成")
        #調整角度
        for i in range(92,20-1,-4):
            pwm1.duty(angle_to_duty(i,freq1))
            #print(i)
            utime.sleep_ms(20)
        while(detect() in harmfulGarbage):
            servoShake(pwm1,(40,20))
        pwm1.duty(angle_to_duty(20,freq1))

    #elif garbageKind in kitchenGarbage:#帶有桶滿邏輯的條件是(garbageKind in kitchenGarbage)and GarbageBin0.value():
    elif (garbageKind in kitchenGarbage)and GarbageBin1.value():
        actionCount+=1
        UARTsendMessgae(str(actionCount)+dict[garbageKind]+" "+"1"+"完成")
        message[1]=kitchenGarbage[0]  #將訊息陣列進行再次更新為對應的標籤
        detect()    #檢測
        # 調整角度
        for i in range(92,160+1,4):
            pwm1.duty(angle_to_duty(i,freq1))
            #print(i)
            utime.sleep_ms(20)
        while(detect()in kitchenGarbage):
            servoShake(pwm1,(140,160))
        pwm1.duty(angle_to_duty(160,freq1))

    #elif garbageKind in reuseableGarbage:
    elif (garbageKind in reuseableGarbage)and GarbageBin2.value():
        actionCount+=1
        UARTsendMessgae(str(actionCount)+dict[garbageKind]+" "+"1"+"完成")
        message[1]=reuseableGarbage[0]
        detect()
        for i in range(92,160+1,4):
            pwm2.duty(angle_to_duty(i,freq1))
            #print(i)
            utime.sleep_ms(20)
        while(detect()in reuseableGarbage):
            servoShake(pwm2,(160,140))
        pwm2.duty(angle_to_duty(140,freq1))
    #elif garbageKind in otherGarbage:
    elif (garbageKind in otherGarbage)and GarbageBin3.value():
        actionCount+=1
        UARTsendMessgae(str(actionCount)+dict[garbageKind]+" "+"1"+"完成")
        message[1]=otherGarbage[0]
        detect()
        for i in range(92,20-1,-4):
            pwm2.duty(angle_to_duty(i,freq1))
            #print(i)
            utime.sleep_ms(20)
        #time.sleep(1)
        while(detect()in otherGarbage):
            servoShake(pwm2,(40,20))
        pwm2.duty(angle_to_duty(20,freq1))
    for delayTimes in range(5):
        detect()
    message[0]="處理完成"
    message[1]="無物品"
    #恢復初始位置
    pwm1.duty(angle_to_duty(89,freq1))
    pwm2.duty(angle_to_duty(92,freq1))

#servoShakingCount=0
servoShakingState=False
def servoShake(servoName,twoAngle):
#讓舵機在兩個角度twoangel[0]或[1]之間來回擺,產生抖動效果。每進入一次這個函式,twoAngle[1]或[0]變為twoAngle[0]或[1]
    #global servoShakingCount
    global servoShakingState#全域性變數 保留上次在這個函式里產生的值
    servoName.duty(angle_to_duty(twoAngle[servoShakingState],freq1))
    servoShakingState=not servoShakingState
    #servoShakingState取反,下次進入函式時就是相反的值,產生重複進入這個函式時servoShakingState一次為0,一次為1,來回變化的效果

def checkGarbageFull():#檢測四個紅外對射管的輸入,判斷垃圾桶是否裝滿
    if GarbageBin0.value()==0:
        message[2]="有害垃圾已滿"   #將訊息陣列2的元素設定為“xxx已滿”
                                 # 從2開始,因為0,1已經在main中使用
    else:
        message[2]=" "

    if GarbageBin1.value()==0:
        message[3]="廚餘垃圾已滿"
    else:
        message[3]=" "

    if GarbageBin2.value()==0:
        message[4]="可回收垃圾已滿"
    else:
        message[4]=" "

    if GarbageBin3.value()==0:
        message[5]="其它垃圾已滿"
    else:
        message[5]=" "
    pass#另外三個垃圾桶的紅外對射管,等機械結構確定後再接線

image.font_load(image.UTF8, 16, 16, 0x500000)
fm.register(17, fm.fpioa.GPIO0)
fm.register(16, fm.fpioa.GPIO1)
fm.register(15, fm.fpioa.GPIO2)
fm.register(14, fm.fpioa.GPIO3)
GarbageBin0=GPIO(GPIO.GPIO0, GPIO.IN,GPIO.PULL_UP)
GarbageBin1=GPIO(GPIO.GPIO1, GPIO.IN,GPIO.PULL_UP)
GarbageBin2=GPIO(GPIO.GPIO2, GPIO.IN,GPIO.PULL_UP)
GarbageBin3=GPIO(GPIO.GPIO3, GPIO.IN,GPIO.PULL_UP)
tim1= Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
tim2= Timer(Timer.TIMER0, Timer.CHANNEL1, mode=Timer.MODE_PWM)
pwm1= machine.PWM(tim1, freq=freq1, duty=angle_to_duty(89,freq1), pin=12)
pwm2= machine.PWM(tim2, freq=freq1, duty=angle_to_duty(92,freq1), pin=13)
task = kpu.load(0x300000)#,model_addr="/sd/m.kmodel",
def main(labels = None, sensor_window=(224, 224), lcd_rotation=0, sensor_hmirror=1, sensor_vflip=1):
    sensor.reset(dual_buff=False)
    sensor.set_pixformat(sensor.RGB565)
    sensor.set_framesize(sensor.QVGA)
    sensor.set_windowing(sensor_window)
    sensor.set_auto_whitebal(1)
    sensor.set_hmirror(sensor_hmirror)
    sensor.set_vflip(sensor_vflip)
    sensor.run(1)
    lcd.init(type=1)
    lcd.rotation(lcd_rotation)
    lcd.clear(lcd.WHITE)

    img = image.Image(size=(320, 240))
    img.draw_string(90, 110, "loading model...", color=(255, 255, 255), scale=2)
    lcd.display(img)

    while(True):
        #t = time.ticks_ms()
        message[0]=" "
        message[1]="無物品"
        garbageKind=detect()  #進行物體檢測
        checkGarbageFull()    #檢查垃圾桶是否已滿,並且一直更新垃圾桶狀態
        if garbageKind !="no object":
            message[0]="檢測中"   #更新訊息陣列狀態
            message[1]=" "      #儲存標籤型別
            garbageKind=detectEnsureing(garbageKind)  #多次確認物體型別
            #message[1]=garbageKind
            action(garbageKind)   #進行型別對應的操作
        else:
            #message[1]="no object"
            pass
        #t = time.ticks_ms()-t
        #message[6]=str(t)

    kpu.deinit(task)  #釋放


if __name__ == "__main__":
    try:
        labels = ["fruit", "no object", "battery", "bottle", "can", "vegatable", "cigaret", "brick"]
        main(labels=labels)# model_addr=0x300000
        #main(labels=labels, model_addr="/sd/m.kmodel")
    finally:
        gc.collect()

 

專案地址:https://gitee.com/Zx11111111/2023.git

https://gitee.com/Zx11111111/2023.git

 

相關文章