Context and Preparation
Getting started with tinkering on Microcontrollers can often be hindered by the need to purchase hardware. In this tutorial, we offer an introduction to Arduino that requires no prior experience and no physical hardware. Instead, we will utilize an Arduino simulator called TinkerCAD. However, for those who do have the hardware, we will provide parallel instructions. TinkerCAD was chosen for its ability to closely mimic working with actual hardware—blinking lights, moving motors, and building circuits with breadboards—making it an excellent free option among various microcontroller simulators available.
- Acquire familiarity with the standard functions and programming syntax of the Arduino language.
- -Engage with various microcontroller accessories to establish a solid groundwork for future tinkering.
List of Hardware (Optional):
For participants intending to utilize hardware during this workshop, provided below is a list of the required items:
- Arduino Uno
- 1 LED
- 1 resistor (anything from 100 to 1k will work)
- 1 10k resistor
- Push button
- Servo motor
- Jumper wires
- DHT11 sensor
Circuit 1: Turning on an LED
An abbreviated introduction to breadboarding:
When working with a breadboard, it is essential to remember a few conventions for establishing electrical connections between components:
- The columns on the sides of the breadboard labeled with a ‘+’ or ‘-’ are interconnected. These columns are known as the power columns. As a result, all the holes in the first column (indicated by an orange line below) are internally connected to each other, and similarly, all the holes in the second column (marked with a blue line) are internally connected.
- a. The power columns are not interconnected, meaning there is no internal electrical connection between a hole in the orange column and a hole in the blue column.
- In the columns labeled a-e and f-j, the holes in each row are linked together. For instance, hole 1c is connected to hole 1e (green circles), and hole 7f is connected to hole 7i (pink circles).
- The separation in the board between columns e and f usually indicates a break in the internal electrical connections. Consequently, a hole in column d of a row won’t be connected to a hole in column h within the same row.
Building the Circuit:
In both TinkerCAD and physical hardware, we will construct the following circuit. This circuit enables us to control the LED’s on and off states through code.
The Arduino Uno is equipped with various pins that serve as physical inputs and outputs with distinct capabilities. These pins include power, analog, digital, pwm, interrupt, I2C, Serial, and SPI pins, as depicted in the commonly referred diagram called the “pin-out.” In this tutorial, we will mainly focus on the Power, Digital, and Analog pins, which are also conveniently labeled on the board in the pin-out.
- To initiate the circuit in TinkerCAD, access the “Circuits” option in the menu on the left side of the Dashboard, and then choose “Create New Circuit.”
2. To incorporate components onto the canvas, simply click on them in the components menu located on the right side. Begin by adding an Arduino Uno and a breadboard to the canvas.
- After placing a component, you can click and drag to select and move it.
- Utilize the mouse scroll wheel to zoom in and out. To pan, hold down the scroll wheel.
Let’s begin by establishing the power/control and ground connections between the Arduino and the breadboard.
- Create a connection between the 5V pin on the Arduino and the + power column on the breadboard.
- Establish a link between the 5V pin on the Arduino and the + power column on the breadboard.
- Hardware: Connect a jumper wire from the 5V pin on the Arduino to the + power column on the breadboard.
- Establish a connection between one of the ground (GND) pins on the Arduino Uno and the – power column on the breadboard.
- In TinkerCAD, brown wires will be utilized for ground (GND) connections to facilitate easy identification.
- For hardware implementation, utilize another jumper wire to create this connection.
Next, we’ll incorporate a 330Ω resistor and an LED into the circuit. The resistor serves the purpose of limiting the current flowing to the LED to prevent it from burning out. The greater the resistance of the resistor, the less current will flow to the LED, making it appear dimmer.
- Place the 330Ω resistor and LED on the canvas.
- In TinkerCAD, after adding the resistor to the canvas, you will have the option to modify its value. Observe that the stripes on the resistor change color to simulate the appearance of a physical resistor with that particular value.
- Establish an electrical connection between the resistor and the breadboard by connecting one end of the resistor to a hole in the a-e columns of the breadboard. The other end of the resistor should be linked to the + power column. This connection effectively links the 5V pin on our Arduino to the resistor.
- In TinkerCAD, utilize wires to create the connections. A helpful approach is to position the resistor beside the breadboard, draw the connections, and then relocate the resistor onto the breadboard to clearly visualize the connections being made. The wires will move along with the resistor when you move it.
- For hardware setup, insert one leg of the resistor into the + power column and the other leg into the middle of the breadboard.
LEDs are polarized components, meaning they only function in one specific direction, while resistors are non-polarized. In a circuit, the current flows in the direction indicated by the LED/diode symbol’s arrow, which means it goes in through the anode (+) and out through the cathode (-). LEDs denote the anode and cathode in several ways:
- The legs of the LED are of two different lengths, with the longer leg being the anode.
- One side of the “light bulb” portion of the LED has a flat surface, which may be difficult to see but can be felt. This flat side indicates the cathode side.
- To remember the correct orientation of the LED in the circuit, visualize the LED symbol resembling a funnel shape.
While using TinkerCAD, hovering over one of the legs of the LED will indicate whether it’s the anode or the cathode. To rotate components in TinkerCAD, simply select the component and click the rotate button located in the upper left corner.
- Link the anode of the LED to the same row of the breadboard as the resistor, and connect the cathode to any other row. This will establish a connection between the resistor and the LED.
- Finalize the circuit by connecting the cathode of the LED to the – power column.
- Test your circuit by checking if the LED turns on. If the wiring is correct, the LED should illuminate.
- In TinkerCAD, click on “Start Simulation” located in the upper right corner to initiate the simulation. This will activate the USB connection and power the circuit.
- For hardware testing, connect the USB cable to the Arduino and your computer. If the Arduino is receiving power from your computer, the Arduino power light will turn off.
Circuit 2: Blinking LEDMoving forward, we will modify the previous circuit to program the LED to blink.
Setup the Circuit:
- Adjust the connection from the 5V pin on the Arduino to digital pin 13 (D13).
Write the Code:We recommend writing the code in the Arduino IDE and then copying it into TinkerCAD. This is because TinkerCAD automatically generates a significant portion of the code for you, which undermines the purpose of this tutorial.
- Launch the Arduino IDE and begin a new sketch by selecting “File” and then “New.”
Within the Arduino IDE and language (also known as Arduino language), programs are referred to as sketches. In a sketch, two main components/functions are present:
- The “void setup()” function is where we establish the groundwork of the code by informing the IDE about the purpose of each pin we are utilizing. This function runs only once when the code is uploaded to the physical (or virtual) Arduino.
- The “void loop()” function serves as the main body of the code. Here, we instruct the pins on what actions we want them to perform to control the connected accessories, such as the LED. This portion of the code will continuously run in a loop until either the power is removed from the Arduino or the code is altered.
In Arduino, comments are indicated by using double slashes “//”.
- Choose the Arduino Uno as your board in the “Tools” menu located at the top of the IDE. This selection informs the IDE about the pin assignments for proper identification.
- If you are working with hardware, ensure your Arduino is connected (the power light on the board should be illuminated) and verify the correct Port through the “Tools” menu. Selecting the proper COM port is essential, as without it, your computer won’t be able to upload code onto the Arduino.
The Arduino language bears similarities to C and encompasses numerous built-in functions that we will be using in our projects. Below, you can find the definitions of some of these built-in functions, denoted by blue text with capitalized function names.
– Pin: this is the arduino pin you are referencing
– Type: INPUT, OUTPUT, INPUT_PULLUP
– INPUT_PULLUP: pin is an input but will be pulled high by default
– Example: pinMode(LED_BUILTIN, OUTPUT);
– Pin: pin you want to control
– Level: HIGH or LOW
– Pay attention to the device you are controlling. If it is active low it will be on when
the pin is set LOW
– Example: digitalWrite(13,LOW);
– Pin: the pin whose value you want to determine
– Often used in if statements to see if a pin meets certain conditions
– Example: digitalRead(2);
– Pin: pin you want to control
– Value: between 0 and 255. The value varies the duty cycle of the PWM signal being
written to a pin
– Example: analogWrite(A0, 27);
– Pin: the pin whose value you want to determine
– Example: analogRead(A2);
– x: millisecond value that determines the duration of the delay. The next command won’t
be executed until the delay is complete.
– Example: delay(200);
Serial.print(val) or Serial.print(val, format)
Serial.print(78) gives “78”
Serial.print(1.23456) gives “1.23”
Serial.print(‘N’) gives “N”
Serial.print(“Hello world.”) gives “Hello world.”
Serial.print(78, BIN) gives “1001110”
Serial.print(78, OCT) gives “116”
Serial.print(78, DEC) gives “78”
Serial.print(78, HEX) gives “4E”
– Make sure you’re including semi-colons. Every code line you add needs to end with a
– Watch your capitalization
– Make sure you’re referencing the correct pin
- In the setup function, configure digital pin 13 as an OUTPUT pin using the pinMode() function. Attempt to accomplish this without referring to the answer shown in the Figure below.
To achieve the blinking effect of the LED, we must control its on and off states through pin 13. Since the code inside the loop() function repeats rapidly, we introduce a delay between turning the LED on and off and turning it back on again. This delay allows us to visually perceive the blinking action of the LED.
- Compose the code within the loop function to create the blinking effect of the LED using the digitalWrite() and delay() functions. Initiate the blinking with a delay of 500 milliseconds.
- Click on “Verify” (checkmark icon in the upper left-hand corner) to save and compile your code. If there are any errors, such as a missing semicolon, the IDE will display an error printout in the bottom message section.
- Once your code successfully compiles, proceed to upload it to the Arduino.
- In TinkerCAD, click on the Code button located in the upper right corner and switch from “Blocks” to “Text.” Copy your code from the Arduino IDE and paste it into the TinkerCAD code window. Then, click on “Start Simulation” to execute your code.
- For hardware usage, connect your Arduino to the computer and click on the Upload button, located adjacent to the Verify button. Clicking the Upload button will compile and then upload the code, eliminating the need to verify before every upload.
- Ensure that your hardware behaves as expected. The LED should turn on and off repeatedly.
- Next, experiment with the delays and observe the effect on your simulation or hardware. Determine the smallest delay you can use while still being able to distinguish that the LED is turning on and off.
Rather than using default pin names, we can employ variables to make pin usage more intuitive. This becomes particularly beneficial when dealing with numerous pins, as it aids in keeping track of the specific functions of each pin in your code.
- Introduce a variable named “LED” to represent digital pin 13. Place this code above the setup() function, using the syntax “int LED = 13;”. In TinkerCAD, you’ll need to halt the simulation before modifying the code.
- Replace all instances of “13” with “LED” in your code. You can perform this modification either in the TinkerCAD code window or the Arduino IDE, as this is your custom code.
- Upload the modified code and verify that your hardware behaves as anticipated in response to the changes.
Circuit 3: Push Button with LED
In the next step, we will integrate a push button into our circuit. When the button is pressed, the LED will turn on. This process entails expanding our previous breadboarding setup and incorporating control structures in our code.
Build the Circuit:
1. Keep your blinking LED circuit unchanged. If you’re using hardware, disconnect it before constructing the pushbutton part of the circuit, as it’s not advisable to work with live hardware. In TinkerCAD, you can simply stop the simulation by closing the code window with the Code button.
2. Integrate a pushbutton into the circuit, positioning it across the break in the breadboard for easier placement.
1. Establish a connection between the bottom left pin of the push button and digital pin 8 on the Arduino, using a red wire in TinkerCAD. Additionally, connect the bottom right pin of the push button to the – power column on the breadboard using a brown wire in TinkerCAD.
Write the Code:
As we are utilizing digital pin 8 to control the button, we must define a variable for the button and declare its pin type within the setup() function. You can modify the code you previously wrote for the Blinking LED circuit or begin a new sketch to incorporate these changes.
- Introduce a variable named “Button” and assign it the value of digital pin 8. Additionally, retain the variable named “LED” that is already set to digital pin 13.
- Within the setup() function, configure the LED pin as an OUTPUT and set the Button pin as “INPUT_PULLUP.” Since push buttons are active low devices (i.e., they are considered “on” when given a LOW signal), using INPUT_PULLUP ensures that the pin remains HIGH by default, keeping the button off by default
Control structures enable the code to take different paths or repeat based on specific conditions. Some examples of control structures include if/elseif/else statements, do/while loops, and for loops.
In if/elseif/else statements, conditions are utilized to determine the code’s behavior. If a condition is met, the code under that specific condition is executed.
Then do this code
Then do this code
Do this code
Conditions in control structures typically involve equalities or inequalities and can utilize digitalRead or analogRead to access the value of a pin.
– Example: if(digitalRead(8)==LOW)
– Example: elseif(x<12)
– Example: if(analogRead(A2)>12)
For a do/while statement, we tell the code to run over and over again until a condition is met.
A for loop is a control structure that allows for iteration, such as incemenenting to look through a
data set or increasing speed one notch at a time.
for (initialization; condition; increment)
The initialization should include the data type (e.g., int i=0; i<5; i++)
- Within the loop() function, implement an if/else statement to check if the button is pushed (digitalRead(Button) == LOW). If the button is pushed, turn the LED on using digitalWrite; otherwise, turn the LED off.
- Upload your code and perform the test.
a. In TinkerCAD, click on the push button to press it. You can hold down your left mouse button on the push button to keep it pressed.
Circuit 4: Servo Motor
Now, we’ll shift our focus to working with servos. This circuit doesn’t require a breadboard, so you can either create a new circuit in TinkerCAD or disconnect your Arduino from the breadboard. In TinkerCAD, you can remove a wire or component by selecting it and pressing the delete key on your keyboard.
Servos are rotary actuators that offer position control. Using code, you can set their angle within the range of 0° to 180°. It’s important to note that servos are not designed for continuous rotation.
Building the Circuit
- Connect the Arduino to the servo.
a. In TinkerCAD, we’ll utilize the micro servo available in the components window.
b. Follow these wire designations/connections:
i. Brown wire: Ground ii. Red wire: 5V iii. Orange wire: Signal – connect this wire to a pulse width modulation (PWM) pin on the Arduino, marked with a ‘~’. In this case, connect it to digital pin 11.
Note: On some servos, the signal line may be white instead of orange.
Write the Code
For our code, we will utilize the servo library included in Arduino. This library offers specialized functions that make it easy to control the servo with precision.
- Begin a new sketch in Arduino
- Incorporate the servo library using the following syntax: “#include <Servo.h>”.
- a. Place this statement at the top of the code, before the setup() function.
- Generate a servo object within your code. This object allows us to manipulate its properties to set and read angles. The syntax is “Servo myservo;” and it should be placed below the inclusion of the servo library. You can choose any variable name you prefer for the servo object, such as “myservo” or any other name of your choice.
- In the setup function, we’ll attach the servo to a PWM pin instead of using pinMode. Utilize the following syntax: “myservo.attach(11);”
- Within the loop function, set the position of the servo to 0° as the starting point. Use the syntax:”myservo.write(0);” This action will also reset the servo to the 0° position at the beginning of each execution of the loop function.
- Employ a for loop to increment the angles of the servo from 0° to 180° in 5-degree increments.
a. For loop initialization: “int i = 0;”
b. For loop condition: “i <= 180;”
c. For loop increment: “i += 5;”
d. For loop body: “myservo.write(i); delay(500);”
i. The delay is introduced to allow observation of the increments in angle.
- Upload the code and observe if the servo moves as expected.
Next, we’ll enhance the code to include additional lines so that the position of the servo can be displayed on the serial monitor.
- Introduce a global variable of type int named “servo_position.”a. Note: Similar to when we created variables for the pins (LED and Button) previously, this new variable will also be a global variable placed in the same location.
- Inside the setup function, include the line “Serial.begin(9600);” This enables the usage of the serial port, allowing communication with external devices. The baud rate is set to 9600, which determines the rate of information transfer on the communication channel. A baud rate of 9600 signifies a maximum transfer rate of 9600 bits per second.
- Inside the for loop, set the “servo_position” variable to the value of “myservo.read()”. Place this line below the delay statement.
- Utilize Serial.print to display the value of “servo_position” in the serial monitor. Refer to the examples in the Function definitions provided earlier.
- Using “Serial.print(servo_position);” will display the positions sequentially in the serial monitor, similar to words on a page. If you want each position to be printed on a new line, you should include a second print command: “Serial.print(“\n”);”.
- Upload the code and examine the output in the serial monitor.
- In TinkerCAD, you can access the serial monitor button located in the bottom left corner of the code window. Click this button to view the output.
- If you’re working with hardware in the Arduino IDE, you can find the serial monitor under the Tools menu.
Circuit 5: Temperature/Humidity Sensor
The final circuit we’ll be working with involves a temperature/humidity sensor setup. However, TinkerCAD offers limited options for environmental sensors, so we’ll use the TMP36 temperature sensor in TinkerCAD and the DHT11 temperature/humidity sensor for hardware testing.
TMP36 Sensor – TinkerCAD Circuit
The TMP36 sensor will offer an analog output that corresponds to the temperature.
- Create a new TinkerCAD circuit and add an Arduino Uno and a TMP36 sensor to the canvas. Establish the connections between the sensor’s legs and the Arduino pins as follows: connect power to 5V, ground to the ground pin, and Vout to an analog pin – A0.
- Set up the following global variables: a. int sensorPin = A0; b. int reading; c. float voltage; d. float tempC;
- Inside the setup function, utilize Serial.begin(9600) to set the baud rate.
- Within the loop function, assign the value read from pin A0 to the global variable “reading” using analogRead(sensorPin).
- To convert the value in the “reading” variable to a temperature in Celsius, apply the following formula. You can break the formula into multiple lines, introducing intermediate variables like “voltage”:Temp (in °C) = (voltage – 0.5) * 100.0;
Please note that the voltage value should be derived using the formula: voltage = (reading * 5.0) / 1024.0
6. Display the temperature on the serial monitor and incorporate a 0.5-second delay to introduce a pause between sensor readings.
7. Upload the code and observe the values on the Serial monitor.
DHT11 Sensor: Hardware
The DHT11 sensor is available in two common configurations: a 4-pin version as depicted below and a 3-pin version mounted on a small PCB. The PCB-mounted version incorporates a 10kΩ pull-up resistor. When utilizing the 4-pin version, it is necessary to include this resistor in the circuit.
- Position the DHT11 sensor on the breadboard in such a way that each pin is inserted into a separate row.
- Establish a connection between the Vcc and Signal pin rows on the breadboard using the 10kΩ resistor.
- Ensure the following connections are made:1. Connect the VCC sensor pin to the 5V pin on the Arduino.
2. Connect the ground sensor pin to the ground pin on the Arduino.
3. Connect the signal sensor pin to digital pin 7 on the Arduino.
- Begin a new sketch in Arduino. If you don’t have the “dht.h” library installed yet, access the Library Manager by navigating to Tools > Manage Libraries in the top menu. Search for “dht” and proceed to install the DHT sensor library by Adafruit.
After successfully installing the Adafruit DHT library, open the “DHT tester” example sketch provided within the library.
- Modify the example sketch by adjusting the pin assignment and selecting the DHT11 sensor. Declare digital pin 7 as the signal pin for the sensor.
- Upload the code to the Arduino and examine the output on the serial monitor. A simple method to verify if the sensor is responding correctly is by gently blowing air onto the sensor or creating a change in temperature and observing the changes in the displayed readings