Programming a Microcontroller - Engineering - ثاني ثانوي
1. Engineering Fundamentals
2. Electrical Engineering
3. Digital Circuits
4. Circuit Simulation with Tinkercad Circuits
5. Simulating a microcontroller- based system
5. Simulating a microcontroller- based system In this unit, students will learn about microcontrollers and other electronic components. More specifically, students will learn how to program a micro:bit microcontroller with Python in Tinkercad Circuits to create simple and complex circuits with various sensors and actuators. وزارة التعليم Ministry of Education 172 2074-1446 Learning Objectives In this unit, you will learn to: > Design circuits using a microcontroller. > Recognize external components used in microcontroller circuits. > Describe how different components affect circuit logic. > Program a micro:bit microcontroller with Python. > Use the micro:bit temperature and light sensors. > Design microcontroller circuits for real-life scenarios. > Demonstrate how a potentiometer regulates voltage in an electronic circuit. > Describe the use of a transistor. > Use a transistor as an amplifier in an electronic circuit. > Use a DC motor as an actuator for movement. Tools > Autodesk Tinkercad Circuits
Simulating a microcontrollerbased system
Learning Objectives
Tools > Autodesk Tinkercad Circuits
Lesson 1 Programming a Microcontroller Microcontrollers In the modern world, computers are a common part of many people's lives. Most of us are familiar with computers that use a mouse and keyboard for user input and a monitor for output, however, another type of computer, the microcontroller, usually operates without human interaction. A typical computer could be used to run multiple programs simultaneously, such as playing video games and getting email, but the microcontroller can only run one program at a time. Essentially, a microcontroller is a specialized computer with mostly nonhuman input and output devices for interaction with the outside world. Other names for this type of computer are single-board microcontrollers or embedded systems. In all cases, it integrates a processor, memory and some kind of input and output. Rather than having a mouse, keyboard, and monitor as peripherals, the microcontroller uses devices called sensors as inputs and actuators as outputs. A sensor examines the environment and senses specific stimuli, such as touch, sound, temperature, humidity and light almost in the same way as human senses detect stimuli from the surrounding world. These sensors respond to stimuli by generating a change in voltage or a digital signal. Our body works in a similar way, with our human sense organs that transmit signals to our brain through the nervous system. Fire Sensor Figure 5.2: Fire alarm system Alarm وزارة التعليم Ministry of Education 2024-1446 0000000000 3110 Figure 5.1: Microcontroller board Link to digital lesson www.ien.edu.sa The Microcontroller is almost like a tiny computer. brain. But this tiny brain gets stimuli from its sensors as input to a program running in a continuous loop. The program can react and change outputs accordingly. For example, if the temperature is extreme in a building, a microcontroller that checks for fire conditions can trigger an alarm. INFORMATION The job of a microcontroller might be to run the air-conditioning system in a building, monitor and control the operation of an engine in a car, or run machinery on an automated assembly line. 173
Microcontrollers
Although microcontrollers can mimic some human functions, do not mistake their operation for true intelligence. We might call a device "smart" or "intelligent," but all of them operate in a predefined way, following a very specific procedure based on their programming. It does not matter how elaborate the device or how good the program is that runs on the machine. Computers and microcontrollers as hardware cannot truly be considered intelligent. Micro:bit XUNO ARDUINO CC Arduino UNO 766666 The Raspberry Pi is considered by some to be a microcontroller, like the Arduino. In reality, the Raspberry Pi is a tiny computer that can connect directly to a monitor and input devices such as a keyboard and mouse. At the same time, a full operating system can be loaded via a MicroSD memory card. Figure 5.3: Popular microcontrollers There are various microcontrollers around us, such as in autonomous loT devices or inside other electronic equipment and machinery. The most popular microcontrollers for prototyping are the Arduino and micro:bit boards. Both can be simulated in Tinkercad Circuits, but there are some important differences. An Arduino microcontroller, such as Arduino Uno R3, is more powerful in terms of programming, but the micro:bit board has an integrated display and sensors for temperature, light, motion, sound and orientation. وزارة التعليم Ministry of Education 174 2024-1446 Microcontrollers Advantages • They consume small amounts of electricity and do not produce much heat. • Because of their size they can be placed in smaller circuits. • They are adept at single task operations. They exist with a wide range of memory, from 4-bit to 128- bit microprocessors. Disadvantages • In general, they cannot handle multitask operations. • New programs need to be inserted manually. . They have limited processing power. • They generally have no operating system.
Although microcontrollers can mimic some human functions,
External Components for Microcontroller Circuits DC motor Direct Current (DC) motors are electronically controlled devices that generate rotary movement from electrical power. They include a shaft that rotates so that wheels and gears can be attached to them to provide a wide range of motion. DC motors are produced in a wide variety of forms, and they operate in a range from 1.5V to 24V and up to 8,000 RPM (Rotations Per Minute). They can be used used for applications that require high RPM. DC motor Simulator component Figure 5.4: DC motor ME Schematic symbol Piezo buzzer Piezoelectric buzzers are small devices that can generate sound signals. They contain small crystals like quartz and topaz that exhibit the piezoelectric effect. When electric currents pass through these crystals, the crystals expand and contract repeatedly, and this causes them to vibrate. These rapid vibrations are the source of the sounds generated by these buzzers. Piezo buzzer Simulator component Figure 5.5: Piezo buzzer Schematic symbol PIR sensors Passive Infrared (PIR) sensors are electronic sensors that can detect objects in a specific Field Of View (FOV). They work by measuring the infrared radiation signals that are present in the FOV that they examine. When an object passes through the FOV, the distribution of those signals changes and the sensor detects that an object is present. They are used for monitoring applications such as security alarms and room lighting controls. وزارة التعليم Ministry of Education 2024-1446 PARALLAX PIN SENSOR Δεν 555-28821 PIR sensor Simulator component Figure 5.6: PIR sensor VCC OUT PIR GND Schematic symbol 175
External Components for Microcontroller Circuits
Potentiometer (Variable Resistor) Potentiometers are small devices that are used to manually adjust the voltage that is applied to a specific part of a circuit. They utilize Ohm's law, which we learned about in a previous lesson. Ohm's law states that V = 1 × R. For constant current, if you want to change the voltage, you need to adjust the resistance. Potentiometers allow you to modulate the voltage to the desired value by manually adjusting the resistance. Potentiometer Simulator component Schematic symbol Figure 5.7: Potentiometer Servomotor Servomotors are a special type of motor with two defining features. They operate within a limited range of motion, and they provide position feedback so that their controller is informed of the exact angle that the servomotor has turned. Servomotors are used for actions that require high-precision motion like robotic applications and manufacturing operations. وزارة التعليم Ministry of Education 176 2024-1446 4 PWR SIG GND Servomotor Simulator component Schematic symbol Figure 5.8: Servomotor
Potentiometer (Variable Resistor)
Servomotors
Micro:bit The Micro:bit microcontroller in Tinkercad Circuits environment With Tinkercad Circuits, you can simulate microcontroller circuits using a simple block-based programming language or the Python programming language. In this unit, you will utilize the micro:bit as a microcontroller in an environment that allows for experimentation. In microcontroller projects there are two parts to every project. The first is the circuit itself, which includes the sensors, the actuators and the wiring that connects all components. The second is the code used to program the microcontroller. This code manages the inputs from the sensors and sends instructions to the actuators. In the Tinkercad simulator, Python for micro:bit is utilized. KE Example 25 LED lights Button A Figure 5.9: Micro:bit in Tinkercad Circuits Plea Ministry of Education 2024-1446 USB connection {0}] Default Name "1" Name of the component "micro:bit" ges saved 1 < Code Start Simulation Send To Components Basic micro:bit Default Color "Red" Name 1 Color Red 0:1 Micro:bit in the workplane Button B 3V GND Edge connector for accessories Search Capacitor Slideswitch 9V 9V Battery > Coin Cell 3V Battery 1.5V Battery Breadboard Small micro:bit Arduino Uno R3 177
Micro:bit
Python Programming You have learned how to write code in Python in previous books/courses in this series. The code used here will be similar. Let's see how Python is implemented for micro:bit in the Tinkercad Circuits code editor. Default Python code Download code Code editor All changes saved 非 ব </ Code Start Simulation Send To Text ? ?. A AA 1 (micro:bit) 1# Python code 2 # 3 4 basic.show_icon (IconNames. Happy) 5 def on_forever (): 6 7 8 pass basic.forever (on_forever) Serial Monitor Serial Monitor Figure 5.10: Tinkercad Circuits code editor Let's take a look at some commands that we are going to use: To pause after an action is completed, use the following method which takes an argument in milliseconds: basic.pause(1000) Pause for 1 second. The following code will begin when you press the Start Simulation button and stop when you press the End Simulation button. def on_forever(): # Your circuit logic here basic.forever(on_forever) The code that will replace the comment will run without stopping. Display a custom shape through the LED light matrix: basic.show_leds("'" . . # . . .###. # # # # # The LED lights matrix will turn on at the locations where the '#' symbols are. وزارة التعليم Ministry of Education 178 2024-1446 Select device Font size Python documentation 0: A GND
Python Programming
画 LED light matrix Let's see how you can use the things that you have learned. You will create a program to show two icons, '0' then '1', alternating every second on the LED matrix and repeating forever. First you need to find micro:bit in the components library and drag it to the workplane. To add micro:bit: > Find micro:bit in the components library + and drag and drop it into the workplane. 2 3 > Click on the drop down menu and choose Green. 4 وزارة التعليم Ministry of Education 2024-1446 :0 2 Saving... 非 < Code Start Simulation Send To micro:bit Components Basic Name 3 3 Search Color Green Red Yellow A6 COIN BATTERY Green 4 Blue 9V Battery Coin Cell 3V Battery B 3V GND Figure 5.11: Add micro:bit > 1.5V Battery Breadboard Small 1 UNO micro:bit Arduino Uno R3 179
LED light matrix
Now, you need to open the code editor: To open the code editor: > Click on Blocks drop down menu. 1 > Select Text from the drop down menu. 2 > Click Continue 3 to open text editor. 4 Example EDIT MODE All changes saved 1 micro:bit Blocks 土 Name 1 Color Red Basic Output Input Control Math Variables Blocks Blocks + Text 2 Text clear screen show icon 非 Code Start Simulation Send To 1 (micro:bit) Are you sure? Are you sure you want to close the Blocks editor? Any blocks you currently have will be lost. The code in the text editor will remain and become editable. Continue 3 Cancel show suing Hellist 4 < Code Start Simulation Send To ? A4 - 1 (micro:b Text 1 # Python code 2 # 3 basic.show_icon (IconNames. Happy) 4 5 def on forever (): passo basic. forever (on_forever) وزارة التعليم Ministry of Education 180 2024-1446 Figure 5.12: Open the code editor If you haven't chosen a microcontroller yet, the code tab will show you the message "No programmable components in this circuit".
Open the code editor:
Continue by writing the code shown below in the text editor and then start the simulation. Writing code: > Write the code in the text editor. > Click Start Simulation button. 2 :0 4 AD Text 2 1 def on_forever (): basic.pause (1000) basic.show leds (""" 3 234 5 6 7 8 2 < Code Start Simulation ? AA A4 - 1 (micro:bit) basic.show_leds (""" 1 When you have finished writing the code, click on the Start Simulation button to begin the simulation. 10 11 12 13 14 15 16 17 869GAWNTO6 9 basic.pause (1000) # 18 basic.forever (on_forever) Figure 5.13: Writing code When the simulation is running on the LED light matrix, you can see the following results: . وزارة التعليم Ministry of Education 2024-1446 34 0: ΔΡ 3V GND ##### # . ##### [:0 2 3V GND 181
Writing code:
micro:bit Sensors When you start the simulation, a window appears in the workplane. This window lets you adjust the properties of the simulation environment that affect the micro:bit's sensors, more specifically, the compass, the light sensitivity sensor, the temperature sensor and the accelerometer. Light sensitivity sensor micro:bit 1 Temperature sensor 21°C 128 Motion actions Figure 5.14: Micro:bit sensor adjustments Temperature indicators To get inputs from integrated micro:bit sensors, e.g. temperature and light level, you need the following methods: In the plot_bar_graph() method, the second argument is the maximum value that is represented by the plot. For example, in the Tinkercad simulator the maximum light level and temperature values are 255 and 50 respectively. 21°C وزارة التعليم Ministry of Education 182 2024-1446 input.temperature() def on_forever(): led.plot_bar_graph(input.temperature(), 50) basic.forever(on_forever) Input the current value of the temperature sensor Temperature sensor maximum value 50 °C input.light_level() def on_forever(): led.plot_bar_graph(input.light_level(), 255) basic.forever(on_forever) Input the current value of the light sensitivity sensor Light sensitivity sensor maximum value 255
micro:bit Sensors
وزارة التعليم Ministry of Education 2024-1446 P micro:bit 3 Let's first see an example of how you can use the temperature sensor with the LED light matrix. Example 4 Simulator time: Simulator time: Code Stop Simulation 1 (micro:bit) 1 def on forever (): 2 led.plot_bar_graph (input.temperature (), 50) 3 basic.forever (on_forever) Temperature at 21 °C Temperature at 40 °C Temperature at 50 °C 0:. GND AB 0 0:. micro:bit 3 GND micro:bit 3 21°C 128 40°C 128 50°C 128 0:] GND 183
Let's first see an example of how you can use the temperature sensor with the LED light matrix.
Now, let's see another example, but this time you are going to use the light sensitivity sensor with the LED light matrix. Example micro:bit 3 21°C وزارة التعليم Ministry of Education 184 2024-1446 34 4 4|A Simulator time: Code Stop Simulation 1 (micro:bit) 1 def on forever (): 2 led.plot_bar_graph (input.light_level(), 255) 3 basic. forever (on_forever) Light level at 34 Light level at 128 Light level at 255 0:. L AB GND micro:bit 3 0:. GND ::0 GND micro:bit 3 21°C 255 21°C 128 L
Now, let's see another example but this time you are going to use the light sensitivity sensor with the LED light matrix.
Exercises 1 How do you use a microcontroller? 2 What are the advantages of using microcontrollers? 3 Match the items in the first row with those in the second. Simulator component PARALLAX PIR SEHEOR 555-28827 Name PIR sensor Servomotor Piezo buzzer Potentiometer DC motor وزارة التعليم Ministry of Education 2024-1446 185
How do you use a microcontroller?
What are the advantages of using microcontrollers?
Match the items in the first row with those in the second.
0:. 4 Create a program to show the three letters, "K", "S", and "A" alternating every second on the LED light matrix and repeated forever. GND 0: 2 GND 0: Change the program to make each letter flash twice quickly before it shows the next letter. Add a pause with a blank matrix at the end of the loop. 3V GND 5 Why do we use the value 50 as a maximum value for temperature when we use led.plot_bar_graph? What will happen if we use another value? Run the simulator and explain what you observe. 6 Create a program on the micro:bit that displays an UP arrow when the temperature is above 21 degrees and a DOWN arrow when the temperature is lower than 21 degrees. What else do you need to check? Fix your program so it works properly in all temperature conditions. وزارة التعليم Ministry of Education 186 2024-1446 B