0% found this document useful (0 votes)
18 views26 pages

MEC8063 Tutorial 1 Arduino Getting Started

Uploaded by

yulin lin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views26 pages

MEC8063 Tutorial 1 Arduino Getting Started

Uploaded by

yulin lin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

MEC8063 Introduction to Mechatronics Design

Tutorial 1 – Arduino : Getting started

Objective: This tutorial is to gain experience in creating and simulating basic circuits using the Arduino and writing
some simple programs. You will get to understand the Arduino hardware fundamentals, the basics of
programming your Arduino in C/C++, writing functions in Arduino sketches and using the Arduino’s digital and
analogue inputs and outputs. This tutorial will also get you started on using an Arduino simulation software
package called Tinkercad.

Reading: There is no specific reading for this tutorial however if you were interested in learning more about the
Arduino, a good introductory book is “Programming Arduino: Getting Started with Sketches, Second Edition” by
Simon Monk.

1. Introduction

Microcontrollers are used in embedded systems as programmable controllers. Although they contain a processor,
memory, input/output functionality, they differ from computers as they do not have an operating system, namely
they do not have a background environment on which you can run programs/applications. So, for example, if you
wanted to write and run a program on a computer, you would open a text editor, write the program, use another
program to compile your text file (to make it into a computer readable file) and then run the program. As
microcontrollers do not provide this functionality, when writing and compiling a program for a microcontroller
this needs to be done on a different computer and then uploaded onto the microcontroller. This job is made
easier by the use of an integrated development environment (IDE) which is essentially a compiler and text editor
with additional tools, for example syntax highlighting.

There are many manufacturers of microcontrollers and microcontroller platforms (a microcontroller chip
mounted on a circuit board with additional components to make it easier for you to use). An Arduino is an
example of a microcontroller platform. The Arduino platform itself comes in a number of variations depending on
whether your application requires small size, more input/output options, etc.

An Arduino, as shown in figure 1, is a small microcontroller board with a universal serial bus (USB) plug to connect
to your computer and a number of connection sockets that can be wired to external electronics such as motors,
relays, light sensors, microphones, switches and more. They can either be powered through the USB connection
from the computer, from a 9V battery, or from a power supply. They can be controlled from the computer or
programmed by the computer and then disconnected and allowed to work independently (provided they are still
powered).

Arduino interface boards (referred to as ‘shields’), provide a low-cost, easy-to-use technology to create
microcontroller-based projects. With a little electronics, you can make your Arduino do all sorts of things, from
controlling lights to managing the power of a solar energy system. The basic boards are supplemented by
accessory shield boards that can be plugged on top of the Arduino board as shown in figure 2.

John Hedley and Paul Watson, School of Engineering, 2024. Page 1


MEC8063 Introduction to Mechatronics Design

Figure 1: Arduino Uno board

Figure 2: LCD Shield connected on top of Arduino Uno

To create the necessary functionality and required operations, the user must program the Arduino using the
C/C++ programming language. It is best to think of a program (known as a sketch in Arduino) as a list of
instructions to be carried out in the order that they are written down.

The heart of the Arduino is a microcontroller, a small computer on a chip. The 28-pin microcontroller chip used on
the Arduino Uno board is the ATmega328 and fitted into a dual in-line (DIL) socket so it can be easily replaced. It
has a processor, random access memory (RAM) for holding data, erasable programmable read-only memory
(EPROM) or flash memory for holding your programs and it has input and output pins. These input/output (I/O)
pins link the microcontroller to the rest of your electronics.

Inputs can read both digital (i.e. on or off) and analogue (i.e. what is the voltage at a pin). This opens up the
opportunity of connecting many different types of sensors for lights, temperature, sound etc. Outputs can also be
both digital and analogue. So, you can set a digital pin to be on or off (i.e. 0V or 5V) and this can turn LEDs on or
off directly, or you can use the output to control higher power devices such as motors. They can also be used to
set an analogue output voltage to a pin, allowing you to control the speed of a motor or the brightness of a light,
rather than simply turning it on or off. A good reference for information is the Arduino website:
https://www.arduino.cc/reference/en/

John Hedley and Paul Watson, School of Engineering, 2024. Page 2


MEC8063 Introduction to Mechatronics Design
For convenience of teaching, we will use an Arduino simulator (Tinkercad) to learn the basics of using an Arduino.
However each tutorial will also have practical examples for you to try your hand at using the actual electronics
hardware. Although the examples in Tinkercad are a quick way to get started and build a circuit, for the exercises
you will build our circuits from the component parts as this is a better way to understand what is happening. It is
also worth typing in the program code (rather than cut and paste) as this will help you learn the subtleties of the
programming language. In your programs, try to structure your text (leave indents for loops, conditional
statements, etc) as this makes it much clearer to understand the program and find errors.

2. Tinkercad

Note: There seems to be a problem running Tinkercad on Microsoft Edge, the program keeps crashing. Google
Chrome seems to work OK.

Tinkercad is a free to use online CAD and circuit simulator from AutoDesk. We will use this to design and simulate
Arduino circuits. The circuit simulator does have limited functionality however it is an ideal way to start learning
about Arduino/circuit building and its clear presentation makes it obvious to users how components connect
together.

