import sensor
import time
import pyb
from machine import UART
RED_threshold = (30,40,12,127,-7,127)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
uart = UART(3, 115200)
clock = time.clock()
send1 = 'p'
send2 = 'q'
#=======找到画面的中心位置
img_center_x = sensor.width() //2
img_center_y = sensor.height() //2
threshold = 30
#=======找到最大的色块
def find_max(blobs):
max_size = 0
for blob in blobs:
if blob.pixels() >max_size :
max_blob = blob
max_size = blob.pixels()
return max_blob
#=======主循环
while True:
clock.tick()
img = sensor.snapshot()
blobs = img.find_blobs([RED_threshold])
if blobs:
max_blob = find_max(blobs)
blob_cx = max_blob.cx()
blob_cy = max_blob.cy()
img.draw_rectangle(max_blob.rect(), color=(0, 0, 255))
img.draw_cross(blob_cx ,blob_cy ,colar=(255,0,0))
#===相对位置
delta_x = blob_cx - img_center_x
delta_y = blob_cy - img_center_y
if abs(delta_x) < threshold and abs(delta_y) < threshold :# 消抖
send1 = 'o'
else :
if delta_x >30 :
send1 = 'a'
elif delta_x > 0:
send1 = 'b'
elif delta_x < -30 :
send1 = 'c'
else :
send1 = 'd'
#====y
if delta_y >50 :
send2 = 'x'
elif delta_y > 20:
send2 = 'z'
elif delta_y < -50 :
send2 = 'y'
elif delta_y < -50 :
send2 = 'w'
else :
send2 = 'o'
else :
print("not find")
print("you send:",send1)
print("you send:",send2)
uart.write(send1)
time.sleep_ms(2)
uart.write(send2)
print(clock.fps())