基于亚博k210+arduino 智能垃圾桶(23工训赛)

复制代码
#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