Day 1
Summary of This Lesson
This week will go over the ultrasonic sensor, how it works, and how to use them. We have used ultrasonic sensors before, and there was some introduction to how it worked in past lessons, but this will go a little bit in more detail. It will also involve looking at the documentation of the ultrasonic sensor. Documentation can really help you out in figuring out how to use a sensor or any electronic component with proper documentation.
Lessons for Electrical Training on the website requires a Tinkercad account at www.Tinkercad.com, so if you haven't already, make an account on that website. Also, you can press the "Try Circuits" button in the circuits tab of Tinkercad to get an introduction of how to use Tinkercad's circuit simulation feature.
The Ultrasonic sensor, how it works
The ultrasonic sensor is a sensor that can be used to detect how far an object in front of it is to itself. It does this by sending out an ultrasonic wave with its receiver which bounces back from an object, then gets received by a receiver on the ultrasonic sensor. The time in between sending and receiving the ultrasonic wave is used to calculate the distance. We will go over how that is done in the code later.
How to use it
There are four pins which you might've seen and used in previous lessons, but let's go over them anyway. The first is GND, which connects to the ground pin of the Arduino or any other controller to provide a reference voltage, which we say is 0V. Next is the Vcc pin which connects to the 5V pin of the Arduino or any other controller, which provides 5V to the ultrasonic sensor. Next is the TRIG pin, and it activates the sending of an ultrasonic wave if that pin receives a 5V signal from an Arduino or other controller. Finally, the ECHO pin will transmit a pulsing 5V signal towards a DIO pin of an Arduino or other controller when the sensor receives a ultrasonic wave.
So we've went over the pins, but how do we use it specifically? This would be a good time to introduce documentation. Here is the documentation for the HC-sr04 ultrasonic sensor: HC-SR04 User Manual.pdf (maine.edu) . We will be using this documentation of that ultrasonic sensor to help us out in finding how to use it.
Using Documentation
The first two pages are too important, it's just introduction and a table of contents. The third page has some general characteristics of this sensor, which is worth looking at for things like operating range in terms of distance and degrees, voltage and current levels, etc. On page five, you will see an angle graph with black highlights. Those highlights tell you that objects in that area will likely be detected by the ultrasonic sensor. Other documentation will have test results of the electrical component the documentation is about, which can be things like current draw, detection of different things in the environment, working conditions in different temperatures, you name it. Below that you will see specifications and limitations. This will help you know how much a sensor or electrical component needs of something, say, voltage or current. You can guess what the first and third section means, but quiescent current is the current that it is at when the sensor isn't doing anything. Think of how quiescent sounds like quiet. The ultrasonic frequency is how fast it cycles between a high and low signal when sending out an ultrasonic wave. This is done internally as we'll see later.
Now, the important part, the next page, which is page 7. If you read the short paragraph, it will tell you that it needs a high signal (5 volts) for 10us, which is 10 microseconds. This will allow the ultrasonic sensor to send out an ultrasonic wave, which it says it will do 8 times in a quick burst at a frequency of 40 kHz, meaning every cycle lasts for 1/40000 of a second, so very fast. To clarify, one cycle in this context means that the ultrasonic sensor sends out an ultrasonic wave, then stops which it does in 1/40000 of a second. Put 8 of these together and that is what the ultrasonic sensor does when it is triggered to do so. Next describes what happens when the ultrasonic sensor receives an ultrasonic wave. Once it receives the ultrasonic wave, the ECHO pin goes high, or 5V, for the same amount of time it took for the ultrasonic wave to have a roundtrip from the sensor, to the target, and back again. We can use the time it was high for provided by the ECHO pin to calculate the distance. In the document, we can use this formula for centimeters: time (length of time ECHO was high for in microseconds)/58 = distance in centimeters. Now this comes from this: (time in microseconds*0.0343 centimeters per microsecond)/2, which simplifies to time/58, since time*0.0343/2 is the same as time/(2/0.0343) or time/58.
The rest of the document is just different example code and hardware, which we don't need to see.
Let's actually use this
Get into Tinkercad so we can start tinkering. Get the Arduino out and the ultrasonic sensor out, and why not, let's get a LED out as well. Use the documentation to connect the Vcc pin and GND pin to the power pins on the Arduino correctly. Since the code I will give you is specific in terms of DIO pins, you will use DIO pin 5 for the TRIG pin, and DIO pin 4 for the ECHO pin. For the LED, use DIO pin 13 for it and don't forget the current limiting resistor to prevent it from blowing up. Once you get that setup, copy and paste the code below into that Arduino by clicking on it, pressing the "code button", pressing the drop down menu that says "blocks" then choosing "text", then replace the text to the right with the code you've copied. Here's the code:
const int ECHO = 4;
const int TRIG = 5;
const int LED = 13;
int TimeToTarget = 0;
int DistanceToTarget = 0;
void setup()
{
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(LED, OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
TimeToTarget = (pulseIn(ECHO, HIGH)); //Time to target and back in microseconds
DistanceToTarget = (TimeToTarget/2*0.0343); //Distance to target
Serial.println(DistanceToTarget);
if (DistanceToTarget > 100){
digitalWrite(LED, LOW);
}
if (DistanceToTarget <= 100){
digitalWrite(LED, HIGH);
}
delay(100);
}
How Hardware works with Software
The first 3 lines of code assign a number, which are the DIO pins, to a variable, the DIO pins being one for the LED, ECHO, and TRIG. We are just naming numbers so that it can be put into context. The next two are just variables used to "hold onto" the information about the time to target, or the distance to the target. In the void setup area, we are just setting up the modes of the pins for the LED, TRIG, and ECHO. If you look at the void loop area, you will see "digitalWrite(TRIG, LOW);" with "delayMicroseconds(2);" after that. This just makes sure the TRIG pin is off. Then, we have "digitalWrite(TRIG, HIGH);" with "delayMicroseconds(10);" and "digitalWrite(TRIG, LOW);" after that. This will have the TRIG pin go to 5V for 10 microseconds then turns to 0V after, which is what is needed to have a proper sending of ultrasonic waves according to this sensor's documentation. Now, we see "TimeToTarget = (pulseIn(ECHO, HIGH));" which you can look inside to see "pulseIn". This measures the time the ECHO pin was high for, or how long it was at 5V for. The next line, "DistanceToTarget = (TimeToTarget/2*0.0343);" gets us the distance to the target by taking the time ECHO was high for in microseconds, dividing it by two to get the time to the target and not the round trip, then using that to multiply by 0.0343, which is the speed of sound in centimeters per microsecond. The rest of the code just uses that calculation to turn on the LED off when the distance is > 100, and on when the distance is < or = 100.
Using the Oscilloscope
You can take an oscilloscope out and probe the voltages between the ECHO pin and the GND pin of the ultrasonic sensor by connecting the negative black wire of the oscilloscope to GND, and the positive red wire to ECHO. If you change the time per division of the oscilloscope by clicking on it and changing the time per division category to 10 ms instead of 100 ms, you will zoom into one ECHO pulse signal. Click on the ultrasonic sensor and move the circle that pops up around. You will see the length of time of the pulse from the ECHO pin get longer or shorter as the distances get longer or shorter respectively. Here are two pictures below depicting that.
The left picture shows an object that is pretty close, resulting in a shorter length for the pulse, whereas the right picture shows an object pretty far away, resulting in a longer length for the pulse. This length of time of the pulse from the ECHO pin is what we used in the mini project above to get the distance.
That's Basically it!
The in-person people will get to play around with their ultrasonic sensor and be able to use it with other components. You can try to play around with it, but since I cannot make custom code for you, you are limited to the code that is there. You can also try to learn the basics of Arduino code, which is a simplified version of C++, a coding language.
Day 2
Summary of This Lesson
This lesson will go over and introduce rotary and quadrature encoders, how they work, different types of encoders, and how to use them. This is another kind of sensor that is used with motors to measure how fast the motor is rotating, as well as direction.
Lessons for Electrical Training on the website requires a Tinkercad account at www.Tinkercad.com, so if you haven't already, make an account on that website. Also, you can press the "Try Circuits" button in the circuits tab of Tinkercad to get an introduction of how to use Tinkercad's circuit simulation feature.
What is an Encoder?
An encoder uses different techniques to detect a rotational motion, as well as a linear motion, which means in a straight line. Encoders are usually paired with a rotating shaft or something that moves in a straight line to measure the rotation or movement of whatever the encoder is paired with. One example of a technique is using light. In a rotational encoder with that technique, there is a light that shines toward a light sensor, also called a photo sensor. Then, there is a circle that rotates in between those two, with holes on the edges. Whenever there is a change in light hitting the photo sensor due to the holes allowing light through, or not allowing it through, the sensor gives out a high or low signal, which differs from what it was before. So in an encoder, if light was hitting a photo sensor, it would give a high signal, then when the circle in between the photo sensor and the light blocks the light from hitting the photo sensor, the photo sensor gives a low signal, or vice versa depending on what makes the photo sensor go high or low. If we know how many holes and non-holes there are on the edge of the circle, we can use that to know what position the circle is in relative to when we started counting, like for example, if the photo sensor had gone high and low, meaning it encountered a hole and non-hole, for half the holes and non-holes in the circle, we know that the circle had spun half way.
Different types of Encoders (covering a few)
Absolute vs. incremental (All encoders fall into one of these)
All encoders would either be absolute or incremental. Absolute means that the encoder will be able to tell you where it is. It's like a GPS telling you exactly where you are on Earth. Incremental is relative, meaning it tells you how much the motor or whatever the encoder is measuring how far it has moved in relation to where it once was. So, it's like a GPS telling you that you've moved 500 feet from your local gas station, but it doesn't tell you exactly where you are in the world. That's the basic gist of absolute and incremental encoders.
Quadrature vs. Rotary
Let's start with rotary encoders since quadrature encoders build upon rotary ones. Rotary encoders are the ones that you see in the right picture below. They are able to measure the speed of how fast the circle is moving by looking at how quickly the holes and non-holes go in between the light and the photo sensor. The quicker the holes and non-holes go in between the light and the photo sensor means the circle is spinning faster, and if we know how many holes and non-holes there are in the circle, we can figure out how many times the circle has rotated for. Quadrature encoders work in a similar way, except this time it has two lights and photo sensors. In the fancy gif below and to the left, you can see two sensors of some sort. The lights are not included in the picture as the sensors could represent different sensors that don't require light from say, and LED, but you get how there are spaces on the circle that change, which changes the sensors to have a high or low output. Looking at the gif, you can see how the square wave signals are not aligned, which is how we can tell if the encoder's circle is spinning forwards or backwards. In the gif, it looks like the "A" sensor goes high, or a digital 1, first, then the "B" sensor. If we were to change the direction of the circle to go in the opposite direction, then we would see the "B" sensor go high first, then the "A" sensor. So this difference of which sensor goes first can help determine the direction the circle is spinning in. Another way is to use binary as you see in the gif with 1s and zeros.
Different ways of doing things (different tech used by various encoders)
So encoders can measure rotation or movement, but there are various ways that can be done. Here are some examples:
Using light (optical): Light can be used to measure rotation or movement using the light as a way to send information, such as light being blocked meaning it gives ___ signal, or light not being blocked meaning it gives ____ signal. Usually the blanks would be high or low, or 1s and 0s. We will take a look at this example in the rest of the lesson.
Using magnetic fields: This would essentially be using a permanent magnet which spins, moving the north side and south side in a rotating fashion. This spinning magnetic field can be detected by a hall effect sensor, which just detects magnetic fields.
Seeing the Theory in Action
In real life, we can use an oscilloscope to look at both sensors in an encoder to see how the signals are shifted a bit. In Tinkercad, if we use two different oscilloscopes, they won't look different because the oscilloscopes both align the signals to the center of the graph, making them look the same. We will try it anyways as it will show how the motors speed can affect how long the sensors see the holes and non-holes.
To start, get an Arduino out, a potentiometer, a diode, a transistor, a motor with an encoder which you can search in the search bar "DC motor with encoder" and pick the one with multi colored wires, and finally an oscilloscope.
First off, let's just know what pins we need to use on the Arduino for which components/pins of those components.
DIO pins 3 & 2: channel A and B of the DC motor with encoder
DIO pin 5: To the base pin of the transistor to allow a larger current through to the motor without having too much current come from the DIO pin itself
analog pin A5: To the wiper/middle pin of the potentiometer to measure the varying voltages of the potentiometer.
That's it for the DIO pins. everything else is either just for power, which is the 5V pin, or GND, or specifically for the oscilloscope, connecting it to the GND and channel A or B of the DC motor with encoder component.
Keep in mind that the diode is used as a flyback diode to prevent a large voltage from being created near the switch, which in this case is the transistor. We don't want that, so place the diode in reverse polarity of the flow of current from the motor in parallel to the motor.
A refresher on how to connect the potentiometer, connect the middle pin to the analog pin listed above, and the side pins to either the 5V pin or GND pin separately. This creates the voltage divider type circuit that was shown to explain how a potentiometer works in a previous lesson.
For the transistor, the base connects to the DIO pin listed above to activate the transistor, and the emitter pin connects to GND while the collector pin goes on the 5V side of the circuit (with the motor along that path to power the motor).
FInally, the oscilloscope negative pin connects to ground and the positive pin connects to either channel A or B so that it can start taking in voltages and plotting them.
If you need a picture of how the components are connected, you can look at the picture below. I am just using a breadboard to keep things more organized instead of having too many wires everywhere. Realistically, we wouldn't rely on the Arduino to source the current for the motor, since that would be too much current going through the Arduino and to the motor. We would use a separate power source that would power both the Arduino using a 5V voltage regulator, and for the motor we would connect the power wires to it in parallel, so that the current going through the motor won't have to go through the Arduino, which would be a series type circuit, which we don't want, since more current means more heat (P = I*V). But for simplicity, and since Tinkercad would still power the Arduino with a USB cable which we can't get rid of, we will just power the motor with the Arduino.
Once you get that setup, copy and paste the code below into that Arduino by clicking on it, pressing the "code button", pressing the drop down menu that says "blocks" then choosing "text", then replace the text to the right with the code you've copied. This will control the Arduino to make the LED brighter or dimmer depending on the potentiometer's handle position. Here's the code:
int A = 0;
int B = 0;
int motor_output = 255;
void setup()
{
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(A5, INPUT);
pinMode(5, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (int(analogRead(A5)/4 >= 255)){
motor_output = 255;
}
else{
motor_output = analogRead(A5)/4;
}
analogWrite(5, int(motor_output));
A = digitalRead(3);
B = digitalRead(2);
delay(1);
}
Explanation of the code
The top half is mainly just setting stuff up, like defining variables or setting the modes of different pins. The bottom half of the code essentially takes in the voltage that the wiper pin of the potentiometer has, and converts that to a PWM signal in the DIO pin. The reason why we divide the analog reading as you see here, "(analogRead(A5)/4" is because the analog readings would be 4 times greater than the DIO output numbers, which is a maximum of 255, ~1/4 of 1023. So, after we convert it to the correct number for an analog output for DIO pin 5 which is a PWM signal, we can tell it to go at a speed which correlates to that number. The next part of the code prints out either a "1" or "0" for the channels A and B.
Press simulate and change the potentiometer's handle. I have found that if the potentiometer ever hits a point where the analog pin reads a voltage of zero, the motor will not want to turn anymore visually, even if the rpm reading is not zero. It would also make the oscilloscope graph a non square wave function even if the rpm reading is not zero. So in short, don't turn the potentiometer to the end that makes the analog pin read 0V. If it does happen, and the motor bugs out, rotate the potentiometer handle to the middle, and press simulate again.
If you go to the serial monitor, you will see the digital outputs of channels A and B, the 1s showing a high signal, and 0s showing a low signal. The left number is channel A, and the right number is channel B. Whenever there is a 1, that means that the sensor in the channel with a 1 has seen the presence or absence of light, or whatever the sensor was designed to detect, which made it output a high signal.
That's Basically it!
That's the end of this lesson on rotary and quadrature encoders, different ways to measure rotation or movement, as well as different categorizations of encoders which are absolute and incremental. The in-person people will get to experiment further on rotary and quadrature encoders. Here are some videos that can help explain the applications of encoders, how they work, and the difference between absolute vs. incremental encoders.
Here's also the demo for the Tinkercad circuit for the mini-project above