Reputation: 101
I want to move a servo connected to arduino when I detect face in OpenCV (python).
OpenCV code:
import numpy as np
import cv2
import serial
import time
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
ser = serial.Serial('COM1', 19200,timeout=5)
time.sleep(6)
print(ser)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x1, y1, w1, h1) in faces:
cv2.rectangle(img, (x1, y1), (x1 + w1, y1 + h1), (255, 0, 0), 2)
detect_face=x1
print 'face distance: ', detect_face
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if 0 < detect_face < 100:
ser.write('Y')
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
Arduino Code:
#include <Servo.h>
int servoPin = 3;
Servo Servo1;
char incomingBit;
void setup() {
Servo1.attach(servoPin);
pinMode(servoPin, OUTPUT);
Serial.begin(19200);
}
void loop() {
if (Serial.available() > 0) {
incomingBit = Serial.read();
Serial.print("I received: ");
Serial.println(incomingBit);
if(incomingBit == 'Y' || incomingBit == 'y') {
Servo1.write(0);
delay(1000);
Servo1.write(90);
delay(1000);
Servo1.write(180);
delay(1000);
exit(0);
}
else {
digitalWrite(servoPin, LOW);
}
}
}
I get the following face_detect
value :
Serial<id=0x3203c30, open=True>(port='COM1', baudrate=19200, bytesize=8,
parity='N', stopbits=1, timeout=5, xonxoff=False, rtscts=False,
dsrdtr=False)
face distance: 203
face distance: 192
face distance: 187
face distance: 177
face distance: 163
face distance: 157
face distance: 145
face distance: 130
face distance: 116
face distance: 109
face distance: 104
face distance: 95
face distance: 80
face distance: 80
face distance: 98
face distance: 100
face distance: 98
face distance: 101
face distance: 110
face distance: 108
face distance: 109
face distance: 110
face distance: 110
face distance: 96
face distance: 88
face distance: 81
The first time face_detect
goes below 100, python sends a signal and servo does a 180 degree turn. But after that it just remains there. Although face_detect
goes below 100 several times, servo does not move.
I think i am having a loop problem. How to solve that?
Upvotes: 1
Views: 256
Reputation: 28958
exit(0) stops your program in the first loop cycle when you have a data in the serial buffer. It basically puts your arduino into an infinite loop that does nothing.
Have you even read your code befor posting that question?
Upvotes: 1