I am using a Raspberry Pi 3 to control a servo motor (via PWM with RPi.GPIO) and a Pi Camera. What I want to do is, I want to move the servo motor several hundred times to a specific position. In order to avoid that the servo slightly changes the position, I stop the pwm inbetween movements. The following Python code is working well:
import RPi.GPIO as GPIO
import time
from picamera import PiCamera
import numpy as np
## settings for Servo motor control (forward and backward movement)
FW = 8.5
BW = 7.4
#GPIO.setwarnings(False)
camera = PiCamera()
# use GPIO pin numbering convention
GPIO.setmode(GPIO.BCM)
# define GPIO pin for PWM (for the servo motor)
ServoPin = 25
# set pin 25 servo pin for output
GPIO.setup(ServoPin, GPIO.OUT)
ISI = 10
n = ISI - 1
stim = [n*i for i in range(0,150)]
lastStimOn = stim[-1]
print lastStimOn
current_date = (time.strftime("%y%m%d"))
current_time = (time.strftime("%H%M%S"))
automatic_name = "".join(("/home/pi/Desktop/", current_date, "_", current_time, "_ISI", str(ISI), ".h264"))
camera.start_recording(automatic_name)
print(automatic_name)
time.sleep(10)
camera.stop_recording()
This works well, the video is recorded. But if the following code is then run, the servo stops after moving 240 times (although it should move more often) and the video file that is created, does not include any data (it has a size of only 19 bytes):
stimON = np.array(stim)
stimOFF = stimON + 5
# create object for PWM at 50 Hz
pwm = GPIO.PWM(ServoPin, 50)
# set Timer to 0
Timer = 0
try:
for x in range(0, (lastStimOn+120)):
print (x, Timer)
Timer = Timer + 1
time.sleep(0.1) # run this line, if you want to speed up
#time.sleep(1)
if any(stimON == Timer):
pwm = GPIO.PWM(ServoPin, 50)
# move dummy forwards
pwm.start(FW)
# wait 0.5 sec
time.sleep(0.5)
# stop PWM output
pwm.stop()
if any(stimOFF == Timer):
pwm = GPIO.PWM(ServoPin, 50)
pwm.start(BW)
time.sleep(0.5)
pwm.stop()
if (Timer == (lastStimOn-5)):
current_date = (time.strftime("%y%m%d"))
current_time = (time.strftime("%H%M%S"))
automatic_name = "".join(("/home/pi/Desktop/", current_date, "_", current_time, "_ISI", str(ISI), ".h264"))
camera.start_recording(automatic_name)
if (Timer == (lastStimOn+119)):
camera.stop_recording()
Timer = 0
RUN = False
pwm = GPIO.PWM(ServoPin, 50)
pwm.start(BW)
time.sleep(0.5)
pwm.stop()
GPIO.cleanup()
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
GPIO.cleanup() # cleanup all GPIO
print "Finished"
Does anyone have encountered this problem as well?
Can someone having a PiCamera run this code and try to reproduce the problem I have? What can I do to avoid it? Any ideas?
Thanks,
Steffi