Note that there are occasionally issues with the Tinkercad compiler and the software will not run correctly. You
will see a warning message when this happens. This problem is usually rectified within 24 hours.

To use this, you will firstly need to register an account. Go to https://www.tinkercad.com, select ‘JOIN NOW’ from
the top right corner of the screen and then ‘Create a personal account’. Once you are logged in, click on ‘Designs’
and then Circuits from the list of options.

To get started, we shall look at a couple of simple examples. Click on the search icon, search for ‘blink’ (narrow to
selection to Circuits by selecting the appropriate tab) and then select an example (example given here is ‘Blink
(Blocks)’ by bekathwia). Select ‘Copy and Tinker’ and you should see the circuit shown in figure 3.

Figure 3: The Tinkercad circuit screen

If you click on the Code item, the Arduino program will be displayed. This will initially be shown in block format,
select the Text option, as shown in figure 4, to get a program listing. It is important to learn to program in text
format as the block format will not have all the options we need as we progress through the exercises. Start the

John Hedley and Paul Watson, School of Engineering, 2024. Page 3


MEC8063 Introduction to Mechatronics Design
simulation and you should see the LED continually switch on and then off at a rate of once per second (depending
on the example downloaded) with respect to simulation time. For more complicated circuits and programs, the
simulation time will run much slower (due to the number of calculations needed). Stop the simulation and try
clicking on some components. For wires, you can change the colour, for resistors you can change the resistance
value, etc. In the program code try changing both the delay commands to delay(250), these changes will be saved
automatically, and rerun the simulation. The LED should now blink much faster. If communication were being sent
via the serial port, these could be viewed by turning on the Serial Monitor (more about this in a later tutorial).

Figure 4: Programming on Tinkercad.

Return to your Home menu (top left icon) and you should see this circuit listed as ‘Copy of Blink (Blocks)’. The
gear icon in the top right corner of this box is where you can change the properties. Click on ‘Properties’, change
the design name to ‘MyBlink’ and save changes. If you are wanting to share your design, you can also make if
publically available. The design is now updated with the new name however if you click on the circuit to get more
details, the information will still show that ‘This is a remix of Blink (Blocks) by bekathwia’. You can Tinker this
further if you wish but for now will we close this window.

Click on ‘Create’ then ‘Circuit’ and you will be presented with a blank circuit screen. Go to Components (note that
the Code display will need to be closed to show this) and show the drop down list. You can build your circuits
from individual components or use a starter circuit to begin with and then alter accordingly. Select the Starters –
Arduino option and drag the Blink circuit into your design space. Try looking at the code and running the
simulation. This should work in the same as the previous example. Return to your home screen and now you
should see 2 circuits displayed, the first MyBlink circuit and this newer one given a random default name (you
should change this to something more meaningful).

The main difference is that if you now click on this new circuit, it will show it as your circuit rather than a remix
from someone else. This ensures that if you make your file available for public use, you are still credited with the
original. It also means that if the examiners need to check for any cases of plagiarism, we can ask you to
demonstrate any files you submit for marking are your own work.

This concludes the introduction to Tinkercad. The tutorials will guide you through further examples which you can
modify to produce your own original solutions to the module assignment.

John Hedley and Paul Watson, School of Engineering, 2024. Page 4


MEC8063 Introduction to Mechatronics Design

3. Arduino programming basics

3.1. Sketches

A sketch or program is a list of instructions that allows the Arduino to interface to buttons, LEDs, network
modules and much more. The software language C/C++ is used to create the Arduino sketches. After the sketch
has been written, the Arduino will first compile the code to translate it into machine code, and if there are no
errors transfer the machine code into the microcontroller to run the application.

When you create a new sketch the “setup” and “loop” functions are automatically created by the software and
are essential to every program you write. In Arduino, some functions are already defined for you e.g.
digitalWrite() but others you must define for yourself. Setup and loop are two functions that you must define for
yourself in every sketch you create. Setup and loop are defined as void because they do not return a value.

• setup(): Will run just once when the sketch begins.


• loop(): Will run continuously after setup() has occurred whilst the Arduino is powered.

Create a new circuit in Tinkercad as shown in figure 5 and enter the program shown in figure 6.

Figure 5: Constructing a simple LED circuit.

// Blink: See https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink

