import sensor, image, time, network, usocket, sys
import pyb
import wifi
from pid import PID
from pyb import Servo
from pyb import Pin, Timer
SSID ='OPENMV_AP' # Network SSID
KEY ='1234567890' # Network key (must be 10 chars)
HOST = '' # Use first available interface
PORT = 8080 # Arbitrary non-privileged port
pan_servo=Servo(1)
tilt_servo=Servo(2)
led = pyb.LED(3)
green_threshold = (31, 100, -100, -44, -2, 69)
pan_pid = PID(p=0.07, i=0, imax=90)
tilt_pid = PID(p=0.05, i=0, imax=90)
sensor.reset() # Initialize the camera sensor.
sensor.set_contrast(1)
sensor.set_brightness(1)
sensor.set_saturation(1)
sensor.set_gainceiling(16)
sensor.set_pixformat(sensor.RGB565) # use RGB565.
sensor.set_framesize(sensor.QQVGA) # use QQVGA for speed.
sensor.skip_frames(10) # Let new settings take affect.
sensor.set_auto_whitebal(False) # turn this off.
clock = time.clock() # Tracks FPS.
face_cascade = image.HaarCascade("frontalface", stages=25)
# Init wlan module in AP mode.
wlan = network.WINC(mode=network.WINC.MODE_AP)
wlan.start_ap(SSID, key=KEY, security=wlan.WEP, channel=2)
# You can block waiting for client to connect
#print(wlan.wait_for_sta(10000))
def find_max(blobs):
max_size=0
for blob in blobs:
if blob[2]*blob[3] > max_size:
max_blob=blob
max_size = blob[2]*blob[3]
return max_blob
while (True):
clock.tick() # Track elapsed milliseconds between snapshots().
img = sensor.snapshot() # Take a picture and return the image.
blobs = img.find_blobs([green_threshold])
objects = img.to_grayscale().find_features(face_cascade, threshold=0.75, scale=1.35)
if blobs:
max_blob = find_max(blobs)
pan_error = max_blob.cx()-img.width()/2
tilt_error = max_blob.cy()-img.height()/2
print("pan_error: ", pan_error)
img.draw_rectangle(max_blob.rect()) # rect
img.draw_cross(max_blob.cx(), max_blob.cy()) # cx, cy
pan_output=pan_pid.get_pid(pan_error,1)/2
tilt_output=tilt_pid.get_pid(tilt_error,1)
print("pan_output",pan_output)
pan_servo.angle(pan_servo.angle()+pan_output)
tilt_servo.angle(tilt_servo.angle()-tilt_output)
elif objects:
led.on()
time.sleep_ms(150) #延时150ms
led.off()
else:
# Create server socket
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
try:
# Bind and listen
s.bind([HOST, PORT])
s.listen(5)
# Set server socket timeout
# NOTE: Due to a WINC FW bug, the server socket must be closed and reopened if
# the client disconnects. Use a timeout here to close and re-create the socket.
s.settimeout(3)
wifi.start_streaming(s)
except OSError as e:
s.close()
print("socket error: ", e)
#sys.print_exception(e)