🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

ET1025 IEP Lab_Project Guide Using Basic Embedded System.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

ET1025 Introduction to Engineering Programming Part 2 --- Programming on Basic Embedded System Lab and Project Guide Introduction to Engineering Programming Lab and Project Guide Engineering Programming Application in Basic Embedded Syst...

ET1025 Introduction to Engineering Programming Part 2 --- Programming on Basic Embedded System Lab and Project Guide Introduction to Engineering Programming Lab and Project Guide Engineering Programming Application in Basic Embedded Systems In this module, you are required to carry out an Arduino project to further develop your programming skill and apply your C++ programming knowledge in Engineering applications. 1. Embedded System Basics An embedded system is often a small form factor (small size) computer system that performs specific tasks. It consists of software, hardware with sensors and interfacing circuits that can be either mechanical or electronic. All these parts function together to perform a dedicated function. Examples of Embedded systems: o Electronic parking meters and parking pay stations o Robotic vacuum cleaners o Smart watches o Appliances, example: refrigerators, washing machines, microwave ovens o Home security systems o Air-conditioners, etc. The heart of a simple embedded system is a microcontroller. A microcontroller is a computer system on a chip. It contains the following parts integrated on one IC chip: 1. Integrated processor with memory (RAM, ROM, flash memory) 2. Programmable timers, counters, clocks, comparators, etc. 3. Communication (USB, I2C, SPI, USART-RS232, etc.) (connection) 4. I/O interface circuit for interfacing Input-output devices, like sensors, LED, etc, to control or interact with the physical environment. Example: To interact with humans: keyboards, keypads, buttons, LCD-LED displays, joysticks, etc. To measure the environment: temperature sensors, light sensor, pressure sensors, weight sensors, color sensors, moisture sensors, humidity sensors, etc. To move things: DC motors, servo motors, stepper motors, actuators, etc. Others: speakers, microphone, etc. General Block Diagram of a simple embedded system. Light Logic voltage Drivers Motors Sensor (Arduino) Temp to Temp Voltage & Microcontroller LED Sensor ADconvert (uC) Digital Micro Intelligent Analog Power Amplifier Speakers phone ADconvert Process & Convert Amplifier Some Decision Some Input Signal Output Signal Input ‘The Brain’ Output Conditioning Conditioning Devices Devices & interface & interface School of EEE Lab and Project Guide Page 1 Introduction to Engineering Programming Lab and Project Guide Embedded Software or Program allows Hardware to monitor external events (Inputs / Sensors) and control external devices (Outputs) accordingly. During this process, the program for an Embedded System may have to directly manipulate the internal architecture of the Embedded Hardware (usually the processor) such as Timers, Serial Communications Interface, Interrupt Handling, and I/O Ports, etc. There are many programming languages that are used for Embedded Systems like Assembly Language, C, C++, JAVA, Python, etc. In this module, you will learn how to use C++ programming language to develop a simple engineering application running on an Arduino Uno based embedded system. 2. What is Arduino? Arduino is an open-source platform used for building electronics projects involving both hardware and software. The Arduino board is in the form of a printed circuit board (PCB) that is specifically designed to use a microcontroller chip as well as other inputs and outputs. It also has many other electronic components that are needed for the microcontroller to function or to extend its capabilities. You write code in the Arduino software to tell the microcontroller what to do. For example, by writing a line of code, you can tell an LED to blink or stop blinking. If you add a pushbutton and add another line of code, you can tell the LED to turn on only when the button is pressed. Next, you may want to tell the LED to blink only when the pushbutton is held down. In this way, you can quickly build a behaviour for a system that would be difficult to achieve without a microcontroller. Similarly to a conventional computer, an Arduino can perform a multitude of functions, but it’s not much use on its own. It requires other inputs or outputs to make it more useful. These inputs and outputs allow a computer to sense objects in the world and to affect the world. 2.1 Arduino Uno R3 There are many types of Arduino boards, each with its own design to suit various applications. Deciding what board to use can be a daunting prospect because the number of boards is increasing, each with new and exciting prospects. However, one board can be considered the backbone of the Arduino hardware; this is the one that almost all people start with and that is suitable for most applications. It’s the Arduino Uno. R3 relates to the revision of the features on the board, which includes updates, refinements, and fixes. In this case, it is the third revision. Refer to https://www.arduino.cc/en/hardware#boards for other types of Arduino boards. School of EEE Lab and Project Guide Page 2 Introduction to Engineering Programming Lab and Project Guide 2.2 Arduino Uno and its Key features (the heart) Key features of Arduino Uno R3: It uses the ATmega328P microcontroller, has 14 digital input/output pins (of which 6 can be used as PWM or Pulse Width Modulation outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a power jack, and a reset button. Arduino Uno Pinout Configuration for reference only Pin Category Pin Name Details Power Vin, 3.3V, 5V, GND Vin: Input voltage to Arduino when using an external power source. 5V: Regulated power supply used to power microcontroller and other components on the board. 3.3V: 3.3V supply generated by on-board voltage regulator. Maximum current draw is 50mA. GND: ground pins. Reset Reset Resets the microcontroller. Analog Pins A0 – A5 Used to provide analog input in the range of 0-5V Input/Output Pins Digital Pins 0 – 13 Can be used as input or output pins. Serial 0(Rx), 1(Tx) Used to receive and transmit TTL serial data. External Interrupts 2, 3 To trigger an interrupt. PWM 3, 5, 6, 9, 11 Provides 8-bit PWM output. SPI 10 (SS), 11 (MOSI), 12 (MISO) Used for SPI communication. and 13 (SCK) Inbuilt LED 13 To turn on the inbuilt LED. TWI A4 (SDA), A5 (SCA) Used for TWI communication. AREF AREF It is a reference INPUT voltage used by the A/Ds School of EEE Lab and Project Guide Page 3 Introduction to Engineering Programming Lab and Project Guide 2.3 Arduino Shields Arduino shields are boards that will expand the functionalities of your Arduino. You just need to plug them over the top of the Arduino board. There are countless types of shields to do countless tasks. For example, you can use a shield to make it easier to connect and control motors or even to turn your Arduino into something as complex as a mobile phone. A shield may start out as an interesting bit of hardware that an enthusiast has been experimenting with and wants to share with the community. Or an enterprising individual (or company) may design a shield to make a specific application easier based on demand from the Arduino community. Shields allow you to use your Arduino for more than one purposes. They neatly package the electronics for that circuit in the same footprint as an Arduino. In your project, a shield starter kit (Named as Rich Shield and produced by Open-Smart company) will be used. This Rich Shield has many basic components on board such as LEDs, buttons, buzzer and other input sensors or output devices. It also leads out two I2C ports for you to connect I2C device such as DS1307 RTC, I2C 1602 LCD, PCA9685 16 Channel 12-bit PWM Servo motor Driver I2C Module or other I2C devices. And it also leads out UART port to connect serial control devices such as serial MP3 player, serial Bluetooth- compatible, serial wifi-compatible module, serial 125k RFID, etc. Rich Shield with IR (Infrared) The Rich Shield also has an Infrared Receiver that can work Remote Controller with an external IR Remote controller. Its Pinout configuration is as follows: Analog pins Digital pins // ~ denotes PWM pins A0 Blue Knob/potentiometer 0 Rx A1 NTC Temperature Sensor 1 Tx A2 LDR 2 IR Receiver A3 External voltage Source 3~ Buzzer (Voltage Divider) 4 LED1 (Red) 180k/(180+820)k = 0.18 ratio 5~ LED2 (Green) 6~ LED3 (Blue) A4 SDA (Connect to EEPROM 7 LED4 (Yellow) 24C02ASN) 8 KEY0 (Button Switch K1) A5 SCL (Connect to EEPROM 24C02ASN) 9~ KEY1 (Button Switch K2) 10 CLK (for LED Drive Control Special Circuit TM1637) 11~ DIO (For TM1637) 12 DHT 13 Uno Inbuilt LED School of EEE Lab and Project Guide Page 4 Introduction to Engineering Programming Lab and Project Guide 2.4 Programming the Arduino Board This module will guide you through Arduino coding using the C++ programming language. We will employ the Arduino IDE, version 2.x, as the Integrated Development Environment for creating and developing your Arduino programs. It's worth noting that compatibility extends to older versions of the Arduino IDE as well. 2.4.1 Basics of Arduino Programming void setup( ) { statements-1; The structure of Arduino program is pretty simple. Arduino. programs have a minimum of 2 blocks. Each block has a set. of statements enclosed in curly braces:. statement-n; } setup ( ) is the preparation block and loop ( ) is an execution block. Both functions are required for the program to work. void loop ( ) { The setup ( ) function should follow the declaration of any statement-1; variables at the very beginning of the program. It is the first. function to run in the program. It is run only once and is. used to set pinMode or initialize serial communication, etc.. It must be included in the program even if there are no statement-n; statements to execute. } After the setup ( ) function is executed, the loop ( ) function runs next. The loop ( ) function hosts statements like reading inputs, triggering outputs, checking conditions, etc. As the name suggests, the loop( ) function executes the set of statements (enclosed in curly braces) repeatedly. This function is the core of all Arduino programs and does the bulk of the work. One example is shown below. Refer to the comments for explanation of the code. void setup() { pinMode (pinNumber, OUTPUT); // set the ‘pinNumber’ as output pinMode (pinNumber, INPUT); // set the ‘pinNumber’ as input } void loop() { digitalWrite (pinNumber,HIGH); // turns ON the component connected to ‘pinNumber’ delay (1000); // wait for 1 sec or 1000 milliseconds digitalWrite (pinNumber, LOW); // turns OFF the component connected to ‘pinNumber’ delay (1000); //wait for 1 sec } School of EEE Lab and Project Guide Page 5 Introduction to Engineering Programming Lab and Project Guide The functions, pinMode(), digitalWrite() and delay() are part of the "Arduino core functions" or "Arduino built-in functions." Arduino core Description Function Prototypes function pinMode() Configure a specific pin to void pinMode(int pin, int mode) ; behave either as an input or an output. The first parameter, pin is the number of the pin whose mode you wish to set. The second parameter, mode can be INPUT, OUTPUT, or INPUT_PULLUP. digitalWrite() Write a HIGH or a LOW value void digitalWrite(int pin, int logicLevel); to a digital pin. The first parameter, pin is the number of the digital pin. The second parameter, logicLevel can be HIGH (or 1) or LOW (or 0) delay() Pause the execution of your void delay(int mSec); Arduino program for a specified period Function parameter, mSec specifies the delay duration in millisecond Now, let us take a giant leap and do some experiments with Arduino. Refer to the lab experiment 1 on “Getting started with Arduino Programming” and other lab exercises to learn how to write programs with engineering applications. With the Arduino Uno and the I/O shield (Rich Shield), you will learn how to create and develop some simple engineering projects, such as the following: Control of LEDs Monitoring Light sensor and Control of LEDs Creating melody with Passive buzzer Detecting Button pressed or released Knob control for LED brightness Temperature and humidity measurement and display Infrared remote control, etc. School of EEE Lab and Project Guide Page 6 Introduction to Engineering Programming Lab and Project Guide Lab Experiment 1: Installing Arduino IDE Getting Started with Arduino Programming Controlling LEDs on IO Shield Activities 1. Installing Arduino IDE 1.1 Download Arduino IDE Visit the official Arduino website: https://www.arduino.cc/en/software Download Arduino IDE (version 2.X.X or the latest version available); Download Option: Windows win 10 and newer, 64 bits. 1.2 Install Arduino IDE Run the installer you downloaded Follow the on-screen instructions to complete the installation. 2. Getting Started with Arduino Programming This guide will walk you through setting up your development environment, equipping you to write, compile, debug, and upload Arduino sketches. An Arduino sketch, a program for Arduino boards, typically includes two functions: setup() and loop(). In the Arduino IDE, these programs are referred to as sketches and are stored as.ino files containing the source code to control Arduino circuit boards. 2.1. Arduino IDE Set Up with Arduino Uno Board Connected to PC/laptop Launch Arduino IDE. Select Arduino Uno board via Tools -> Board -> Arduino AVR Boards -> Arduino Uno Connect your Arduino board to the computer using the USB cable provided. Ensure the board is recognized by checking the Tools -> Port menu in the Arduino IDE. Tip: If you connect your board to a different USB plug on your PC, The port number that your Arduino Board is connected the COM port number may change. Whenever you have problems uploading to can be different from the your sketch to the Arduino board, first check if the proper COM port is selected. screenshot shown here. School of EEE Lab and Project Guide Page 7 Introduction to Engineering Programming Lab and Project Guide 2.2. Test Blink Program with Verify and Upload Buttons The Blink program, named “Blink.ino”, is a fundamental built-in example accessible through the File menu: File -> Examples -> 01.Basics -> Blink as shown below: Click the Verify button followed by the Upload button to upload the program to the Arduino Uno board. The Verify button is used to compile your sketch without uploading it. The Upload button combines the Verify Function and once the code is compiled successfully, it will upload it via the Serial port to your microcontroller. And you will see your code running and performing specified tasks in your Uno board. Verify that the built-in LED on the Arduino Uno board is blinking, confirming both the correctness of your Arduino IDE setup and the proper functioning of the Arduino Uno board. Note: As your Uno board is connected to the Rich Shield, you can only see the blinking LED on the board underneath the Shield. Upload Verify button button 2.3. Modify the Blink Program to Blink the Red LED on the Rich Shield Replace all 'LED_BUILTIN' in the above Blink.ino program with '4' to make the Red LED on the Rich Shield blink, instead of the built-in LED. School of EEE Lab and Project Guide Page 8 Introduction to Engineering Programming Lab and Project Guide ‘4’ is the number of digital pin connected to the Red LED on Rich Shield. Verify and upload the code to run the program. Save the program and name it 'BlinkRedLED' using File -> Save As... Note: The name of the file must be in one word without spaces. 3. Controlling LEDs on IO Shield Create a new program by selecting File -> New Sketch. Refer to the following program guide to control any of the 4 LEDs on the IO Shield, such as blinking any or all of them. Check the comments within the code for explanations. #define LED_RED 4 //The red Led is connected to Digital Pin 4 of Arduino Uno #define LED_GREEN 5 //The green Led is connected to Digital Pin 5 of Arduino Uno #define LED_BLUE 6 //The blue Led is connected to Digital Pin 6 of Arduino Uno #define LED_YELLOW 7 //The yellow Led is connected to Digital Pin 7 of Arduino Uno // the setup function runs once when you press reset or power the board void setup() { // initialize each of the digital pins as an output. pinMode(LED_RED,OUTPUT); pinMode(LED_GREEN,OUTPUT); pinMode(LED_BLUE,OUTPUT); pinMode(LED_YELLOW,OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(____________, HIGH); // turn a LED on (HIGH is the voltage level) delay(_____________); // wait for ? millisecond digitalWrite(____________, LOW); // turn a LED off by making the voltage LOW delay(_____________); // wait for ? millisecond // you may add more program statements to turn ON/OFF other LEDs } School of EEE Lab and Project Guide Page 9 Introduction to Engineering Programming Lab and Project Guide Below is a typical block diagram illustrating a project with an LED, along with the program flowchart detailing the steps to blink the LED. Block diagram Arduino LED Flowchart Start Start Set LED PIN as output Set LED PIN as output Turn on LED Write 1 or HIGH to LED pin Delay for a while Delay for a while Turn OFF LED Write 0 or LOW to LED pin Delay for a while Delay for a while or Practices 1 to 3 in the upcoming pages are designed for additional hands-on experience in controlling LEDs. These exercises serve as valuable preparation, sparking ideas for your upcoming projects. LAB1 Practice 1 : Writing User-defined Functions for LED Control In this prac ce, you will explore the implementa on of loops and func ons in your program to control the blinking patern of an LED. Specifically, you'll write a program to make the blue LED, connected to pin 6 on the Arduino, alternate between fast and slow blinks. Follow these specifica ons: The LED should blink 5 mes quickly, followed by 5 slow blinks. During fast blinking, the LED should have a 1-second period—turned on for 0.5 seconds and off for 0.5 seconds. During slow blinking, the LED should have a 4-second period—turned on for 2 seconds and off for 2 seconds. Ensure that the LED con nues this alterna ng patern for as long as the Arduino receives power from your laptop. School of EEE Lab and Project Guide Page 10 Introduction to Engineering Programming Lab and Project Guide (a) Implement the LED blinking pattern using Flowchart for Lab 1 Practice 1(a) two loops. The first loop should control Start the LED to fast blink 5 times, and the Set BLUE LED PIN 6 as output, Declare int variable count second loop should control the LED to count=5 slow blink 5 times (See the flowchart on the right for reference). No Is count 0? Yes Write 1 or HIGH count=5 to BLUE LED Yes Is count 0? Delay 0.5 sec No Write 1 or HIGH Write 0 or LOW to BLUE LED to BLUE LED Delay 2 sec Delay 0.5 sec Write 0 or LOW count-- to BLUE LED Delay 2 sec count-- (b) Alternatively, you can improve the code within the loop() function by utilizing two function calls, as shown below:" void loop() { blink(LED_BLUE, 1000, 5); blink(LED_BLUE, 4000, 5); } Refer to the flowchart below for guidance on implementing the blink function. Follow the given function prototype and use the provided parameter names. void blink(int pinNum, int blinkPeriod, int blinkTimes); Flowchart for Lab 1 Practice 1(b) Start void blink(int pinNum, int blinkPeriod, int blinkTimes) Set BLUE LED PIN 6 as output, Declare int variable count No Yes Declare int variable duration Is blinkTimes 0? Write 1 or HIGH to pinNum count=5 duration=1000 Delay blinkPeriod/2 blink Write 0 or LOW to pinNum count=5 duration=4000 Delay blinkPeriod/2 blink blinkTimes-- return funcitonName This is the symbol for user-defined function (refer to Appendix D for reference). `. School of EEE Lab and Project Guide Page 11 Introduction to Engineering Programming Lab and Project Guide LAB1 Practice 2 : Blinking Red LED to Simulate Emergency Flashing Lights (Optional based on your project needs) Red beacon lights are associated with emergency situations. In Singapore, red flashing lights on ambulances and fire engines signal to other road users that there is an emergency. All other vehicles are legally bound to give way to the emergency vehicles in such situations. Red beacons are also used to warn of hazardous conditions, and for people to stay away from a certain area. (a) Modify the Blink LED program example to blink the red LED instead, as a simulation of the red beacon lights. (b) Practise drawing the block diagram and flowchart in the space provided below and modify your program by calling the “blink function” designed in Practice 1(b) to simulate emergency flashing lights. School of EEE Lab and Project Guide Page 12 Introduction to Engineering Programming Lab and Project Guide LAB1 Practice 3 : Traffic Lights Sequence for Vehicles (Optional based on your project needs) Create a new Arduino program to control the LEDs to simulate the Traffic lights sequence as follows: 1. Turn on green LED only for 5 seconds 2. Turn on yellow LED only for 1.5 seconds 3. Turn on red LED only for 4 seconds. 4. Repeat the sequence indefinitely. Draw the block diagram and flowchart first before coding. School of EEE Lab and Project Guide Page 13 Introduction to Engineering Programming Lab and Project Guide Lab Experiment 2 (Part 1): Programming the Arduino Board with Inputs and Outputs on IO Shield Working with Buttons and Serial Monitor Working with Knob (Potentiometer) and LDR (Light Dependence Resistor) 1. Working with Buttons and Serial Monitor Introduction There are two buttons, labelled as K1 and K2 in the IO shield. They are connected to digital pin 8 and pin 9 respectively and are inputs to the Arduino board. To ensure proper button operation, set the pins connected to the buttons as INPUT_PULLUP using the pinMode function as follows: pinMode (pinNumber, INPUT_PULLUP); //prototype: void pinMode (int pinNo, int mode) This configuration enables the internal pull-up resistors, eliminating the need for external resistors. Use the digitalRead function to check the status of the buttons. Function prototype: int digitalRead(int digitalPinNumber) The function returns:  0 when the button is pressed  1 when the button is released. This is the result of the INPUT_PULLUP configuration on the Arduino board, where the pin is normally HIGH (1) and goes LOW (0) when the button is pressed. The Arduino Serial Monitor facilitates real-time communication between your computer and Arduino board. Primarily used for debugging and monitoring, it enables data exchange through a serial connection. Basic Usage: 1. Opening Serial Monitor: After uploading your Arduino sketch, access the Serial Monitor through the toolbar icon or Tools > Serial Monitor. 2. Selecting Serial Port: Confirm the correct port is chosen in Tools > Port, corresponding to your Arduino connection. 3. Setting Baud Rate: Specify baud rate, matching it with your sketch’s baud rate settings. 4. Sending and Receiving Data: Input data in the top field and click "Send" or press "Enter" to transmit to the Arduino. Monitor received data in the main window, useful for real-time feedback and debugging. 5. Debugging and Monitoring: Use Serial.println() in your sketch for debugging, printing variables or messages. Example: Serial.println("Hello, Arduino!"); (similar to cout) 6. Closing Serial Monitor: Click the "X" button or revisit Tools > Serial Monitor to close the interface. School of EEE Lab and Project Guide Page 14 Introduction to Engineering Programming Lab and Project Guide Activities 1.1 Create an Arduino program and copy & paste the following program to it. #define BUTTONK1 8 //BUTTON K1 is connected to digital Pin 8 void setup() { pinMode(BUTTONK1,INPUT_PULLUP); // sets pin8 as input with INPUT_PULLUP mode. Serial.begin(9600); // open serial port, set data rate to 9600 bps } void loop() { if (digitalRead(BUTTONK1) == 0) // check if button K1 is pressed (logic 0 when pressed) { delay(300); // add a small delay to debounce the button Serial.println("Button K1 is pressed");//send the string to Serial monitor while (digitalRead(BUTTONK1) == 0); } } 1.2 Ensure you have selected the correct board and port, then upload the program to the Arduino Uno. Debug any errors that may arise. Finally, open the Serial Monitor to observe the real-time button states. In the Serial monitor, you can see that whenever you press button K1, the string message in Serial.println("Button K1 is pressed") will appear. Start Set Button K1 PIN 8 as input with INPUT_PULLUP mode Set serial port data rate to 9600 bps Read Button K1 value No 1.3 The block diagram and flowchart for this coding activity Is Button K1 pressed? are given below and on the right respectively for your Yes reference. Delay 0.1 sec Dispaly “Button K1 is Pressed” to Serial Monitor Button K1 Arduino Serial Read Button K1 value Monitor No Is Button K1 Relessed? Yes School of EEE Lab and Project Guide Page 15 Introduction to Engineering Programming Lab and Project Guide Congratulations for successfully running the basic code. Next, do Practice 1 below to use the button switches to control LEDs. LAB2 Practice 1 : Button to Control Traffic Light Sequence Modify the above program to simulate pedestrian’s request to stop the vehicles’ flow when button K2 is pressed. 1.5 seconds after the button K2 is pressed, the green LED will be OFF and yellow LED will be ON for 1.5 seconds followed by red LED turned ON for 4 seconds. The pedestrian can then safely cross the road. After this, the green LED is ON again indefinitely if button K2 is not pressed. (a) Draw the block diagram and plan your program with the flowchart in the space provided below. (b) Write your program with the use of a function. Its function prototype is given below: void stopVehicleRequest (int button); Implement and call the function in your program. (Hint: refer to the previous page, or Lab Guide Appendix B for how to use button K2 in Arduino code.) School of EEE Lab and Project Guide Page 16 Introduction to Engineering Programming Lab and Project Guide 2. Working with Knob (Potentiometer) & LDR (Light Dependence Resistors) Introduction The blue knob in the IO shield is connected to Analog pin, A0. It is an analog input. It is not necessary to use pinMode () to set it as an input. (no need for analog pins) The int analogRead(int analogPin) function is used to check the strength of the analog signal that is internally digitised by the Arduino board. analogRead(A0) returns a value ranged from 0 to 1023 which is a 10-bit digitised value (from Analog to Digital conversion) of the analog signal strength as the knob is turned from one end (anticlockwise) to the other end (clockwise). The knob can be used to simulate an analog input or sensor, such as water level sensor, distance sensor, pressure level sensor and so on. Similarly, the Light Dependence Resistor, LDR is connected to analog pin, A2 and analogRead(A2) is used as it is an analog input/sensor (light level sensor). LDR are light sensitive devices most often used to indicate the presence or absence of light, or to measure the light intensity. Its resistance decreases with increasing light levels. Typically > 1 MΩ when dark and < 1 kΩ in high light levels with response time of 2 – 50 ms. LDR on the shield is connected such that o When there is no light (or in full darkness environment), analogRead(A2) returns a very small value (can be less than 10). o When very strong lights shine on it, analogRead(A2) returns a very high value (can be near to 1023, the maximum possible value). Activities Create an Arduino program and copy & paste the following program to it. Compile and upload to run the program by slowly turning the blue knob clockwise and anticlockwise. #define KNOB_PIN A0 //The blue knob is connected to analog pin A0 int knobValue; void setup() { Serial.begin(9600); } void loop() { knobValue=analogRead(KNOB_PIN); //read value of the knob and assign it to the variable Serial.print("Knob value : "); Serial.println(knobValue); //print out the value of the knob to the Serial monitor delay(500); } School of EEE Lab and Project Guide Page 17 Introduction to Engineering Programming Lab and Project Guide Write down your observation / learning points on how to program for the knob. LAB2 Practice 2 : LED ON/OFF Control with LDR and Brightness Control with Knob (Optional based on your project needs) (a) Add in the code to use the LDR to control LED. Hints: #define LDR_PIN A2 //add this line int ldrValue; //declare int variable, ldrValue to store the analog value read from LDR sensor ldrValue = analogRead(LDR_PIN); //store the analog value read from LDR sensor Using Serial.println ( ) function, observe how ldrValue changes as you use your phone torch light to shine on it and as you cover it with a black cloth or with your hand. (b) Apply the LDR control such that when the ldrValue is lower than a DARKNESS level (to be set by you with reference to the ambient light of your surrounding), the yellow LED (pin 7) will be turned ON, otherwise, the yellow LED will be turned OFF. (c) Add in a control in your program to dim another LED light when the blue knob, served as a dimmer switch, is turned anticlockwise. Conversely, the LED brightness level will increase when the knob is turned clockwise. Choose either the green LED (pin 5) or blue LED (pin 6). Pin 5 and pin 6 are 2 of the PWM (Pulse Width Modulation) pins that can be used with the analogWrite ( ) function described below. Hints: knobValue = analogRead(A0); analogWrite(LED_PIN, knobValue/4); (d) Draw the block diagram and plan your program with the flowchart on the next page. Write your program with a user-defined function: void dimmer(int outputPwmPinNum, int inputControlPinNum); Design and implement this function, and use it in your program. School of EEE Lab and Project Guide Page 18 Introduction to Engineering Programming Lab and Project Guide Brief Explanation of PMW and AnalogWrite (pin, value) Function PWM,Pulse Width Modulation, is a technique used in controlling brightness of LED, speed of DC motor, moving angle of a servo motor, or where you have to get analog output with digital means. The Arduino's built-in library function makes PWM easy to use; simply call analogWrite(pin, value), where value is an 8-bit number from 0 to 255, and pin is one of the PWM pins (3, 5, 6, 9, 10, or 11). The 8-bit value corresponds to an effective voltage of 0 to 5 Volts. The higher the value, the higher the effective voltage to the PWM pin. The analogWrite function provides a simple interface to the hardware PWM, but doesn't provide any control over frequency. School of EEE Lab and Project Guide Page 19 Introduction to Engineering Programming Lab and Project Guide Lab Experiment 2 (Part 2): Programming the Arduino Board with Inputs and Outputs on IO Shield Installing RichShield Library Passive Buzzer 4-digit 7-segment Display DHT11, Temperature and Humidity Sensor NTC, Temperature Sensor (Optional) IR Receiver and IR Remote Transmitter (Optional) In this lab, you will learn how to program the other input and output devices on the RichShield. You will need to install the RichShield libraries which provide some useful functions and examples to help you in programing these input and output devices more easily and you do not have to write too much code to complete the project. Installing the RichShield Library Step1: Download the “RichShield” zipped file from Brightspace (under Practical Session Resources). Step2: Open Sketch menu, choose "Include Library" > "Add.ZIP Library...". Step3: Add the “RichShield.zip” file in your Downloads folder (from step 1). School of EEE Lab and Project Guide Page 20 Introduction to Engineering Programming Lab and Project Guide 3. Programming the Passive Buzzer //Numbering continues from Lab Experiment 2 Part1 Introduction A buzzer is a basic audio device that generates a sound from an incoming electrical signal. An active buzzer generates the sound itself. You basically just turn it on or off. A passive buzzer, on the other hand, needs a signal source that generates the sound. The buzzer in the RichShield is a passive buzzer which is connected to pin 3, one of the PWM pins of Arduino Uno. You will learn how to use the Example program, L2_Buzzer_PlayTone and modify it to play other simple songs and activate the buzzer to produce tones of different frequencies. Essential program lines and statements needed to program the Buzzer: a. Include the "RichShieldPassiveBuzzer.h" header file to control the buzzer more easily. This header file contains the definition of a class type named as PassiveBuzzer. #include "RichShieldPassiveBuzzer.h" Notes: A class is a user-defined type that describes what a certain type of object will look like. A class is a blueprint for creating objects, providing initial values for data (member data 1 variables or attributes), and implementations of behaviour (member functions or data.. methods). function 1 An object is a single instance of a class. You can create as many as possible objects from the same class type. function.. b. Create an object of PassiveBuzzer class and set the buzzer pin. Example as follows: PassiveBuzzer buz(PassiveBuzzerPin); c. The object created can then be used to access the member function: void playTone(long note, long millisecond); // This member function has been defined in the PassiveBuzzer class //The 1st parameter, note is the frequency of the tone, unit is Hz; //The 2nd parameter, millisecond is the duration of this tone to be played, unit is ms. //long is a type of integer data. Its size is 4 Bytes when used in Arduino Programming. School of EEE Lab and Project Guide Page 21 Introduction to Engineering Programming Lab and Project Guide The line below shows how the object, buz calls the member function, playTone() to produce a tone of frequency (value stored in array element, Tiger[thisNote] ) for a duration (value stored in noteDuration variable): buz.playTone ( Tigers[thisNote], noteDuration ); dot operator: It’s used to access the member function, playTone() from an object named as buz. Activities 3.1 Launch Arduino IDE. 3.2 Open the RichShield Example program via File > Examples > RichShield > Basic > L2_Buzzer_PlayTone. 3.3 Connect your Arduino board, upload and run the program. "L2_Buzzer_PlayTone" program is shown in the following page for reference. School of EEE Lab and Project Guide Page 22 Introduction to Engineering Programming Lab and Project Guide #include "RichShieldPassiveBuzzer.h" #define PassiveBuzzerPin 3 //the signal pin of the module is connected with pin 3 of OPEN-SMART UNO R3 PassiveBuzzer buz(PassiveBuzzerPin);//create PassiveBuzzer type of object and initialize its pin No. //------------------------------------ //This is a macro definition of bass, midrange, and treble frequencies #define NOTE_L1 262 #define NOTE_L2 294 #define NOTE_L3 330 #define NOTE_L4 349 #define NOTE_L5 392 #define NOTE_L6 440 #define NOTE_L7 494 #define NOTE_M1 523 #define NOTE_M2 587 #define NOTE_M3 659 #define NOTE_M4 698 #define NOTE_M5 784 #define NOTE_M6 880 #define NOTE_M7 988 Interesting Note: Function prototype of #define NOTE_H1 1046 #define #define NOTE_H2 NOTE_H3 1175 1318 sing() is not found in the example program. #define NOTE_H4 1397 #define NOTE_H5 1568 #define NOTE_H6 1760 #define NOTE_H7 1976 //------------------------------------------- //musical notation of Two Tiger const static int Tiger[] = { //original array name is doubleTiger in the RichShild example program NOTE_M1,NOTE_M2,NOTE_M3,NOTE_M1, NOTE_M1,NOTE_M2,NOTE_M3,NOTE_M1, NOTE_M3,NOTE_M4,NOTE_M5, NOTE_M3,NOTE_M4,NOTE_M5, NOTE_M5,NOTE_M6,NOTE_M5,NOTE_M4, NOTE_M3,NOTE_M1, NOTE_M5,NOTE_M6,NOTE_M5,NOTE_M4, NOTE_M3,NOTE_M1, NOTE_M2,NOTE_L5, NOTE_M1,0, NOTE_M2,NOTE_L5, NOTE_M1,0 }; //------------------------------------------- //note duration of Two Tigers, 2 is half a beat, 1 is a beat. const static int tempo[] = { 2,2,2,2, 2,2,2,2, 2,2,1, 2,2,1, 2,2,2,2, 1,1, 2,2,2,2, 1,1, 1,1, 1,1, 1,1, 1,1 }; void setup(void) { sing();//sing the tunes } void loop() { } void sing() { // iterate over the notes of the melody: int size = sizeof(Tiger) / sizeof(int); for (int thisNote = 0; thisNote < size; thisNote++) { int noteDuration = 500 / tempo[thisNote];//a beat for 0.5 second buz.playTone(Tiger[thisNote], noteDuration); // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 0.30; delay(pauseBetweenNotes); } } School of EEE Lab and Project Guide Page 23 Introduction to Engineering Programming Lab and Project Guide Notes on Function Prototypes in Arduino Programs Function prototypes are not strictly required in Arduino programs, but they are recommended. Arduino uses a simplified version of C++ programming language, and in C++, it's good practice to declare function prototypes before using them in the code. Function prototypes help the compiler understand the function's signature (return type, name, and parameter types) before it encounters the actual function definition. While the Arduino IDE (Integrated Development Environment) allows you to write code without function prototypes, it's advisable to include them for several reasons:  Readability: Function prototypes at the beginning of your sketch provide a quick overview of the functions used in your program, making it easier for others (and yourself) to understand the code.  Error Prevention: Prototypes help catch errors early. If there's a mismatch between the actual function definition and its usage, the compiler will generate an error, alerting you to the issue.  Forward Declarations: Prototypes act as forward declarations, allowing you to define functions in any order within your sketch. This can be useful when you have functions calling each other. LAB2 Practice 3A : Create your song and play it with Passive Buzzer (Optional based on your project needs) Study the "L2_Buzzer_PlayTone" program and modify it to play a different simple song. School of EEE Lab and Project Guide Page 24 Introduction to Engineering Programming Lab and Project Guide LAB2 Practice 3B : Play Buzzer tone for Traffic Light System (Optional based on your project needs) Write a program to simulate a traffic light system using one button (connected to pin 8), three LEDs (green LED connected to pin 5, yellow LED connected to pin 7 and red LED connected to pin 4), and a passive buzzer (connected to pin 3). When the button is pressed, the following sequence of operations should occur: 1. The normally ON green LED turns OFF after a delay of 1.5 seconds. 2. The yellow LED turns ON for 1.5 seconds. 3. The red LED turns ON for 4 seconds, accompanied by the buzzer producing a 1-tone sound for the same duration. 4. After the red LED and buzzer sequence, the green LED turns ON again. Design the block diagram and flowchart first before coding. //Hints for the main operations as follows: if (digitalRead(8) == ){ delay(1500); digitalWrite(LED_GREEN, LOW); digitalWrite(LED_YELLOW, HIGH); delay(1500); digitalWrite(LED_YELLOW, LOW); digitalWrite(LED_RED, HIGH); for (int i = 0; i < ; i++){ buz.playTone(392, 100); delay(100); } } else{ digitalWrite(LED_GREEN, ); digitalWrite(LED_YELLOW, ); digitalWrite(LED_RED, ); } Once you get your program working, make some improvement by implementing the program with user defined function(s). Notes: 1. Ensure that these lines are at the top of your program #include "RichShieldPassiveBuzzer.h" #define PassiveBuzzerPin 3 PassiveBuzzer buz(PassiveBuzzerPin); 2. Frequency range of passive buzzer in Arduino plugin richShield: 50 ~ 14,000 Hz School of EEE Lab and Project Guide Page 25 Introduction to Engineering Programming Lab and Project Guide 4. Programming the 4-digit 7-segment Display Introduction The bare 4-digit 7-segment displays usually require 12 connection pins. But the TM1637 IC, a 7-segment LED driver, is mounted on the back of the display module, which reduces the total wire to 4. Two pins are required for the power connections (Vcc and Gnd) and the other two pins are used to control the segments (CLK pin and DIO data pin) The CLK pin is connected to pin 10 and DIO pin is connected to pin 11 of the UNO or its compatible board. You will learn how to display numbers, which can be displayed in bits, or you can display integers directly by using the functions provided by the RichShield library. Essential program lines and statements needed to program the 4-Digit 7-Segment Display: a. Include library header file: #include "RichShieldTM1637.h" b. #define CLK 10 //CLK of the TM1637 IC connected to D10 of OPEN-SMART UNO R3 #define DIO 11 //DIO of the TM1637 IC connected to D11 of OPEN-SMART UNO R3 c. Create an object of TM1637 class and set the pins used. TM1637 disp(CLK,DIO); d. Initialize the 4-Digit 7-Segment display in the setup() disp.init(); e. The disp object created can then be used to access other member functions as listed below. S/N TM1637 class member functions Descriptions and usage (where disp is an object of TM1637 class) 1 disp.init(); Initialize the 4-Digit 7-Segment display. It should be included in the setup function to initialize it. 2 disp.display(int8_t DispData []); Display the numbers in the array of up to 4 elements. int8_t means signed integer type with width of exactly 8 bits and using 2's complement for negative values. For example, the array is {1,2,3,4}, then show 1234 3 disp.display(uint8_t BitAddr, Bit by bit to display numbers, characters. int8_t DispData); BitAddr range is 0 to 3, uint8_t means unsigned 8-bit integer type. Parameter DispData range is 0 to 19 which represents 0 to 9, A, b, c, d, E, F, -, space, H and U e.g. disp.display(0, 10); will display ‘A’ at the left most digit 4 disp.display(int Decimal); Display range: -999 to 9999 5 disp.display(double Decimal); Display a floating-point value School of EEE Lab and Project Guide Page 26 Introduction to Engineering Programming Lab and Project Guide 6 disp.set(uint8_t brightness); Set the brightness, 0 to 7, the greater the value, the higher the brightness. The next display takes effect 7 disp.point(0); Turn off the display colon and the next display takes effect (applicable for the clock type display with a colon at the middle of the display) 8 disp.point(1); Turn on the display colon and the next display takes effect (applicable for the clock type display with a colon at the middle of the display) 9 disp.clearDisplay(); Clear the display or nothing display Note: The above table shows TM1637 class has 4 display member functions, but each display function has different parameter list. This is called function overloading. Activities 4.1 Launch Arduino IDE. 4.2 Open the RichShield Example program via File > Examples > RichShield > Basic > L4_Display. 4.3 Connect your Arduino board and upload the program to run it. 4.4 Study the program and learn how to use the disp.display() function. // "L4_Display" program #include "RichShieldTM1637.h" #define CLK 10 //CLK of the TM1637 IC connected to D10 of OPEN-SMART UNO R3 #define DIO 11 //DIO of the TM1637 IC connected to D11 of OPEN-SMART UNO R3 TM1637 disp(CLK,DIO); // create TM1637 class object disp, initialize its pins for clock and data void setup(){ disp.init(); } void loop(){ int8_t ListDisp = {3,4,5,6}; //declare and initialize array ListDisp with int type elements 3, 4, 5, 6 disp.display(ListDisp); delay(1000); disp.display(-100); delay(1000); disp.display(256); delay(1000); disp.display(1.234); delay(1000); } School of EEE Lab and Project Guide Page 27 Introduction to Engineering Programming Lab and Project Guide LAB2 Practice 4 : Count-down Display for Traffic Light System (Optional based on your project needs) Upgrade Practice 3B with a countdown feature as follows: When the red LED is activated, introduce a digital countdown display from 20 to 0. Each number change triggers a 100ms tone and a 300ms delay. Once countdown completes, the system reverts to its normal state with the green LED illuminated. Subsequently, the program will monitor the button input, and upon activation, it will trigger the sequence to turn on the red LED and initiate the countdown once again." Before you start coding, draw the block diagram and flowchart. Implement your program with user defined function. School of EEE Lab and Project Guide Page 28 Introduction to Engineering Programming Lab and Project Guide 5. Programming DHT11, Temperature and Humidity Sensor Introduction DHT11 is a single wire digital humidity and temperature sensor, which gives relative humidity (RH) in percentage and temperature in degree Celsius. It can be easily interfaced with any micro-controller such as Arduino, Raspberry Pi, etc., to measure humidity and temperature instantaneously. It provides humidity value in percentage in relative humidity (20 to 80% RH with 5% accuracy) and temperature values in degree Celsius (0 to 50 °C with a 2-degree accuracy). The sampling rate of this sensor is 1 Hz. This sensor is used in various applications such as measuring humidity and temperature values in heating, ventilation and air conditioning systems. Weather stations also use these sensors to predict weather conditions. Offices, cars, museums, greenhouses and industries use this sensor for measuring humidity values and as a safety measure. The data pin of DHT11 on the IO Shield is connected to digital pin 12 of Uno or its compatible board. Essential program lines and statements needed to read the temperature and humidity values with the use of the library functions: a. Include library header file. #include "RichShieldDHT.h" b. Create an object of DHT class. The data pin is set to pin 12 by default in the class definition. DHT dht; c. Initialize dht in the setup(): dht.begin(); d. The dht object created can then be used to access other member functions as listed in the following page: School of EEE Lab and Project Guide Page 29 Introduction to Engineering Programming Lab and Project Guide DHT class member functions and Descriptions usage (where dht is an object of DHT class) dht.begin(); Initialize DHT11. It should be included in the setup function to initialize it. t=dht.readTemperature(); Get the temperature value, and return a floating-point number (of type float) //where t is a variable of type float Use of float data type saves memory by half compared to that of double data type. (float requires 4 bytes while double needs 8 bytes to store the value) h=dht.readHumidity(); Get the humidity value, and return a floating-point //where h is a variable of type float number (of type float) Activities 5.1 Launch Arduino IDE. 5.2 Open the RichShield Example program via File > Examples > RichShield > Advanced > L11_DHT11. 5.3 Connect your Arduino board and upload the program to run it. 5.4 Study the code and learn how to program the DHT11 sensor. #include "RichShieldDHT.h" #include "RichShieldTM1637.h" #define CLK 10 //CLK of the TM1637 IC connect to D10 of OPEN-SMART UNO R3 #define DIO 11 //DIO of the TM1637 IC connect to D11 of OPEN-SMART UNO R3 TM1637 disp(CLK,DIO); // create TM1637 class object disp and initialize its pins for clock and data DHT dht; // create DHT class object dht with data pin set to pin 12 by default in the DHT class void setup() { disp.init(); dht.begin(); } School of EEE Lab and Project Guide Page 30 Introduction to Engineering Programming Lab and Project Guide void loop() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); float t = dht.readTemperature(); //Check if the functions above return valid values, if they are nan (not a number), then something went wrong! if (isnan(t) || isnan(h)){ displayError(); //call user defined function displayError() to display error, its design is at the end of code } else{ displayTemperature((int8_t)t); user defined functions delay(3000); //delay to let the temperature shown for a while displayHumidity((int8_t)h); delay(2000); //delay to let the humidity shown for a while } } void displayTemperature(int8_t temperature){ int8_t temp; if(temperature < 0){ temp = INDEX_NEGATIVE_SIGN; temperature = abs(temperature); } else{ if(temperature < 100) temp = INDEX_BLANK; else temp = temperature/100; } temperature %= 100; temp = temperature / 10; temp = temperature % 10; temp = 12; // 12 represents 'C' for displaying celsius degree symbol. disp.display(temp);//disp object calls TM1637 class member function to display numbers stored in temp array } void displayHumidity(int8_t humi){ int8_t temp; if(humi < 100) temp = INDEX_BLANK; else temp = humi/100; humi %= 100; temp = humi / 10; temp = humi % 10; temp = 18; //18 represents 'H' just for displaying a symbol for humidity. disp.display(temp);//disp object calls TM1637 class member function to display numbers stored in temp array } void displayError(){ disp.display(3,14); } School of EEE Lab and Project Guide Page 31 Introduction to Engineering Programming Lab and Project Guide LAB2 Practice 5A : Using Serial Plotter in Arduino IDE (Optional based on your project needs) In this practice, you will learn how to use Serial Plotter in Arduino IDE to monitor the temperature and humidity values. From the same program above, Initialize Serial Communication using Serial.begin() in setup(); Send Data to Serial Monitor  Use Serial.print() or Serial.println() to send the sensor data to Serial Monitor  Use a specific format (e.g. comma-separated values) for multi-value plotting. The necessary lines to add to the program are highlighted below for plotting both the temperature and humidity values. Open Serial Monitor via Tools > Serial Monitor Open Plotter via Tools > Serial Plotter void setup() { disp.init(); dht.begin(); Serial.begin(9600); } void loop() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); float t = dht.readTemperature(); // check if returns are valid, if they are NaN (not a number) then something went wrong! if (isnan(t) || isnan(h)) { displayError(); } else{ displayTemperature((int8_t)t);// delay(3000); displayHumidity((int8_t)h);// Serial.print(t); Serial.print(","); Serial.println(h); delay(2000); } } School of EEE Lab and Project Guide Page 32 Introduction to Engineering Programming Lab and Project Guide Both the Temperature (Value 1) graph and the Humidity (Value 2) graph are generated as shown below: Refer to the reference below for further details. https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-serial-plotter/ School of EEE Lab and Project Guide Page 33 Introduction to Engineering Programming Lab and Project Guide LAB2 Practice 5B : Environmental Control with DHT, Temperature and Humidity Sensor (Optional based on your project needs) From the graphs, you would know roughly the range of temperature and humidity values at the time and place of experimenting with the DHT sensor. Based on the range of values, add in some control in your program, e.g. if the temperature is >32 °C (by applying some heat on the DHT), it will turn on the green LED (to simulate turning on a cooling fan) till the temperature drops to 32 °C or below. You can also add other controls depending on your application, e.g. when the relative humidity is > 90, it will turn on the blue led (to simulate turning on a dehumidifier) till the relative humidity drops to 90 or below. Before you start coding, draw the block diagram and flowchart. Implement your program with user defined function. Hints: #define HIGHTEMP XX //set XX value based on your environment.. If (t > HIGHTEMP) digitalWrite(LED_GREEN, HIGH); else digitalWrite(LED_GREEN, LOW); School of EEE Lab and Project Guide Page 34 Introduction to Engineering Programming Lab and Project Guide 6. Programming NTC, Temperature Sensor (Optional) Introduction NTC refers to a type of temperature sensor, an NTC thermistor. NTC stands for "Negative Temperature Coefficient". NTC thermistors are resistors with a negative temperature coefficient, which means that the resistance decreases with increasing temperature. This type of Temperature sensors can be found in every day appliances such as fire alarms, ovens and refrigerators. They are also used in digital thermometers and in many automotive applications to measure temperature. The signal pin of NTC temperature sensor on the IO Shield is connected to analog pin A1 of Uno or its compatible board. Essential program lines and statements needed to read the temperature values with the use of the library functions: a. Include library header file. #include "RichShieldNTC.h" //This header file contains definition of a class named as NTC b. Define NTC_Pin which is A1 and create an object of NTC class. #define NTC_PIN A1 //Define the pin, A1 that is connected to NTC sensor. NTC temper(NTC_PIN); //Create an object named ‘temper’ of the NTC class. The temper object created can then be used to access the member function as listed below: NTC class functions and usage Descriptions (where temper is an object of NTC class) celsius = temper.getTemperature(); Get the temperature value, and return a floating-point number (of type float) //where celsius is a variable of type float This value is internally converted by the member function from a resistance value to a temperature value in degree Celsius Activities 6.1 Launch Arduino IDE. 6.2 Open the RichShield Example program via File > Examples > RichShield > Basic > L7_Temperature_Display. 6.3 Connect your Arduino board and upload the program to run it. 6.4 Study the code and learn how to program the NTC sensor. 6.5 You may practice plotting a graph of temperature readings for monitoring purpose and/or modify the program to do certain temperature control based on your program applications. School of EEE Lab and Project Guide Page 35 Introduction to Engineering Programming Lab and Project Guide 7. Programming IR Receiver with an IR Remote Transmitter (Optional based on your project needs) IR Trasmitter IR Receiver Introduction Infrared radiation is a form of light similar to the light we see all around us. The only difference between IR light and visible light is the frequency and wavelength. Infrared radiation lies outside the range of visible light, so humans can’t see it: Because IR is a type of light, IR communication requires a direct line of sight from the receiver to the transmitter. It can’t transmit through walls or other materials like WiFi or Bluetooth. Infrared (IR) communication is a widely used and easy to implement wireless technology that has many useful applications. The most prominent examples in day to day life are TV/video remote controls. A typical infrared communication system requires an IR transmitter and an IR receiver. The transmitter looks just like a standard LED, except it produces light in the IR spectrum instead of the visible spectrum. With an IR receiver connected to Digital pin 2 of UNO (or its compatible board) and a remote keypad controller with a built-in IR transmitter, you can do projects involving remote control of things (e.g. simulating home appliances) connected to the Arduino. Essential program lines and statements needed to read the temperature values with the use of the library functions: a. Include library header file. #include "RichShieldIRremote.h" b. Define RECV_PIN (IR Receiver Signal Pin) which is connected to pin 2 of UNO (or its compatible board) and create an object of IRrecv class. #define RECV_PIN 2 IRrecv IR(RECV_PIN); School of EEE Lab and Project Guide Page 36 Introduction to Engineering Programming Lab and Project Guide c. Enable or Start the IR receiver in the setup() IR.enableIRIn(); // IR object calls IRrecv class member function enableIRIn() to start the receiver The IR object created can then be used to access other member function as listed below: IRrecv class Functions and usage Descriptions (where IR is an object of IRrecv class) IR.enableIRIn(); Start or enable the IR receiver in setup () IR.decode(); If no result, it returns 0, otherwise it returns 1. IR.resume(); Resume to receive again. Run this statement so that it can receive the next value. IR.isReleased(); if the button is not released yet, it returns 0; otherwise (when it is released), it returns 1; Other useful information: 1. There are 20 keys in the keypad. 2. Each key is encoded and defined in the key code table in the "RichShieldIRremote.h" header file. #define KEY_POWER 0x45 #define KEY_MENU 0x47 #define KEY_TEST 0x44 #define KEY_PLUS 0x40 #define KEY_BACK 0x43 #define KEY_PREV 0x07 #define KEY_PLAY 0x15 #define KEY_NEXT 0x09 #define KEY_ZERO 0x16 #define KEY_MINUS 0x19 #define KEY_C 0x0D #define KEY_ONE 0x0C #define KEY_TWO 0x18 #define KEY_THREE 0x5E #define KEY_FOUR 0x08 #define KEY_FIVE 0x1C #define KEY_SIX 0x5A #define KEY_SEVEN 0x42 #define KEY_EIGHT 0x52 #define KEY_NINE 0x4A 3. To read the code of the key pressed and received by the IR receiver, simply access the member variable of the IR object, IR.keycode of unsigned char data type. School of EEE Lab and Project Guide Page 37 Introduction to Engineering Programming Lab and Project Guide Activities 7.1 Launch Arduino IDE. 7.2 Open the RichShield Example program via File > Examples > RichShield > Advanced > L13_IR_Control_Display. 7.3 Connect your Arduino board and upload the program to run it. 7.4 Study the code reproduced below for your reference. #include "RichShieldTM1637.h" #include "RichShieldIRremote.h" #include "RichShieldPassiveBuzzer.h" #define PassiveBuzzerPin 3 //the SIG pin of the module is connected with D3 of UNO board //There is no white waterproof sticker on the passive buzzer PassiveBuzzer buz(PassiveBuzzerPin); //Create PassiveBuzzer type object buz and set the buzzer pin #define RECV_PIN 2 //the SIG pin of Infrared Receiver is connected with D2 of UNO board IRrecv IR(RECV_PIN); //Create IRrecvtype type object IR and initialise the IR receiver pin to pin 2 #define CLK 10 //CLK of the TM1637 IC connect to D10 of Arduino #define DIO 11 //DIO of the TM1637 IC connect to D11 of Arduino TM1637 disp(CLK,DIO); // create TM1637 type object disp and initialize its pins for clock and data unsigned char num = 0; void setup(){ disp.init(); // disp object calls TM1637 class member function, init() to initialize the 7-Segment display IR.enableIRIn(); // IR object calls IRrecv class member function, enableIRIn() to start the receiver } void loop(){ if (IR.decode()){ if(IR.isReleased()) { buz.playTone(2500,50); switch(IR.keycode){ case KEY_ZERO: num = 0;break; case KEY_ONE: num = 1;break; case KEY_TWO: num = 2;break; case KEY_THREE: num = 3;break; case KEY_FOUR: num = 4;break; case KEY_FIVE: num = 5;break; case KEY_SIX: num = 6;break; case KEY_SEVEN: num = 7;break; case KEY_EIGHT: num = 8;break; case KEY_NINE: num = 9;break; case KEY_PLUS: num = num+1;break; case KEY_MINUS: num = num-1;break; default: break; } disp.display(num); delay(100); //delay 100 ms to show the display value } IR.resume(); //Receive the next value } } School of EEE Lab and Project Guide Page 38 Introduction to Engineering Programming Lab and Project Guide LAB2 Practice 6 : Remote Control to ON/OFF Devices (Optional based on your project needs) Write a program with a remote control (via the IR transmitter keypad control) to turn on/off some devices. For example, press ‘1’ to turn on and ‘2’ to turn off the yellow LED. Press ‘4’ to turn on and ‘5’ to turn off the blue LED. Press ‘7’ to turn on and ‘8’ to turn off both LEDs. Before you start coding, draw the block diagram and flowchart. Implement your program with user defined function. School of EEE Lab and Project Guide Page 39 Introduction to Engineering Programming Appendix Appendix A Common C++ Operators: Precedence and Associativity OPERATORS TYPE ASSOCIATIVITY () []. Groups left to right ! ~ ++ -- Unary right to left * / % Multiplicative left to right + - Additive left to right > Shift left to right < > = Relational left to right == != Equality left to right & ^ Bitwise left to right | && Logical left to right || = += -= *= /= Assignment right to left School of EEE Page A1 Introduction to Engineering Programming Appendix Appendix B --- Standard ASCII Table School of EEE Page A2 Introduction to Engineering Programming Appendix Appendix C --- Common C++ Keywords ( to be continued) School of EEE Page A3 Introduction to Engineering Programming Appendix Appendix C --- Common C++ Keywords (continued) School of EEE Page A4 Introduction to Engineering Programming Lab and Project Guide Appendix Appendix A -- Arduino Uno and Rich Shield Pinout Configurations Arduino Uno Pinout Configuration Pin Category Pin Name Details Power Vin, 3.3V, 5V, GND Vin: Input voltage to Arduino when using an external power source. 5V: Regulated power supply used to power microcontroller and other components on the board. 3.3V: 3.3V supply generated by on-board voltage regulator. Maximum current draw is 50mA. GND: ground pins. Reset Reset Resets the microcontroller. Analog Pins A0 – A5 Used to provide analog input in the range of 0-5V Input/Output Pins Digital Pins 0 - 13 Can be used as input or output pins. Serial 0(Rx), 1(Tx) Used to receive and transmit TTL serial data. External Interrupts 2, 3 To trigger an interrupt. PWM 3, 5, 6, 9, 11 Provides 8-bit PWM output. SPI 10 (SS), 11 (MOSI), 12 (MISO) Used for SPI communication. and 13 (SCK) Inbuilt LED 13 To turn on the inbuilt LED. TWI A4 (SDA), A5 (SCA) Used for TWI communication. AREF AREF It is a reference INPUT voltage used by the A/Ds Rich Shield Pinout configuration Analog pins Digital pins // ~ denotes PWM pins A0 Blue Knob/potentiometer 0 Rx A1 NTC Temperature Sensor 1 Tx A2 LDR 2 IR Receiver A3 External voltage Source 3~ Buzzer (Voltage Divider) 4 LED1 (Red) 180k/(180+820)k = 0.18 ratio 5~ LED2 (Green) 6~ LED3 (Blue) A4 SDA (Connect to EEPROM 24C02ASN) 7 LED4 (Yellow) A5 SCL (Connect to EEPROM 24C02ASN) 8 KEY0 (K1) 9~ KEY1 (K2) 10 CLK (for LED Drive Control Special Circuit TM1637) 11~ DIO (For TM1637) 12 DHT 13 Uno Inbuilt LED School of EEE Lab and Project Guide Appendix Page 1 Introduction to Engineering Programming Lab and Project Guide Appendix Appendix B -- Useful Program Codes for Rich Shield IO Components //LEDs //pinMode setting in setup() //Related functions #define LED_RED 4 pinMode(LED_RED, OUTPUT); digitalWrite(ledPin,HIGH); #define LED_GREEN 5 pinMode(LED_GREEN, OUTPUT); digitalWrite(ledPin,LOW); #define LED_BLUE 6 pinMode(LED_BLUE, OUTPUT); analogWrite(PWMPin, value); #define LED_YELLOW 7 pinMode(LED_YELLOW, OUTPUT); PWM pins connection in RichShield D3~ Buzzer D5~ LED2 (Green) D6~ LED3 (Blue) D9~ KEY1 (K2) D11~ DIO (For TM1637) //Buttons //pinMode setting in setup() buttonState=digitalRead(buttonPin); //where buttonState can be 0 or 1 #define BUTTONK1 8 pinMode(BUTTONK1, INPUT_PULLUP); #define BUTTONK2 9 pinMode(BUTTONK2, INPUT_PULLUP); //Analog Sensors: Knob and LDR #define KNOB_PIN A0 int knobValue; #define LDR_PIN A2 int ldrValue; // to store the analog read value from LDR sensor. inputValue=analogRead(analogPin); //where inputValue can be from 0 to 1023 //Passive Buzzer #include "RichShieldPassiveBuzzer.h" #define PassiveBuzzerPin 3 PassiveBuzzer buz(PassiveBuzzerPin); //4-digit display #include "RichShieldTM1637.h" #define CLK 10 #define DIO 11 disp.init(); TM1637 disp(CLK, DIO); //For NTC #include "RichShieldNTC.h" #define NTC_PIN A1 //NTC Temperature Sensor NTC temper(NTC_PIN); //For DHT //Initialize DHT11 in setup() #include "RichShieldDHT.h" dht.begin(); DHT dht; //For IR Receiver //Start or enable the IR receiver in setup() #include "RichShieldIRremote.h" IR.enableIRIn(); // Enable the IR receiver #define RECV_PIN 2 IRrecv IR(RECV_PIN); School of EEE Lab and Project Guide Appendix Page 2 Introduction to Engineering Programming Lab and Project Guide Appendix Appendix C -- Data Types for Arduino in C++ C++ used for Arduino is a subset of standard C/C++, with additional functionalities related to the hardware features of the board. The main differences between Arduino C++ and standard C++ are in the memory storage. Usually a modern computer has more than 2GB of RAM, while the Arduino Uno has 2kB (1 million times less). The Arduino also uses 8-bit instructions instead of the 32-bit or 64-bit ones a computer uses. This will mainly affect the amount of information you can store in a variable. C++ defines a number of different data types. Below is a list of the data types commonly seen in Arduino. Note: signed variables allow both positive and negative numbers, while unsigned variables allow only non-negative values. Arduino Data Size Value Ranges Types in Bytes boolean 1 true (1) or false (0) char 1 signed number from -128 to 127. The compiler will attempt to interpret this data type as a character in some circumstances, which may yield unexpected results unsigned char, 1 unsigned number from 0 to 255. These 3 types are the same. byte, uint8_t unsigned int, 2 unsigned number from 0 to 65535. These 3 types are the same. word, uint16_t int 2 signed number from -32768 to 32767. This is most commonly what you see used for general purpose variables in Arduino example code provided with the Arduino IDE long 4 signed number from -2,147,483,648 to 2,147,483,647 unsigned long, 4 unsigned number from 0 to 4,294,967,295. uint32_t The most common usage of this is to store the result of the millis() function, which returns the number of milliseconds the current code has been running. float 4 signed number from -3.4028235E38 to 3.4028235E38. Floating point on the Arduino is not native; the compiler has to jump through hoops to make it work. If you can avoid it, you should. School of EEE Lab and Project Guide Appendix Page 3 Introduction to Engineering Programming Lab and Project Guide Appendix Appendix D -- Flowchart Symbol for Software Design Flowchart Symbol Purpose Description Indicates the flow of logic by Flow line connecting symbols. Represents the start and the Terminal(Stop/Start) end of a flowchart. Used for input and output Input / Output operation. Used for arithmetic Processing operations and data- manipulations. Used for decision making Decision between two or more alternatives. Represents a group of Predefined statements performing one Process/Function processing task. Used to join different On-page Connector flowline Used to connect the Off-page Connector flowchart portion on a different page. School of EEE Lab and Project Guide Appendix Page 4 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub Learning Guide for Introduction to Git & GitHub Content: 1. What is Version Control? 2. What is Git and GitHub? 3. What is GitHub Desktop? 4. Getting Started with GitHub and GitHub Desktop 5. How to commit changes and publish your repository into GitHub? 6. Illustration of making changes to your file, Commit and Push the changes into GitHub? 1. What is Version Control? Version control is a system that helps track changes to a project over time. Version control systems are software tools that help software teams manage changes to source code over time. 2. What is Git and GitHub? Git is a popular version control system that enables efficient tracking of changes. It allows developers to track changes, create branches for different features, and collaborate seamlessly. GitHub, on the other hand, is a web-based platform that uses Git for version control. It provides a place to host your Git repositories (collections of code) and adds a bunch of features on top. In essence, Git is the tool, and GitHub is a platform that makes using Git easier and more collaborative. There are other platforms like GitLab and Bitbucket that also use Git, but GitHub is one of the most popular ones. 3. What is GitHub Desktop? GitHub Desktop is a free, open source application that helps you to work with code hosted on GitHub or other Git hosting services. With GitHub Desktop, you can perform Git commands, such as committing and pushing changes, in a graphical user interface, rather than using the command line. 4. Getting Started with GitHub and GitHub Desktop 4.1 Sign Up for GitHub Go to www.github.com, enter your ichat email and click on “Sign up for GitHub“ button, if you do not have any GitHub account. School of EEE Learning Guide Appendix Git & GitHub Page 1 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub 4.2 Download & Install GitHub Desktop Go to https://desktop.github.com/. Download and install the GitHub desktop application. 4.3 Click “Sign in to GitHub.com” and sign in with the account that you just created. 4.4 Configure Git Enter your name and email used when you signed up for GitHub. This is used to identify the commits you create. Anyone will be able to see this information if you publish commits. School of EEE Learning Guide Appendix Git & GitHub Page 2 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub 4.5 Create New Repository A repository is basically your project. It contains all the files, including the revision history. (i) Click “Create a New Repository on your hard drive…”. A new window will pop up. Fill up the name, description and choose a folder on your Laptop local drive for the repository. Then click “Create repository” button. (ii) After creating the repository, the screen on Desktop application will change to below. Then go to your laptop C: drive to check that the repository is created. School of EEE Learning Guide Appendix Git & GitHub Page 3 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub 4.6 Add New File to the Repository (i) Add a file, e.g. Ex5_Q5.cpp to the folder. (ii) Once you add a new file into the repository folder in your laptop, the GitHub Desktop application will show all the changes. School of EEE Learning Guide Appendix Git & GitHub Page 4 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub 5. How to Commit Changes and Publish Your Repository into GitHub? As you make changes to your project, you "commit" those changes. This is like saving a snapshot of your project at that moment. A commit is a record of what changes you have made since the last time you made a commit. Essentially, you make changes to your repository (for example, adding a file or modifying one) and then tell git to put those changes into a commit. Commits make up the essence of your project and allow you to jump to the state of a project at any other commit. 5.1 Continue from above step, add a description of the changes before you click “Commit to main”. 5.2 Desktop application will change to the following. Click “Publish Repository” School of EEE Learning Guide Appendix Git & GitHub Page 5 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub 5.3 This repository will be published to www.github.com. Please make sure you remember the name of the repository and check “Keep this code private”. 5.4 Visit www.github.com and find the repository you just created. And you will see something similar like the screenshot below. This means that your project is successfully stored on GitHub. 6. Illustration of making changes to your file, Commit and Push the changes into GitHub? You will use a command in Github Desktop, called "Push origin" to upload your local repository content to a remote repository (i.e. Github). In Git, "origin" is the default name given to the remote repository from which your local repository was cloned. When you push changes to the "origin" repository, you are essentially synchronizing your local repository's changes with the remote repository. To illustrate how to push changes to Github, go back to your local machine (i.e. your laptop) and make some changes to the file inside the repository folder. The changes will be reflected and listed in the GitHub Desktop application. Add a description of the changes. Then you click “Commit to main” and in the next screen click on Push origin and the changes will PUSH to GitHub. School of EEE Learning Guide Appendix Git & GitHub Page 6 Introduction to Engineering Programming Learning Guide Appendix Git & GitHub 6.1 Program in “Ex5_Q5.cpp” has been improved and saved in your local repository. The following shows the improved code. Original Program in Ex5_Q5.cpp //Ex5 Q5 #include using namespace std; int main() { int num; cout > num; for (int i = 1; i

Use Quizgecko on...
Browser
Browser