1 of 49

Unit 1 - Training�Lab 1C : Introduction to Arduino code and Evaluating Speed of Sound

UCLA Physics Department

University of California, Los Angeles

Department of Physics and Astronomy

Physics 4AL

2 of 49

Outline of Lab 1C

  • 1C In-Lab
    • Intro to Arduino code
    • Led Blinking using Arduino
    • Set up and use the Ultrasonic Sensor to collect data
    • Plot the relationship between sensor output and distance from sensor
    • Find the Speed of Sound

UCLA Physics Department

3 of 49

Introduction to Arduino code

UCLA Physics Department

4 of 49

Arduino Input/Output

Input/output pins

PWM Pins(~): 3, 5, 6, 9, 10, 11

Digital Pins: 2, 4, 7, 8, 12, 13

USB input/output/power

Battery power

Output power + ground

Analog Input

5 of 49

Connecting an Arduino

  • Connect one end of blue cable to Arduino and other end to computer.
  • Check if small lights are turned on.

UCLA Physics Department

5

6 of 49

Downloads and references

  • Arduino IDE download
    • https://www.arduino.cc/en/Main/Software
  • Arduino Reference
    • https://www.arduino.cc/reference/en/
    • Contains all the references for functions and variables

UCLA Physics Department

7 of 49

Arduino Connection

UCLA Physics Department

8 of 49

Code basics

  • We will be writing programs.
    • List of commands that are stored in a file.
  • Those commands are uploaded into the Arduino.
  • The Arduino reads the commands and executes them.

UCLA Physics Department

9 of 49

Code basics - void setup()

UCLA Physics Department

UCLA Physics Department

  • We begin our code with

void setup() {

Commands here

}

  • These are the commands that the Arduino will run first.
  • The list of the commands is the body of the function.

10 of 49

Code basics - void loop()

UCLA Physics Department

  • After the setup function we have a loop function.

void loop() {

Commands here

}

  • This runs after the setup function and the commands in the body of this function will repeat over and over unless instructed to stop.

11 of 49

Code Basics - Variables

  • Before the code we can declare variables.
  • Variables in code work like variables in algebra.
  • Variables are case sensitive and cannot have spaces.
  • The code will then use that variable name in all of the functions.

UCLA Physics Department

12 of 49

Code Basics - Variable types

  • Structure
    • [type of variable] [name of variable] = [value];
    • int ledPin = 13;
  • All variable declarations need to end with a semicolon.
  • Int stands for integer, a number with no decimals while float stands for a floating point number.
    • int: 20
    • float: 20.40

UCLA Physics Department

13 of 49

Code Basics - Digital Input/Output

UCLA Physics Department

  • pinMode(pin,mode);
    • Sets the mode of the pin # to either INPUT or OUTPUT.
    • Is the pin receiving or issuing signals.
  • digitalRead(pin);
    • If pinMode is set to INPUT, the Arduino will tell you if the state of the pin is HIGH or LOW.
  • digitalWrite(pin,value);
    • If pinMode is set to OUTPUT then this can write a value of HIGH(5 V) or LOW(0 V).

14 of 49

Example code - Comments

  • Comments begin with //.
  • These are intended for the human reader to understand what the code does.
  • When the code is compiled, these comments are not read by the computer.

UCLA Physics Department

15 of 49

Example code - Upload

  • After the code is written click checkmark to compile the code. This checks to the code to make sure it’s ready to run on the Arduino and tells you if you have any errors that you need to fix.
  • Click the right arrow to upload the code to the board, telling the Arduino to run the program.

UCLA Physics Department

16 of 49

LED operation

  • Disconnect your Arduino from your laptop.
  • Connect pin 13 to the longer lead of the LED through a 220 ohm resistor.
  • Connect the shorter end of the LED to the GND pin.
  • Connect your Arduino to your laptop again.

17 of 49

Using the Arduino to Create a Blinking LED

UCLA Physics Department

18 of 49

Commands: timing

  • delay(t);
    • Pauses for t # of milliseconds (unsigned long variable type)
  • delayMicroseconds(t);
    • Paused for t# of microseconds (unsigned int variable type)
  • time = micros();
    • Returns the time in microseconds since the program start (unsigned int)
  • time = millis();
    • Returns the time in milliseconds

18

19 of 49

External LED Blink

  • Type the code provided on the right into the arduino IDE.
  • Begin by declaring variables.
  • The LED pin is set to OUTPUT in void setup() allowing us to control it.
  • The LED is turned ON for 1 second and then turned OFF for 1 second. Since this is in void loop(), this runs continuously until the arduino is disconnected from power.

19

20 of 49

TA Checkpoint 1 - External LED Blink

  • The arduino must be plugged in to your computer. Select the correct port in the IDE and compile and upload your code.

  • Complete and show the blinking external LED to your TA.

20

21 of 49

Code basics : Analog Input/Output

UCLA Physics Department

  • analogWrite(pin, value);
    • Can only be used by pins with ‘~’ preceding the pin number.
    • Int value between 0 and 255
  • analogRead(pin);
    • Used for reading analog pin values

22 of 49

LED Brightness Changing

  • This code includes an if statement
  • Structured if (condition) { commands }
  • if (brightness <= 0 || brightness >= 255) {

fadeAmount = -fadeAmount;

}

  • If the condition is not met, then the code will keep running, skipping the commands. This forces the LED brightness to increase if it hits a value of 0 and the LED brightness to decrease if it hits a value of 255 (which is the maximum).

Note: The LED pin is changed to pin number 9. Only the ponds with the squiggly line (~) in front of them are capable of analog control.

You do not have to type in the code, you can download it here

