Question

This is a timelapse script for moving a camera along a dolly. The problem is that when I run the code, sometimes (at iteration 7 exactly, for example) the dolly is moving and the camera snaps a photo at the same time. It's as if the commands aren't blocking before the next one gets executed. As you can see, I've tried scattering sleep's in the code to no avail.

Here is the workflow:

  1. Raspberry Pi sends commands to camera (snap photo) and Arduino (move dolly)
  2. The Arduino talks to EasyDriver Stepper Motor Driver, which talks to the stepper and causes dolly to move.
  3. Repeat.

Here is my Python script.

import os, commands, string, gps
from subprocess import Popen, PIPE
from time import sleep
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
sleep (5)

for i in range(0, 20):
    #To write information
    steps = 1000*(i+1)
    ser.write('1,'+str( steps )+'/n')
    sleep (4)

    bashCommand = "sudo /home/mh00h/Timelapse/camerareset.sh"
    os.system(bashCommand)
    sleep (2)
    bashCommand = "sudo gphoto2 --capture-image"
    os.system(bashCommand)
    sleep (1)
Was it helpful?

Solution

There are (potentially) two reasons why this doesn't block as required:

  1. Serial communication is buffered, so as long as the length of the data passed to Serial.write() is smaller than the buffer this call can return before the data is read by the Arduino sketch. In fact, depending on the length of the data and the size of the buffer, several calls to Serial.write() could complete before the Arduino completes any reads.
  2. The Arduino sketch may not block until the stepper motor has completed its movement. It would be useful to see the sketch to determine whether this is the case.

Sleeping between calls can help but even if you can get this to work you'll likely experience odd, non-reproducible behavior.

The solution to both the problems above is to synchronize the actions in your code. For the serial communication this can be achieved by sending a 'finished' message back from the Arduino sketch to the python script which will read from the serial port until it receives this message. How to synchronize the stepper motor with the Arduino sketch (if needed) will depend on how the Arduino to stepper motor communication is coded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top