B
@kidswong999
import sensor, image, time, math
from pyb import UART,LED
import json
import ustruct
#white_threshold_01 = ((95, 100, -18, 3, -8, 4)); #白色阈值
red_threshold_01 = ((17, 67, 23, 71, -1, 45));
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False) # must be turned off for color tracking
sensor.set_auto_whitebal(False) # must be turned off for color tracking
clock = time.clock()
red_led =LED(1)
green_led =LED(2)
blue_led=LED(3)
uart = UART(3,500000) #定义串口3变量
uart.init(500000, bits=8, parity=None, stop=1) # init with given parameters
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
def USART_SendData(fx,dx,fy,dy):
global uart;
#frame=[0x2C,18,cx%0xff,int(cx/0xff),cy%0xff,int(cy/0xff),0x5B];
#data = bytearray(frame)
data = ustruct.pack("<bbhhhhb", #格式为俩个字符俩个短整型(2字节)
0xFF, #帧头
0xFE,
int(fx), # up sample by 4 #数据1
int(dx),
int(fy), # up sample by 4 #数据2
int(dy),
0xFD)
uart.write(data); #必须要传入一个字节数组
def recive_data():
global uart
if uart.any():
tmp_data = uart.readline();
print(tmp_data)
#mainloop
while(True):
clock.tick() # Track elapsed milliseconds between snapshots().
img = sensor.snapshot() # Take a picture and return the image.
# pixels_threshold=100, area_threshold=100
blobs = img.find_blobs([red_threshold_01], area_threshold=150);
cx=0;cy=0;
if blobs:
#如果找到了目标颜色
max_b = find_max(blobs);
# Draw a rect around the blob.
img.draw_rectangle(max_b[0:4]) # rect
#用矩形标记出目标颜色区域
img.draw_cross(max_b[5], max_b[6]) # cx, cy
img.draw_cross(160, 120) # 在中心点画标记
#在目标颜色区域的中心画十字形标记
cx=max_b[5];
cy=max_b[6];
img.draw_line((160,120,cx,cy), color=(127));
#img.draw_string(160,120, "(%d, %d)"%(160,120), color=(127));
img.draw_string(cx, cy, "(%d, %d)"%(cx,cy), color=(127));
fx=cx//10
fy=cy//10
dx=fx/10
dy=fy/10
USART_SendData(fx,dx,fy,dy) #发送点位坐
print('整数:%d '%fx,'余数:%d '%dx,'整数:%d '%fy,'余数:%d '%dy);
time.sleep(5);
recive_data();
blue_led.off()
red_led.off()
green_led.on()
else:
blue_led.off()
green_led.off()
red_led.on()
if uart.any():
tmp_data = uart.readline();
blue_led.on()
green_led.off()
red_led.off()