23 of 49

TA Checkpoint 2 - LED Brightness Changing

  • This code includes an if statement
  • if (brightness <= 0 || brightness >= 255)
  • This is the condition the statement will check to see if the brightness is <= to 0 or if the brightness is >= 255
  • The or is indicated by the rails ||
  • Example conditions that can be checked:
    • Variable == value (equal to)
    • Variable >= value (greater than or equal to)
    • Variable < value (less than)
    • Variable != value (not equal to)
  • Show the completed working setup to your TA.

24 of 49

Connecting the Ultrasonic Sensor

UCLA Physics Department

24

25 of 49

HC-SR04 Ultrasonic Sensor

25

26 of 49

Working Principle

 

26

27 of 49

Arduino extension board

Attach Arduino extension board to the Arduino ensuring that corresponding pins match.

27

28 of 49

Arduino extension board

28

29 of 49

Mini breadboard

Pull off the yellow adhesive cover to attach the mini breadboard on the Arduino extension board permanently. However, the circuit on the breadboard can be modified and the extension board can be detached whenever required.

29

30 of 49

Arduino with attached mini breadboard

30

31 of 49

Arduino with attached mini breadboard

The pins on the Arduino extension board correspond to the pins on the Arduino. This setup also has more ground pins and 5V pins.

31

32 of 49

Arduino with attached mini breadboard

Each row with 5 pins are electrically connected. However, the mini breadboard does not have the red and blue rails that were connected to 5V and ground. Instead there are more 5V and ground pins on the extension board.

32

33 of 49

Attach ultrasonic sensor

33

34 of 49

Wiring Diagram

34

35 of 49

Connect ultrasound module

35

36 of 49

Connect Ultrasonic Sensor

36

37 of 49

Using the Ultrasonic Sensor

UCLA Physics Department

37

38 of 49

Serial Class

  • In setup run Serial.begin(9600)
    • This allows for serial communication
    • 9600 is the baud rate for UNO (bits/s)
  • Serial.print(“ “)
    • Prints out to serial
  • Serial.println(“ “)
    • Prints to serial and goes to the next line
  • Arduino has a Serial Monitor to show text and numbers and Serial Plotter to plot data

38

39 of 49

Code - Part 1

  • Variables define the pin numbers for Trig and Echo pins.
  • “numRuns” stands for the number of runs/number of data points collected per reference length.
  • “ii” is a count variable to track the run number

  • trigPin is set as OUTPUT and it emits the square pulse.
  • echoPin is the INPUT and it receives the reflected wave.

39

40 of 49

Code - Part 2

  • The while loop runs if “ii” is less than “numRuns”. “ii” is increased by 1 at for each data point collected as seen later in the code.
  • The first 5 statements inside the while loop waits for 2 microseconds and generates a 10 microsecond square pulse.

40

41 of 49

Code - Part 3

  • “duration” records the time taken in microseconds to receive the reflected sound wave since the generation of the pulse.
  • Delay is 20 ms, so the entire data collection process for each reference length will take a little more than 2 seconds.
  • “ii” is increased by 1 at for each data point.

41

42 of 49

Serial Monitor

Serial Monitor readings.

42

You can download this code here

43 of 49

Reset button

Click reset button on the extension board to collect new data.

43

44 of 49

Ultrasonic Sensor Function

  • Test that your ultrasonic sensor is producing values
  • Test that your ultrasonic sensor values increase as you move it farther away from a reflecting object

  • Collect data points (the code collects 100) for at least 5 reference lengths
  • Copy the data for each of the reference lengths from the serial monitor and paste them into a text file named by the length used
  • You can use Notepad, or an online program, but Google Docs or TextEdit will NOT work
  • Save these files as ‘.txt’ files. You should have one per reference length used (at least 5). Show these files to your TA.

44

45 of 49

The Speed of Sound

UCLA Physics Department

45

46 of 49

TA Checkpoint 3 - Plotting with Error Bars

  • Copy this notebook into your drive. Upload the text files you saved from the serial monitor to the same directory as this notebook.

  • The example is there for you to reference as you complete the notebook
  • Read in your time of flight data for each distance from the files you uploaded
  • Use this data to find the time of flight and uncertainty for each distance
  • Generate an error bar plot of your time-of-flight vs. distance data. Show this plot to your TA.

46

47 of 49

TA Checkpoint 4 - The Speed of Sound

  • Recall from slide 26 that the speed of sound is given by:

  • Complete the ‘Determining the speed of sound’ section of the notebook from TA checkpoint 3. Use the above equation to calculate the speed of sound. Show your completed notebook to your TA.

  • This completed notebook will be required to complete the post-lab for this week

47

48 of 49

Troubleshooting for Problems with Arduino

  • Did you select the right Port on your Arduino IDE?
  • Do you have brackets {} around all of your functions and loops?
  • Are all of your variables defined?
  • Do all of your commands in end a semicolon?
  • Do the conditions on your loops make sense?
  • Is the Arduino plugged into your computer?
  • Are the input, power (5V) and ground (GND) pins plugged in?
  • Do you have complete circuits?

This slide will be useful throughout the quarter.

UCLA Physics Department

49 of 49

Post-Lab Requirements for lab 1C

UCLA Physics Department

  • Ensure that you have run the blink and brightness programs on your Arduino setup. Answer the question about the voltage measurements that you would observe while running these programs.
  • Write the slope of the best-fit line and the speed of sound you obtained from this slope. Include units in your response.
  • Screenshot your completed speed of sound plot from your notebook (including best-fit line) and add it to your post-lab.

Make a copy of this document to submit the post-lab for Week 2.