Home | Links | Contact |

Printed from www.nzmeccano.com

Top Home Bottom

Arduino Programming Reference

(Author: David Couch)

Arduino Programming Reference

Programming devices connected to the Arduino and Adafruit Motor Shield version 2

By David Couch, Nelson, New Zealand

Version 1.5  March 2021

This document shows the Arduino code required to control devices that are likely to be connected to an Arduino system, consisting of an Arduino Uno or Mega and an Adafruit Motor Shield version 2.

This is not an introduction to the Arduino or Arduino programming. It is intended as a handy reference for anyone who is familiar with the Arduino and its language, and wishes to write sketches to control DC motors, stepper motors, servos and LEDs, and take input from switches and potentiometers. It also describes how to connect each device to the Arduino.

About the code

An Arduino "sketch" or program consists of three main sections: the declaration section, the setup function and the loop function. Most devices need code included in more than one of these sections. The code required in each section is shown by the headings below. Code shown in the loop function could also be used in the setup function if appropriate
Lines beginning with // are comments, which you may or may not include in your code. Names shown in italics are variable names of your choice. However, note that a name defined in one example in this document may be referred to in another example. For instance, the Motor Shield named AFMS defined under Adafruit Motor Shield is referred to under DC Motor and Stepper Motor. Other code must be included exactly as shown.

Adafruit Motor Shield version 2

The original Adafruit motor shield can be purchased here. A cheaper but functionally identical clone can be purchased here. Whichever you choose, download the code library here and install it.

Note: the code for the version 1 shield is completely different.

Plug the shield into the Arduino. The shield should have pins in the SDA and SCL positions, to connect these signals to the Arduino. If the pins are not present they may be added, or the connections may be made with wires. The shield should preferably not have pins in the A4 and A5 positions, as these interfere with the operation of the analog pins on the Arduino.

Declaration section
// This code includes the Adafruit Motor Shield library
In the following, replace the square brackets by "less than" and "greater than" symbols.
#include [Adafruit_MotorShield.h]

// Create an Adafruit Motor Shield
// with the default I2C address of 0x60.
Adafruit_MotorShield AFMS = Adafruit_MotorShield();

// If you add a second motor shield, which must have a different I2C address,
// add a second declaration like this:
Adafruit_MotorShield AFMS2 = Adafruit_MotorShield(0x61);

setup function
// Connect the motor shield with the default maximum 1.6KHz PWM frequency.

// To use a different frequency, use a statement like this:

DC Motor

Connect the two wires from the motor to one pair of motor terminals on the motor shield, labelled M1, M2, M3 or M4. Do not connect the motor to ground or anything else.

Declaration section
// Connect a motor to motor port M2
Adafruit_DCMotor *Motor1 = AFMS.getMotor(2);
int motorSpeed;

setup function

loop function
// Set the motor direction: FORWARD, BACKWARD or RELEASE (stopped)

// Set the motor speed, in the range 0 - 255
// The same code could be used to drive several LEDs, with suitable series resistors,
// with variable brightness.

Stepper Motor

A bipolar motor has two coils with two wires connected to each, a total of four wires. Determine which pairs of wires are connected to each coil by measuring resistance. Connect one pair to a pair of motor terminals, e.g. M3, on the motor shield. Connect the other pair of wires to the other pair of terminals in the same group, e.g. M4.

A unipolar motor has an additional wire connected to the centre of each coil. Again determine which is which by measuring resistance. Connect each pair of end wires to a pair of motor terminals, as above. Connect the two centre wires to the ground terminal in the centre of the group.

Declaration section
// Connect a stepper motor with 200 steps per revolution (1.8 degree)
// to stepper motor port 2 (M3 and M4)
Adafruit_StepperMotor *stepper1 = AFMS.getStepper(200, 2);
int stepperSpeed;
int stepperSteps;

setup function

loop function

// Set the speed

// Move the motor. Parameters are
// the number of steps
// the direction: FORWARD or BACKWARD
// the stepping style: SINGLE, DOUBLE, INTERLEAVE or MICROSTEP
stepper1->step(stepperSteps, FORWARD, INTERLEAVE);


Push the servo connector on to one of the three-pin headers on the motor shield. The signal wire, coloured white or yellow, goes on the pin nearest the centre of the board.

Declaration section
// This uses the standard Arduino library
In the following, replace the square brackets by "less than" and "greater than" symbols.
#include [Servo.h]

// Declare a variable of type Servo
Servo servo1;

// The two servo headers are on pins 10 and 9
int servoPin = 10;
int servoAngle;
int servoSpeed;

setup function
// Attach a servo

loop function
// For a standard servo, this code sets its position
// servoAngle is in the range 0 - 180

// For a continuous rotation servo, this code sets the direction and speed
// of rotation. The value 0 gives full speed in one direction, and 180 gives
// full speed in the other direction. No rotation is given by a value of
// approximately 90, but the exact value should be found by experiment,
// or may be adjustable by a trim screw on the servo.


Connect a single LED to one of the Arduino digital pins.
Connect the positive lead to the pin, and the negative lead to ground, with a 200 – 300 ohm series resistor.

Declaration section
int ledPin = 5;
int dutyCycle;

setup function
// Set the pin as an output pin

loop function
// Turn the LED on or off with HIGH or LOW
// This code could be used to drive another simple on/off device, such as a relay

// Or use PWM for variable brightness
// dutyCycle is in the range 0 - 255


Connect a switch, pushbutton etc between a digital pin and ground.

