14 SERVO 01.2018
At the top of our sketch, we’ll include the TinyGPS++
and servo libraries. If you don’t have TinyGPS++ installed,
you can grab the latest version from
https://github.com/mikalhart/TinyGPSPlus. We’ll also
define pins for the servo output, control button input, etc.
I’ve also hard-coded the drop point and tolerance into
the sketch. You could allow a serial port setting of these,
but for this early prototype that was overkill. There are also
variables for the values of open and closed on the gripper. I
set mine through experimentation. Your results may vary
based on your servo and gripper design (Figure 4).
The setup function runs each time the Arduino is
powered up or reset. In the setup function, we need to set
the pin modes for the button and LED pins, attach a pin to
the servo object, start up the serial ports, and set the
gripper to open and the LED to off. Let’s start out with the
pin mode settings.
The button pin should be an input. We could attach an
external pull-up resistor, but instead I’ve elected to activate
the internal pull-up by using
the INPUT_PULLUP mode.
The LED needs to be an
output to drive it high/low.
Next, we tell the
gripperServo object that we
just created that it will
target pin servo_pin with its
We’ll then start up the
serial port at 4800 baud for
the GPS receiver. Finally, we’ll start with the gripper at the
open position and indicator LED off (Figure 5).
The toggleGripper function (Figure 6) does exactly
what its name states. If the gripper state is closed, it opens
it, turns off the LED, and sets the state to open. Otherwise
(the gripper is open), it closes the gripper, turns on the LED,
and sets the state to closed. This could be done more
concisely, but again, clarity is key for this quick prototype.
The shutdown function is a simple infinite while loop
with no instructions (Figure 7). Once we enter this
function, we’ll never leave. That’s ideal for the shutdown
state, and once we’ve dropped off our package, we don’t
want any more movement of the gripper or other system
Finally, we get to the main loop where most of the
work happens (Figure 8). The first thing we do is process
any characters waiting in the serial buffer from the GPS. If
we have a complete GPS message, we’ll calculate the
Figure 9: A simple test sketch that can be used to ensure that
your GPS is working is always a good idea.
Figure 5: The setup function runs at
startup and gets everything to a known
Figure 6: The toggle gripper function is a verbose but
easy to follow way to switch the state of the gripper.
Figure 7: The shutdown function spins
forever without any operations occurring.
Figure 8: The main loop is where most of the logic happens,
including checking the GPS and pushbutton.