I am trying to create a program when the camera capture the servo will rotate in 90 degrees continously, but my code will stop in print output 2 any idea to run the servo continously?

Here's the Code

import numpy as np
import cv2
import serial
import struct
import time

ser = serial.Serial('COM11',9600)



 # Capture frame-by-frame
    cap = cv2.VideoCapture(0)
    #framerate = cap.get(5)
    ret, frame = cap.read()
    # Our operations on the frame come here

    filename = 'C:/Users/DELVO/Desktop/tryTest/bruises/main/images' +  str(int(x)) + ".png"
    cv2.imwrite(filename, frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):

# When everything done, release the capture

Arduino Code

#include <Servo.h>
int data_x = 0;
int data_y = 0;
int data[1];
Servo myservo_x;
Servo myservo_y;// create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo_x.attach(7);  // attaches the servo on pin 9 to the servo object

void loop() {
  while (Serial.available() >= 2) {
    //    data_x=Serial.read();
    //    data_y=Serial.read();
    for (int i = 0; i < 2; i++) {
      data[i] = Serial.read();



  • "code will stop in print output 2" Where is "print output 2" exactly? I don't understand your problem. Please describe it more. What is the code actually doing and what did you expect it to do?
    – chrisl
    Mar 7 '20 at 12:06
  • did you use my program? when the output 2 print the servo will stop Mar 8 '20 at 3:51
  • No, I did not. We are first trying to find an error by looking at the code. Also I don't have a free pi with cam lying around, so I cannot test your code. So you mean, when 2 gets printed on the Pi
    – chrisl
    Mar 8 '20 at 8:50
  • no no im just using arduino anyway my main problem is when the 2 gets printed the servo will stop. Mar 8 '20 at 8:57

is the arduino code giving error because you have initialized the array data with length of 1 (int data[1];) and in the for loop the length is exceeding the allocated length of the string: for (int i = 0; i < 2; i++) { data[i] = Serial.read(); }

  • How to do it? that my servo won't stop if im not close the program. Mar 7 '20 at 10:00
  • 1
    @TrialAndError Have you tried writing int data[2]; instead of int data[1];? That is your first step, since it is the obvious error
    – chrisl
    Mar 7 '20 at 12:04
  • I see. Thank you. Mar 8 '20 at 3:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.