Declaration section
int switchPin = 7;
int switchState;

setup function
// Set the switch pin as an input pin, and enable the internal pull-up resistor

loop function
// Read the state of the switch: LOW if the switch is ON, HIGH if it is OFF
switchState = digitalRead(switchPin);
if (switchState == LOW) {...

Potentiometer (variable resistor)

A 10k ohm linear potentiometer is suitable.

Connect the ends of the potentiometer to the +5 and ground pins.
Connect the wiper to an analog pin.

Declaration section
int analogPin = A1;
int analogValue;

setup function
// Set the pin as an input pin

loop function
// Read the value of the input, which will be in the range 0 -1023
analogValue = analogRead(analogPin);


A joystick usually contains two potentiometers and possibly one or more switches. Connect and program each as a separate device, as described above for switches and potentiometers.

Serial port

// This code allows you to write messages to the serial monitor in the Arduino
// program on your PC. It is extremely useful for debugging. See the Arduino
// language reference for details.

setup function

loop function
Serial.print(text or variable); // without line terminator
Serial.println(text or variable); // with line terminator


If you have any interesting information or comments about this page, please add them here:

Your name:
Your message:
Security check: (Please type in the text to prove you're a person!)
Login status:  You have not yet entered your user name and password. You cannot create or edit documents until you do.
Enter your user name and password to log in

Remember me

If you click on the box marked 'remember me next time', you will not have to log in again on this computer for three months.

If you don't have a user name yet, please click here

On this page...

Latest documents:

The Arduino Sketch 
and how to upload a Youtube or Vimeo video to the Gallery 
(Paulo Kroeff de Souza)
"Homemade" Screwed Rods
(Paulo Kroeff de Souza)
The Meccano driving band problem
(Paulo Kroeff de Souza)
Meccano Cord Reproduction
(Paulo Kroeff de Souza)
Substitutes for parts 142 and 155
(Philip Drew & Richard Smith)
Midlands Meccano Guild
105th Model Report 
92nd Model Report 
(Neil Bedford and John Rogers)
Midlands Meccano Guild
104th Model Report 
91st Model Report 
103rd Meeting Model Report 
by Peter Stuart, Meccano Modellers Association Sydney Inc 
(Richard Smith and Neil Bedford)
Midlands Meccano Guild
102nd Meeting Model Report 
(John Rogers & Colin Bull)
Midlands Meccano Guild
101st Meeting Model Report 
Spanner Challenge 
(John Rogers and Neil Bedford)
Midlands Meccano Guild
100th Meeting Model Report 
A G gauge model 
(Colin Bull & Richard Smith)
Midlands Meccano Guild
99th Meeting Model Report 
98th Meeting Model Report 
97th Meeting Model Report 
(David Couch)
The Little Tram
An introductory Arduino project 
(G. Eiermann and M. Schild)
A Short History of MARKLIN Metall
96th Meeting Model Report 
83rd Meeting Model Report 
82nd Meeting Model Report 
Picks up three golf balls 
(Roger Marriott)
Midlands Meccano Guild
95th Meeting Model Report 
The Spanner Challenge 
94th Meeting Report 
(Andre Theberge)
Meccano Segway
(Andre Theberge)
A Meccano Segway
Arduino code 
(Andre Theberge)
A Meccano Segway
Assembly instructions 
(Michael J. Walker)
Meet the new MMG President
Geoff Wright 
The Spanner Challenge 
(Michael Walker)
Midlands Meccano Guild
93rd Model Report 
Report by Michael J. Walker. 
92nd Model Report 
(Stan Knight)
Minimal Meccano
Pocket Meccano Sets of the 1970s 
Little Lever, Bolton 
The Spanner Challenge 
91st Model Report 
(Bob Thompson)
Back to the beginning
Shop Display Model 
90th Meeting Report 
(Old Blue Gold)
Getting Old
A screwy story 
The Spanner Challenge 
Model report written by Michael J. Walker 
76th Meeting Report 
Exhibition in Nelson, New Zealand 
(Barry Gerdes)
Meccano Radio
How to flatten  
(Rod Socket)
Dear Mrs Spanner
Survival techniques for the Meccanoman's wife 
(Stan Knight)
The Top Ten Tools
Indispensable Tools for the Meccanoman 
A call for help 
The Spanner Challenge 
For small brass and nickel parts. Also for stripping paint and rotted zinc plating. 
(Stephen Heafield)
Waterslide Transfers
Refurbishing 0 & 00 Aero Models 
Construction details 
or Put Your Hammer Away 
Mobile Morris Crane from 1968 MM 
Bert Love's Blocksetter in colour 
The dangers of internet auctions 
(Rob Thompson pp Terry Bullingh)
BlockSetter Tower
Built by Terry Bullingham 
(Rob Thompson pp John Reid)
Captain Robert Falcon Scott
1912 Polar Sledging Party 
(Niels Gottlob)
Bucket Wheel Excavator
Transcribed from typed document with photos 
Selected Spanner messages 18th to 24th January 
Selected Spanner messages 11th to 17th January 
Selected Spanner messages 4th to 10th January 
(Norbert Klimmek)
Hulett Ore Unloader
A 1 to 32 Scale Model 
(Joe Attard of Malta)
A model ship
(Arup Dasgupta (ISM 652))
My E15R Motor
A repair story 
About Meccano
What is Meccano? 
Thoughts about modern Meccano 
Not many in this condition I'll bet! 
Some hints and tips 
 View all | Chat | Models | Hints and Tips | Opinion | Reviews | Mine