// The setup function runs once when the program is initially started
void setup()
{
// Initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

// The loop function repeats continuously until power is disconnected


void loop()
{
digitalWrite(LED_BUILTIN, HIGH); // turn LED on (HIGH voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn LED off (LOW voltage level)
delay(1000); // wait for a second
}

John Hedley and Paul Watson, School of Engineering, 2024. Page 5


MEC8063 Introduction to Mechatronics Design
Figure 6: The Arduino example program Blink (found in Examples – Basic – Blink).

Let’s consider this blinking LED sketch:

1. Run setup and set pin LED_BUILTIN (which has a preprogrammed value of 13) to be an output.
2. Run loop and set pin 13 (LED_BUILTIN) to high (LED on).
3. Delay for 1 second (1000 milliseconds).
4. Set pin 13 to low (LED off).
5. Delay for 1 second (1000 milliseconds).
6. Run loop again, going back to step 2, and set pin 13 to high (LED on).

The program code is running in a continuously loop to switch the LED ‘On’ and then ‘Off’ at one second intervals.
There are several things to note when running the program (the same effect would happen on the real hardware).

• When starting the simulation, the connection to the computer is animated as being plugged in. This would
have to be plugged in to upload the program on a real Arduino. This cable also supplies power to the Arduino.
Once the program is uploaded, you could unplug this cable and the program would still run provided you
supplied power to the Arduino from another source (there are 3 options for supplying power).

• A small LED is illuminated on the Arduino (labelled ON). This shows that the Arduino is being powered. There
are also two LEDs that flash when communications are taking place (labelled TX and RX).

• You have connected an LED to the Arduino. The Arduino does however contain an internal LED connected to
pin 13 (labelled L). This is purely for testing purposes and you should see this internal LED blink at the same
rate as the externally connected one.

Try changing the delay to see the effect of the LED. If the switching effect becomes too fast, your eye will not be
able to perceive it in practise and the LED will just appear to be continuously on but half the intensity. For the
simulation, this depends on how fast the simulation is running and the update rate of your monitor.

3.1.1 Variables

Variables play an important role in computer programming because they enable programmers to write flexible
programs. Rather than entering data directly into a program, a programmer can use variables to store and
represent the data. Then, when the program is executed, the variables are replaced with real data. This makes it
possible for the same program to process different sets of data.

Every variable has a name, called the variable name (decided by user), and a data type. The normal convention for
naming is to start variables with a lowercase letter and begin each new word with an uppercase letter. A
variable's data type indicates what sort of value the variable represents, such as whether it is an integer, a
floating-point number, or a character.

We will change this program slightly to make it a little more interesting. What we will aim to do is increase the
delay between blinking. In figure 6, the delay was set to a fixed amount of 1000 ms. We will replace 1000 with a
variable, arbitrarily called delayPeriod, and set this to a value of 1000 as shown in figure 7. Note it is useful to call
variables something that makes sense to read, for example we could have called it x but then if you have lots of
variables, it makes it difficult to remember what each one is for. We now have the option of changing this value
during program execution, in this case increasing it by 100 ms on every program loop. Try running this new
program and see if the LED behaves as expected.

John Hedley and Paul Watson, School of Engineering, 2024. Page 6


MEC8063 Introduction to Mechatronics Design

// Blink 2
// --- put your name and date here ---

// Define variables
int ledPin = 13;
int delayPeriod = 1000;

void setup()
{
pinMode(LedPin, OUTPUT); // Initialise output pin
}

void loop()
{
digitalWrite(ledPin, HIGH); // turn the LED on
delay(delayPeriod); // wait
digitalWrite(ledPin, LOW); // turn the LED off
delay(delayPeriod); // wait

delayPeriod = delayPeriod + 100; // increase the delay


}

Figure 7: A Blink program with variable delay.

In this program we have also defined ledPin as 13 (the digital pin to which the led is connected) and used that in
our program. The original program used LED_BUILTIN which works in exactly the same way but is one of the
variable names that is automatically defined by the Arduino IDE, other examples are HIGH and LOW which have
defined values of 1 and 0 respectively.

3.1.2. Data types

All the examples of variables we have used so far in our programs have been int (i.e. integer) variables. This is the
most common variable type, but there are others such as float (floating point numbers), boolean (0 or 1), string
(text string) etc. The two important aspects of declaring a data type: what type you wish to choose (for example
int, float, etc) and its scope.

When choosing type, you need to aware of what range of numbers are stored within that type, for example an int
can store any value between -32,768 to 32,767, for more details see:
https://www.arduino.cc/reference/en/language/variables/data-types/int/

For scope, we need to be aware of where that variable will be recognised. In figure 5 we defined ledPin at the
very start of the program – this is known as a global variable and will be recognised by all parts of the program. If
we defined ledPin within the void loop() part of the program, it would be known as a local variable and only
recognised within this loop part of the program.

As you work through the examples in these tutorials, take a note if variables are global or local. Details on other
Arduino data types are available via the language reference website.

3.1.3. Error checking

One last thing to try is to change:

John Hedley and Paul Watson, School of Engineering, 2024. Page 7


MEC8063 Introduction to Mechatronics Design
delayPeriod = delayPeriod + 100;

to:

delayPeriod = delayperiod + 100;

noting the small p in the second delayperiod. Try running the simulation and you will see that errors are
generated. Replace this with:

delayPeriod = delayPeriod + 100

noting a correction in the p but no semicolon at the end. Again errors are generated (different ones in this case)
when trying to run the program. These are 2 of the commonest errors when programming (slightly wrong name
typed in and slight errors in the syntax) and it is important to be able to use these error messages to find faults in
your programs. This is down to plenty of practise and you will develop this skill as the module progresses (and you
will also find plenty of errors where you will need help from the teaching staff to resolve).

2.2 Serial monitor

The serial monitor is a good way to know what is happening in your Arduino program. Printing via the serial
monitor will slow the program and therefore should be used to a minimal extent however it is very useful to put
in lots of serial monitor writes during program development to check the program is functioning correctly. These
writes can be removed (or better still commented out for ease of future use) once you have finalised your
program.

We will edit the program in figure 7 to write some information to the Arduino IDE serial monitor, this will be
trivial information at present but serves as a starting point for future exercises. In figure 8 you will see a modified
Blink program, open the serial monitor and re-run the program. You should see:

Delay = 1000
Delay = 1100
Delay = 1200
Delay = 1300

printed on the serial monitor.

John Hedley and Paul Watson, School of Engineering, 2024. Page 8


MEC8063 Introduction to Mechatronics Design

// Blink 2
// --- put your name and date here ---

// Define variables
int ledPin = 13;
int delayPeriod = 1000;

void setup()
{
pinMode(ledPin, OUTPUT); // Initialise output pin
Serial.begin(9600); // Initialise serial communications with baudrate 9600
}

void loop()
{
digitalWrite(ledPin, HIGH); // turn the LED on
delay(delayPeriod); // wait
digitalWrite(ledPin, LOW); // turn the LED off
delay(delayPeriod); // wait

Serial.print("Delay = "); // serial print info to user


Serial.println(delayPeriod); // println gives a linefeed after this print

delayPeriod = delayPeriod + 100; // increase the delay


}

Figure 8: A Blink program with serial communications.

There are three new lines of code entered, one line to initiate the serial communications with a baud rate and
another two lines to print the desired information over the serial comms. The speed of transmission is defined by
the baud rate, in this case 9600 bits per second (we will learn more about this when we discuss communications
in tutorial 6).

Note: In this simulation case, we have defined the baud rate (the speed of transmission) only in the Arduino
program as we are using the Arduino IDE for communications. If we used this serial communication to talk to
another computer, we would need to ensure both the Arduino and this other computer are set to read/write at the
same baud rate.

Return to your main Tinkercad menu and make a copy of this circuit (select the gear wheel in the top right hand
corner of the circuit icon and select duplicate). This will open up the copy in the circuit editor. Click on the circuit
name (top left of window) and change its name to Test. We will use this circuit to play around with different
program options.

Comment out (i.e. place a // at the start of the line) for the digitalWrite and delay commands and change the
increment of delayPeriod from 100 to 1000 (the LED will not flash but the program will run much faster). Run the
program and watch the values be printed on the serial monitor.

What is the highest value that delayPeriod goes up to? Then what happens?

delayPeriod was defined as an integer variable. Check the Arduino reference page for the int data type. Does your
display on the serial monitor now make sense? You can try changing the variable type to something else, for
example, to type long and see how this affects its range (you may wish to alter increment size on delayPeriod
accordingly).

John Hedley and Paul Watson, School of Engineering, 2024. Page 9


MEC8063 Introduction to Mechatronics Design
Although it is tempting to give each variable as much range as possible, this would be inefficient for programming
(the Arduino needs to reserve the right amount of memory for each variable) and therefore you should limit
variable range to what is needed. Note that getting it wrong can lead to runtime errors and so the serial monitor
is a good way to check that values are what you expect them to be.

2.3. Functions

Segmenting code into functions allows a programmer to create modular pieces of code that perform a defined
task and then return to the area of code from which the function was "called". The typical case for creating a
function is when one needs to perform the same action multiple times in a program. The anatomy of a function is
shown in figure 9.

Figure 9: Example of a function (image reproduced from Arduino website).

In this example, we are sending two integer values to the function and expecting an integer value to be returned.
So if we write program code of:

void loop()
{
int z = myMultiplyFunction(3,4);
}

then 12 would be stored in the variable z. Note that z is a local variable to the loop function and so will only be
recognised in this part of the program whilst x,y and result are local variables to the myMultiplyFunction and are
only recognised in this part of the program.

2.3.1. Example

Code that flashes an LED is a typical example that should be put in a function. So let’s create a function and give it
a name called flash in the example shown in figure 10. All we have done here is to move the four lines of code
that flash the LED from the middle of the for loop to be in a function of their own called flash. Now you can make
the LED flash at any time you like by just calling the new function by writing flash();

John Hedley and Paul Watson, School of Engineering, 2024. Page 10


MEC8063 Introduction to Mechatronics Design

// LED flash

int ledPin = 13;


int delayPeriod = 250;

void setup()
{
pinMode(ledPin, OUTPUT);
}

void loop()
{
for (int i = 0; i< 20; i++)
{
flash(); // Call function
}
delay (3000);
}

void flash()
{
digitalWrite(ledPin, HIGH); // turn the LED on
delay(delayPeriod); // wait
digitalWrite(ledPin, LOW); // turn the LED off
delay(delayPeriod); // wait
}

Figure 10: Function to flash an LED.

This is a fairly straightforward but demonstrates how much tidier, compact and easier to read a program is by
intelligent use of functions. In this case the routine is set up to not receive or return any values. It works in this
case because delayPeriod is set as a global variable (defined before the program begins) and so is recognised by
all parts of the program.

Try writing a function to receive 2 numbers and return the value that is each number squared and then added
together (see https://www.arduino.cc/en/Reference/FunctionDeclaration for help on this subject). You should
print your answer over the serial monitor. A solution is provided in the appendix.

2.4. Commands

The C/C++ language has a number of built-in commands to allow a user to perform different operations and
program flow control. The following is an example of two common commands called the if/else and for
statements. There are many more commands available as shown on the language reference website:
https://www.arduino.cc/reference/en/ which we will come across as we work through the module.

2.4.1. if/else

if/else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be
grouped together. For example, an analog input could be tested and one action A taken if the input was less than
500, and another action B taken if the input was 500 or greater. The example code would look like this:

John Hedley and Paul Watson, School of Engineering, 2024. Page 11


MEC8063 Introduction to Mechatronics Design
if (inputVal < 500)
{
// action A
}
else
{
// action B
}

The else command can proceed another if test, so that multiple, mutually exclusive tests can be run at the same
time. Each test will proceed to the next one until a true test is encountered. When a true test is found, its
associated block of code is run, and the program then skips to the line following the entire if/else construction. If
no test proves to be true, the default else block is executed (if one is present) and sets the default behaviour.

2.4.2. for

The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is
usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is
often used in combination with arrays to operate on collections of data/pins. There are three parts to the for loop
header:

for (initialization; condition; increment)


{
//statement(s);
}

The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it's true,
the statement block and the increment is executed, then the condition is tested again. When the condition
becomes false, the loop ends. For example:

for (int i=0; i <= 255; i++)


{
analogWrite(13, i);
delay(10);
}

The instructions analogWrite() and delay() which are contained within the for statement brackets will run a total
of 256 times before exiting.

2.4.3. Syntax

Note that in these command structures, we have defined what code we wish to run within parentheses, i.e. { }.
However if you only wish to run one line of code then the parentheses are not needed. For example:

for (int i=0; i <= 255; i++)


analogWrite(13, i);

is the same as:

John Hedley and Paul Watson, School of Engineering, 2024. Page 12


MEC8063 Introduction to Mechatronics Design
for (int i=0; i <= 255; i++)
{
analogWrite(13, i);
}

However if you also need the delay(10) command included within this block then you must include the
parentheses.

2.4.4. Exercises

Write a program using the ‘for’ command to cycle through the numbers 1 to 10. Using the ‘if’ command, check to
see if this number is divisible by 3. If it is then print a message over the serial port reporting what number this is.

Note: The / sign is used for divide, e.g. int x = 7/3; then x = 2 (as x is defined as an integer it contains no decimal
places). The % sign is used to find the remainder so for int x = 7%3 then x = 1. To check a value, use the if
statement with the comparison operator == (see comparison operators on the Arduino reference page:
https://www.arduino.cc/reference/en/ ) so if 7%3 == 0 then you know the number is divisible by 3. Once
completed, check your solution with one possible solution given in the appendix.

For those wanting a challenge, alter this program to identify prime numbers. Hint: Assume your number x is prime
and then check it is not divisible by all integers between 2 and (x-1) inclusive. A solution is given in the appendix
(note there are faster solutions possible).

2.5. Input/output

The usefulness of the Arduino comes from its ability to be programmed and then embedded in an application. It
therefore needs to be able input and output signals to the rest of the system. Digital inputs just give you an on/off
answer to what is happening at a particular pin on the Arduino board. Analogue inputs, however, give you a value
between 0 and 1023 depending on the voltage at the analogue input pin. In this section, we will look at some
simple input and output exercises. These will then be developed further in the following tutorials.

As an example of an analogue digitisation, create the circuit and enter the code shown in figure 11. Run the
simulation and see what value is sent over the serial monitor. The program reads the analogue input using the
analogRead function and this voltage is stored within the variable reading. Click on the wire and then move the
end point (currently the end connected to 5V) to a GND pin on the Arduino, note the readings obtained. Finally
move the wire connection to the 3.3V pin and again note the readings. Are these what you expect them to be?

The Arduino has a 10 bit, 5V digitiser and so has 210 = 1024 levels of digitisation (0 to 1023). Therefore a 3.3V input
should give a reading of (3.3/5)×1023.

Now add a potentiometer, as shown in figure 12. When running the simulation, you can now change the setting
on the potentiometer to get any voltage between 0V and 5V input into the Arduino.

John Hedley and Paul Watson, School of Engineering, 2024. Page 13


MEC8063 Introduction to Mechatronics Design

// Analogue input example

int inputPin = A0;


int reading = 0;

void setup()
{
// open serial comms
Serial.begin(9600);
}

void loop()
{
// read value and print
reading = analogRead(inputPin);
Serial.println(reading);
}

Figure 11: A simple analogue read example.

Figure 12: Varying the input voltage to the analogue input pin.

A few of the digital pins – namely digital pins 3, 5, 6, 9, 10, and 11 – can provide variable output other than just
0V or 5V. These are the pins on the board with a ~ or “PWM” next to them. PWM stands for Pulse Width
Modulation, which refers to the means of controlling the amount of voltage at the output. It does so by rapidly
turning the output on and off. The pulses are delivered at the same rate but the length of the pulse is varied. The
analogWrite command is used to initiate this and you must supply the pin number and a value between 0 and 255
(i.e. 8 bits representing 0% to 100%) to set the level. If you were to use PWM to control the speed of a motor,
then if the pulse were long the motor would travel fast. If, however, the pulses are short then the motor would
travel slower. Hence, this is a common method to control the speed of a dc motor by varying the pulse length.
You can test the pulse duration using a basic method involving a multi-meter or better still by using an
oscilloscope to monitor the actual pulse waveform.

Now let us try an output circuit. Delete the potentiometer and add a multimeter (selected to measure V)
connected to pin 3 and GND on the Arduino as shown in figure 13. Also add an oscilloscope and make separate
connections to this also. Set the Time Per Division on the oscilloscope to 1ms. Enter the program given in figure
14 and run the simulation. You can enter values via the serial monitor (type in the value and press the Send
button), the value of which should be displayed as an output voltage on the multimeter. A few things to note:

• The program reads the number 0 to 5 and then scales this to between 0 and 255. This is because 255
corresponds to a duty cycle of 100% and so has the output continuously turned on at a 5V level.

John Hedley and Paul Watson, School of Engineering, 2024. Page 14


MEC8063 Introduction to Mechatronics Design
• Only 1 digit is read (you can determine this by looking at the code) so if you type in 4.2 then it would set the
voltage to 2 (it actually sets it to 4, and then to ., and then to 2 but as this will happen very fast, you will only
notice the 2 being displayed).

• If, for example, you enter the number 2 then the serial monitor does not send the number 2 but an ASCII
character of 2 with a byte of value 00110010 (see table 1) which corresponds to a value of 50. The program
takes away the ASCII value for ‘0’ corresponding to 48 to obtain the numerical value of 2. This is important to
note as, for example, you may inadvertently send values (ASCII characters) without realising. For example, if
you use the Serial.println command then a line feed (LF, ASCII value of 10) will be sent as the last character.

Note: You can set the serial port on a PC to automatically send a line feed or carriage return (CR, ASCII value of
13) to any message sent. So when communicating to an Arduino via the PC serial port, be sure to check if such
extra characters are being sent. You will notice this effect when completing the practical exercises.

• The value does jump around the set point (except for 0V and 5V). This is because the output is actually a pulse
width modulated (PWM) signal which is continually switching on and off at a given duty cycle – this can be
seen on the oscilloscope. A low pass filter would help to rectify this. In practise, this switching is fast enough
not to be noticed by any connected hardware (unless the hardware reacts faster that the PWM frequency).

Note: An actual multimeter is relatively slow to react so you will not see this fluctuating in practical examples.

Figure 13: Example of an analogue output.

John Hedley and Paul Watson, School of Engineering, 2024. Page 15


MEC8063 Introduction to Mechatronics Design

// PWM

int outputPin = 3; // output pin for PWM signal

void setup()
{
pinMode(outputPin, OUTPUT);
Serial.begin(9600); // initialise serial comms
Serial.println("Enter Volts: 0 to 5");
}

void loop()
{
if (Serial.available() > 0) // if a value is waiting in the serial comms buffer
{
char ch = Serial.read(); // read character
int volts = (ch - '0') * 51; // change ASCII value to decimal and scale to 0-255
analogWrite(outputPin, volts); // output PWM signal
}
}

Figure 14: Program to demonstrate PWM output, input value supplied via serial communications.

Table 1: 7-bit ASCII table, reproduced from


https://bournetocode.com/projects/GCSE_Computing_Fundamentals/pages/3-3-5-ascii.html.

John Hedley and Paul Watson, School of Engineering, 2024. Page 16


MEC8063 Introduction to Mechatronics Design
3. Practical exercises

Now that you have covered a basic introduction to programming a simulated Arduino, you will now investigate
some of the basic functionality of an actual Arduino Uno. For this you will need to collect:

• Arduino Uno
• Connection lead (specifically USB A to USB B)
• Jumper wires

3.1. Software installation

The Arduino software will be already installed on the university PCs however you can follow these instructions in
you wish to install in on a personal computer, the software is free.

Go to the Arduino web-site (http://arduino.cc/en/main/software) and follow the instructions to download and
install the Arduino IDE (Integrated Development Environment). The software version required is currently Arduino
2.2.1 (at the time of these notes: September 2023) and can be downloaded for Windows, Linux or Mac. Once you
have successfully installed the Arduino software and USB drivers, you should be able to upload a program to the
Arduino board.

3.2. Uploading your first program

Although your program code will be exactly the same as Tinkercad, the process for uploading it onto the Arduino
is slightly different.

When you start the Arduino software application on your computer, it opens with an empty sketch (i.e. program)
with only setup() and loop() functions. The application comes with a wide range of useful examples already pre-
installed. So from the File menu, open the Blink example as shown in Figure 5.

Figure 5: The Blink sketch

You now need to transfer the sketch to your Arduino board. So plug your Arduino board into your computer using
the USB lead (you will need a type A to type B USB lead as shown in figure 6). You should see the green “On” LED
on the Arduino light up.

John Hedley and Paul Watson, School of Engineering, 2024. Page 17


MEC8063 Introduction to Mechatronics Design

Figure 6: Arduino USB Cable

Before you can upload a sketch, you must tell the Arduino application what type of Arduino board you are using
and which serial port you are connected to. Figures 7 and 8 show you how to do this from the Tools menu.

Figure 7: Selecting the Arduino board type

Figure 8: Selecting the serial port (this can differ from the COM6 port numbers shown and depends on what else
is plugged into the computer).

John Hedley and Paul Watson, School of Engineering, 2024. Page 18


MEC8063 Introduction to Mechatronics Design
On a Windows machine, the serial port is assigned an available COM number. If the port is not shown then the
user must ensure that the USB device driver has been installed correctly and that the Arduino port appears in the
Windows ‘Device Manager’ Ports (COM & LPT) section.

Now click on the Upload icon in the toolbar, a short pause occurs while the sketch is compiled and then the
transfer begins. If it is working, then there will be fast blinking of LEDs as the sketch is transferred, after which you
should see the message “Done Uploading” at the bottom of the Arduino application window.

Once uploaded, the board automatically starts running the sketch and you will see the built in yellow LED labelled
L on the Arduino start to blink. Your environment is all set up and ready to go. If this did not work, then check
your serial and board type settings.

Take a moment to investigate all the available menu options and the selection of example sketches that can be
very useful in learning about the Arduino capabilities.

3.3. Serial monitor

The serial monitor is part of the Arduino IDE (Integrated Development Environment) and you access it by clicking

the top right icon in the toolbar: . Its purpose is to act as a communication channel between
your computer and the Arduino. You can type a message in the text entry area at the top and when you press
enter on the keyboard, it will send that message to the Arduino. Alternatively you can send information from the
Arduino to the serial monitor to print out variables and arithmetic, enabling you to check the operation or debug
your sketch code. Try the Blink program in figure 9 to check your serial monitor is working.

// Blink 2
// --- put your name and date here ---

// Define variables
int ledPin = 13;
int delayPeriod = 1000;

void setup()
{
pinMode(ledPin, OUTPUT); // Initialise output pin
Serial.begin(9600); // Initialise serial communications with baudrate 9600
}

void loop()
{
digitalWrite(ledPin, HIGH); // turn the LED on
delay(delayPeriod); // wait
digitalWrite(ledPin, LOW); // turn the LED off
delay(delayPeriod); // wait

Serial.print("Delay = "); // serial print info to user


Serial.println(delayPeriod); // println gives a linefeed after this print

delayPeriod = delayPeriod + 100; // increase the delay


}

Figure 9: A Blink program with serial communications.

John Hedley and Paul Watson, School of Engineering, 2024. Page 19


MEC8063 Introduction to Mechatronics Design

At the bottom of the Serial Monitor there are several selection boxes. Change the baud 19200 and see what
happens. You should see a random set of characters printed. This is because you have not matched the baud rate
of the PC to the baud rate in your Arduino program of 9600. Change this back to 9600 and it should again work
correctly.

To restart the program without having to load it back in either disconnect the USB cable (which will power down
the Arduino) and then reconnect or, more conveniently, press the small red RESET button that is next to the USB
cable connector. The program will automatically restart. The ‘Delay =’ displayed on the serial monitor should start
again at 1000.

3.4. Analogue input

To try an analogue input, connect up the circuit shown in figure 10 and from the File menu, open the
ReadAnalogVoltage example as shown in figure 11. Check that the value displayed on the Serial Monitor is what is
expected. Try changing the wire connection to the 3.3V or GND pin, does the reading reflect this change?

Figure 10: A simple analogue read example.

Figure 11: Read analogue voltage example

John Hedley and Paul Watson, School of Engineering, 2024. Page 20


MEC8063 Introduction to Mechatronics Design
3.5. Analogue output

The digital voltmeter (DVM) has 2 connectors attached as shown in figure 11. Collect a DVM and connect the
Input VΩ (i.e. this connection will measure either voltage or resistance) to the +5V connection of the Arduino
(make sure you have an electrical contact either by using a piece of wire from the connector or contacting the pin
directly) and connect the COM input of the DVM to the GND of the Arduino. You should get a value of 5V (or
thereabouts) being shown. What happens if you switch these connections around?

Figure 11: Measuring voltage levels on an Arduino using a handheld DVM. You must be sure that it is set to the
required measurement needed (for example voltage, resistance, etc).

To test an analogue output of the Arduino, connect up the circuit shown in figure 12 (using only the DVM, we will
use the oscilloscope in later sessions) and program the Arduino using the code shown in figure 13. Once the
program is running use the Serial Monitor to send values – enter a number 0 to 5 and click the send button. The
Arduino should output the value you sent and the DVM will show this value. However you will notice that the
output is not what is expected, it is always the same value regardless of input (around 2.1V). On the serial
monitor you will see the following printed if you enter the number 5:

5 255

-1938

Figure 12: Example of an analogue output.

John Hedley and Paul Watson, School of Engineering, 2024. Page 21


MEC8063 Introduction to Mechatronics Design

// PWM

int outputPin = 3; // output pin for PWM signal

void setup()
{
pinMode(outputPin, OUTPUT);
Serial.begin(9600); // initialise serial comms
Serial.println("Enter Volts: 0 to 5");
}

void loop()
{
if (Serial.available() > 0) // if a value is waiting in the serial comms buffer
{
char ch = Serial.read(); // read character
int convert = (ch - '0') * 51; // change ASCII value to decimal and scale to 0-255
byte volts = convert;
analogWrite(outputPin, volts); // output PWM signal

// Print values for diagnostics purposes


Serial.print(ch);
Serial.print(" ");
Serial.print(convert);
Serial.print(" ");
Serial.println(volts);
}
}

Figure 13: Program to demonstrate PWM output, input value supplied via serial communications from the PC to
Arduino and then printed back to the PC.

What is actually happening is rather than just sending the number 5 you are sending 2 characters. If you look at
the Serial Monitor, next to the baud setting you will see Newline (which is the default setting for the Serial
Monitor). So when you send it a 5 you are actually sending 5 Linefeed. If you look at an ASCII table (we’ll cover
this in more detail in Tutorial_6_Comms) then:

ASCII 5 = 53 so (53 – 48) x 51 = 255

ASCII LF = 10 so (10 – 48) x 51 = -1938

Thus our output is briefly 255 (i.e. 5V) and then it is set to a value of -1938 (as only values in the range 0 to 255
are allowed then -1938 will be interpreted as -1938+256+256+…etc = 110 corresponding to 2.1V).

There is a very easy fix for this, change Newline in the Serial Monitor to No line ending and the program should
work as expected. This exercise does highlight some subtle effects when trying to do this work practically and it is
not something that is easy to teach, it comes with experience thus with doing the practical work, there is a lot
extra to be learnt.

3.6. Exercise (note this may form part of the assignment so take a copy of the screenshot)

When running the program in figure 13 try entering the character which is the first letter of your name (be sure to
have No line ending selected). Take a screenshot of the screen showing what the output is over the serial monitor

John Hedley and Paul Watson, School of Engineering, 2024. Page 22


MEC8063 Introduction to Mechatronics Design
(remember to show a list of all people in the group on the screen also). Can you explain why it is this value being
shown? Each group member should do this for their name.

4. Summary

This concludes a brief introduction to the Arduino. As you progress through the tutorials, you will learn more of
the functionality of the Arduino. If you have used any equipment, please return this in the condition you collected
it.

If you wish to learn more about Ardunio programming the best way is to experiment and try out your own
projects. There are also many links and videos covering the Arduino on the Internet such as the ‘Open Source
Hardware Group’ http://opensourcehardwaregroup.com/. Of course you are also welcome to ask us for help
(even if it is outside of the module content). Remember the best way to learn is trial and error. There are lots of
examples available on the web but try to understand the code rather than just use the program – there are no
guarantees that the example programs you find are correct and no doubt you will need to modify them for your
own needs.

You can also make a start on the demo exam questions (your final exam will be composed of a selection of these).
You may find the ones for this tutorial particular difficult as you will still be learning about the Arduino over the
coming weeks but these Arduino questions will appear easier as you progress through the material.

John Hedley and Paul Watson, School of Engineering, 2024. Page 23


MEC8063 Introduction to Mechatronics Design
Appendix 1: Coding solutions

A1.1. Program with function to return sum of the squares.

void setup()
{
// Open serial comms
Serial.begin(9600);
}

void loop()
{
// Declare local variables
int a = 3;
int b = 4;
int c;

// Call function
c = myFunction(a, b);

// Print answer
Serial.println(c);
delay(500);
}

int myFunction(int x, int y)


{
int answer;

answer = x*x + y*y;


return answer;
}

John Hedley and Paul Watson, School of Engineering, 2024. Page 24


MEC8063 Introduction to Mechatronics Design
A1.2. Program to highlight numbers divisible by 3.

void setup()
{
Serial.begin(9600); // open the serial comms channel
}

void loop()
{
for(int i=0; i<=10; i++) // loop from 0 to 10 inclusive
{
if(i%3==0) // is it divisible by 3?
{
Serial.print(i);
Serial.println(" is divisible by 3");
}
else
{
Serial.print(i);
Serial.println(" is not divisible by 3");
}
delay(500); // Give the user time to see the answer
}
}

John Hedley and Paul Watson, School of Engineering, 2024. Page 25


MEC8063 Introduction to Mechatronics Design
A1.3. Program to calculate prime numbers.

void setup()
{
Serial.begin(9600); // open the serial comms channel
}

void loop()
{
int i=2;
while(i<100)
{
bool isPrime = checkIfPrime(i); // data type boolean, either 1 (true) or 0 (false)
if(isPrime)
{
Serial.print(i);
Serial.println(" is prime");
}
i++; // same as i=i+1;
}
}

bool checkIfPrime(int x)
{
bool flag=1; // assume it is prime
for(int count=2; count<x; count++)
if(x%count==0) // if found to be divisible then not prime
flag=0;
return flag;
}

A quicker method is to print 2 as a prime number and then edit your program to only check odd numbers, this will
double the speed of your program. You only actually need to check a number by seeing if it is divisible by any
primes smaller than it (and exit the loop once it is found to be non-prime) but for this you would have to save a
list of primes as you find them so the program is getting more complicated (and only worth doing if you are
talking about really large numbers).

John Hedley and Paul Watson, School of Engineering, 2024. Page 26

You might also like