1 of 44

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

UCLA Physics Department

University of California, Los Angeles

Department of Physics and Astronomy

Physics 4AL

2 of 44

JupyterLab Repository Updated

Log in link:

https://physhub.oarc.ucla.edu/hub/login?next=%2Fhub%2F

Physics 4AL:

https://physhub.oarc.ucla.edu/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fuclaphysics4labs%2FPhysics_4AL_2023-24&urlpath=lab%2Ftree%2FPhysics_4AL_2023-24%2F

Please note that material pulled from this link will be periodically updated as the course is changing throughout the quarter.

UCLA Physics Department

3 of 44

Outline of Lab 1C

  • 1C In-Lab
    • Intro to ESP32 code
    • LED Blinking using ESP32
    • 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

4 of 44

Introduction to ESP32 code

UCLA Physics Department

5 of 44

ESP32 Input/Output

5

Component List

6 of 44

Component List

6

Component List

7 of 44

Component List

7

8 of 44

Downloads and references

  • Arduino IDE download (Download 1.8.x version)
  • Arduino Reference
    • https://www.arduino.cc/reference/en/
    • Contains all the references for functions and variables

For Mac users, Please download Xcode to compile the ESP code

UCLA Physics Department

9 of 44

Library Install

10 of 44

ESP32 Connection

UCLA Physics Department

11 of 44

Code basics

  • Programming the Arduino/ESP32
    • Write a list of commands in a file
    • Upload them into the ESP32
    • ESP32 reads, executes the commands

UCLA Physics Department

12 of 44

Code basics - void setup()

UCLA Physics Department

UCLA Physics Department

  • Begin with

void setup() {

Commands here

}

    • These are the commands that the ESP32 will run first.
    • Include the list of the commands

13 of 44

Code basics - void loop()

UCLA Physics Department

  • Loop function

void loop() {

Commands here

}

    • Include after the setup()
    • Runs after the setup()
    • Commands in the body of this function will repeat over and over unless instructed to stop.

14 of 44

Code Basics - Variables

  • Declare variables
    • Before the code
    • 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

15 of 44

Code Basics - Variable types

  • Structure
    • [type of variable] [name of variable] = [value];
    • int ledPin = 2;
  • All variable declarations need to end with a semicolon.
    • int
      • stands for an integer (a number with no decimals)
      • example: 20
    • float :
      • stands for a floating point number. Example: 20.40

UCLA Physics Department

16 of 44

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).

17 of 44

Using the ESP32 to Create a Blinking LED

UCLA Physics Department

18 of 44

Example code - Comments

  • Comments begin with //.
  • For the human reader to understand the code
  • When the code is compiled, these comments are not read by the computer.

  • The code is provided in .txt format. Please copy it to the Arduino IDE and save it to your computer.

UCLA Physics Department

19 of 44

Example code - Upload

  • Write the code
  • Click checkmark : compile the code.
    • Checks the code to make sure it’s ready to run on the ESP32
    • Tells you if you have any errors
  • Click the right arrow : upload to the board

UCLA Physics Department

20 of 44

LED operation

  • Disconnect your ESP32 from your laptop.
  • Connect pin 2 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 ESP32 to your laptop again.

21 of 44

Upload Process

22 of 44

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

22

23 of 44

External LED Blink

  • Type the code provided on the right into the arduino IDE.

  • Begin by declaring variables.
  • Void setup()
    • The LED pin is set to OUTPUT
    • OUTPUT - we can control it
  • Void loop() - What does the code do?
    • The LED : turned ON for 1 second and then turned OFF for 1 second.
    • This runs continuously until the arduino is disconnected from power.

23

24 of 44

TA Checkpoint 1 - External LED Blink

  • Plug in the arduino to your computer
  • Select the correct port in the IDE (in “tools”)
  • Compile and upload your code.

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

24

25 of 44

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

26 of 44

LED Brightness Changing

  • This code includes an if statement
  • Structure: if (condition) { commands }

if (brightness <= 0 || brightness >= 255) {

fadeAmount = -fadeAmount;

}

  • What does the code do?
  • If the condition is not met, then the code will keep running, skipping the commands.
  • 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 (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

27 of 44

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.

28 of 44

Connecting the Ultrasonic Sensor

UCLA Physics Department

28

29 of 44

HC-SR04 Ultrasonic Sensor

29

30 of 44

Working Principle

 

30

31 of 44

Using the Ultrasonic Sensor

UCLA Physics Department

31

32 of 44

Wiring Diagram

32

Trig 2

Echo 4

33 of 44

Accessing Serial Monitor

3 ways to access, keyboard shortcut (Ctrl+Shift+M), clicking it on the tools menu, clicking the magnifying glass

34 of 44

Code Overview

Please refer to 1A slides for the IDE setup.

34

35 of 44

ESP32 Connection (Windows)

35

Check if the computer can find the device. It should download CH340 automatically once connected. If not, follow further instructions.

You can also go to the start menu and type “Device Manager”

36 of 44

IDE Environment Configuration

36

If everything’s right !

Make sure to select this board for the rest of the section

37 of 44

Serial Class

  • In setup run Serial.begin(115200)
    • This allows for serial communication
    • 115200 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
  • ESP32 has a Serial Monitor to show text and numbers and Serial Plotter to plot data

37

Code for Download

.TXT for Download

38 of 44

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 lengths. Use a ruler to make each distance measurement and note it.
  • 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.

38

39 of 44

The Speed of Sound

UCLA Physics Department

39

40 of 44

TA Checkpoint 3 - Plotting with Error Bars

  • Upload the text files you saved from the serial monitor to the same directory as the lab 1C notebook.

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

40

41 of 44

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

41

42 of 44

TA Checkpoint 4 - The Speed of Sound

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

42

43 of 44

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?
  • Are the pins really connected or could they be loose?

This slide will be useful throughout the quarter.

UCLA Physics Department

44 of 44

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.
  • Find the slope of the best-fit line and the speed of sound you obtained from this slope. Include units in your response.
  • Your completed speed of sound plot from your notebook (including best-fit line) and add it to your post-lab.
  • Please complete the post lab assignment found in your JupyterHub Repo.
    • Physics_4AL_2023-24/Assignments/Post-Labs/Post-Lab-Week-2.ipynb