Lab expts sem 6
AIML
TW1 - DFID
|
|
TW2 - BFS
|
|
TW3 - A* algorithm
|
|
USP
Running a code
We shall use fedora to run most of the code. The code will be written in ANSI C and.
To run the code, we shall use the following commands:
Sample code
In order to compile and run this code open a new instance in the terminal and execute the following commands:
A shorter version to run this code is
|
|
This can be done for same in a c++ file. To initialte a c++ file, use the following command:
|
|
To compile and execute the file run the following commands:
Similarly to the c file to run the command in one single line use the following command:
|
|
Checking the version of posix
|
|
TW1 - runtime constraints in C++
|
|
Output
|
|
TW2 - posix job control
Problem statement: Write a C/C++ compliant program that print the posix defined configuration option supported on any given system using feature kept macros.
|
|
Output
TW3 - hardlink and softlink
Problem statement: Write a c/c++program to generate hardlink and softlink
|
|
Output
|
|
TW4 - file locking
Problem statement: Write a C/C++ progaram to demonstate file locking
|
|
Output
|
|
TW5 - zombie process
Problem statement: Write a C/C++ program that created a zombie and then calls system execute the PS command to verify that the process is zombie
|
|
Output
|
|
TW6 - race condition
Probmem statement: Write a C/C++ program to illustate a race condition
|
|
Output
TW7 - client server
Problem statement: Implementing client server communication using socket programming that uses connection oriented prototcol at transport layer
Server code
|
|
Client code
|
|
Output
|
|
TW8 - NS3
Problem statement: Write a C/C++ program to simulate a network application with 2 nodes using NS2/NS3.
|
|
TW10
Problem statement: Write a C/C++ program to simulate a network application with 4 nodes using NS2/NS3.
|
|
IOT
Format
- Title
- Objective
- Brief Theory
- Interfacing Block Diagram and manual calculations if any
- Algorithm
- Code
- Output (Printout)
- Conclusion
- Course learning outcome
- References
Note: The termworks may be different forr different batches
TW1
- Title: Interfacing LED’s with Arduino - Generating morse code using led’s controlled by arduino
- Objective: The objective of this project is to create a pattern generator using LEDs interfaced with an Arduino, where the user inputs an alphanumeric character via serial input, and the corresponding Morse code is displayed using LED
- Brief theory LEDs (Light Emitting Diodes) are semiconductor devices that emit light when an electric current passes through them. LEDs are widely used in electronic devices for various purposes due to their efficiency, compact size, and low power consumption. In this project, LEDs are employed to visually represent Morse code sequences. Each dot or dash of the Morse code is translated into a corresponding LED blink pattern, allowing users to observe and interpret the transmitted message. By interfacing LEDs with an Arduino microcontroller, we can automate the process of Morse code generation, making it accessible and versatile for educational, communication, or signaling purposes. This project highlights the synergy between digital electronics, communication systems, and human-computer interaction, showcasing how technology can bridge the gap between different modes of communication.
- Interfacing block diagram: Check tinkercad
- Algorithm:
- Receive input character via serial input.
- Convert the character to Morse code.
- Output the Morse code using LEDs.
- Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
// Define the size of the dictionary const int DICTIONARY_SIZE = 26; // Structure to represent a key-value pair struct MorsePair { char key; // English alphabet character const char* value; // Morse code counterpart }; // Array of key-value pairs representing the Morse code dictionary const MorsePair morseDictionary[DICTIONARY_SIZE] = { {'A', ".-"}, {'B', "-..."}, {'C', "-.-."}, {'D', "-.."}, {'E', "."}, {'F', "..-."}, {'G', "--."}, {'H', "...."}, {'I', ".."}, {'J', ".---"}, {'K', "-.-"}, {'L', ".-.."}, {'M', "--"}, {'N', "-."}, {'O', "---"}, {'P', ".--."}, {'Q', "--.-"}, {'R', ".-."}, {'S', "..."}, {'T', "-"}, {'U', "..-"}, {'V', "...-"}, {'W', ".--"}, {'X', "-..-"}, {'Y', "-.--"}, {'Z', "--.."} }; // Define the pin for the LED const int LED_PIN = 13; void setup() { // Initialize Serial communication Serial.begin(9600); // Set LED pin as an output pinMode(LED_PIN, OUTPUT); } void loop() { // Prompt the user to enter a string Serial.println("Enter a string (A-Z):"); // Read the user input while (!Serial.available()); // Wait for input String input = Serial.readStringUntil('\n'); // Read input until newline character // Translate input to Morse code and blink LED accordingly translateAndBlink(input); } // Function to translate a string to Morse code and blink LED void translateAndBlink(String input) { // Iterate through each character in the input string for (int i = 0; i < input.length(); i++) { // Convert character to uppercase char c = toupper(input.charAt(i)); // Find Morse code counterpart in the dictionary const char* morseCode = findMorseCode(c); // Blink LED according to Morse code blinkMorseCode(morseCode); } } // Function to find Morse code for a given character const char* findMorseCode(char c) { for (int i = 0; i < DICTIONARY_SIZE; i++) { if (morseDictionary[i].key == c) { return morseDictionary[i].value; } } return ""; // Return empty string if character not found } // Function to blink LED according to Morse code void blinkMorseCode(const char* morseCode) { for (int i = 0; morseCode[i] != '\0'; i++) { if (morseCode[i] == '.') { digitalWrite(LED_PIN, HIGH); delay(250); // Dot duration digitalWrite(LED_PIN, LOW); delay(250); // Inter-element gap } else if (morseCode[i] == '-') { digitalWrite(LED_PIN, HIGH); delay(750); // Dash duration digitalWrite(LED_PIN, LOW); delay(250); // Inter-element gap } else if (morseCode[i] == ' ') { delay(750); // Inter-character gap } } delay(1250); // Inter-word gap }
- Output: Check here
- Conclusion: This project successfully demonstrates the interfacing of LEDs with an Arduino to generate Morse code patterns corresponding to user-input alphanumeric characters. It illustrates the practical application of Morse code and LED interfacing in educational or communication systems.
- Course learning outcome: Understanding serial communication with Arduino. Implementing logic for character-to-Morse code conversion. Applying digital output to control LEDs.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW2
- Title: Interfacing Arduino with a push button for glowing up the LED
- Objective: The objective of this project is to interface a push button with an Arduino board to control the illumination of an LED. When the push button is pressed, the LED will turn on, and when it is released, the LED will turn off.
- Brief theory
- Push Button: A push button is a momentary switch that completes an electrical circuit when pressed. It is commonly used in electronic projects to provide user input or trigger actions.
- LED (Light Emitting Diode): An LED is a semiconductor device that emits light when current flows through it. It is often used in electronic projects for visual indicators or illumination purposes.
- Arduino: Arduino is an open-source electronics platform based on easy-to-use hardware and software. It consists of a microcontroller board and a development environment for writing and uploading code to the board.
- Interfacing block diagram: Check tinkercad
- Algorithm:
- Initialize the Arduino board and configure the push button and LED pins as inputs and outputs, respectively.
- Continuously monitor the state of the push button.
- If the push button is pressed (input HIGH), turn on the LED by setting its pin to HIGH.
- If the push button is released (input LOW), turn off the LED by setting its pin to LOW.
- Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// constants won't change. They're used here to set pin numbers: const int buttonPin = 12; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin // variables will change: int buttonState = 0; // variable for reading the pushbutton status void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } void loop() { // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. If it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, HIGH); } else { // turn LED off: digitalWrite(ledPin, LOW); } }
- Output: Check here
- Conclusion: This project demonstrates the basic concept of interfacing a push button with an Arduino to control an LED. By understanding how to read digital inputs from a push button and control digital outputs to an LED, users can create interactive systems and prototypes for various applications.
- Course learning outcome
- Understanding of digital input and output operations with Arduino.
- Implementation of push button interfacing techniques for user input.
- Practical application of LED control for visual feedback or illumination.
- Introduction to basic circuit design and prototyping using microcontrollers.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW3
- Title: Interfacing Arduino with a button to simulate a dice roll
- Objective: The objective of this project is to interface a push button with an Arduino to generate and display a random number from 1-6, simulating a dice roll, on a 16x2 LCD display.
- Brief theory: A push button is a momentary switch used to provide user input to microcontroller-based systems. LEDs are used to indicate the result of the simulated dice roll. The Arduino generates random numbers to mimic the rolling of a dice.
- Interfacing block diagram: Check tinkercad
- Algorithm:
- Setup the push button and LED connections.
- Initialize the LCD display.
- Wait for the push button press.
- Generate a random number between 1 and 6.
- Display the number on the LCD.
- Light up LEDs corresponding to the number rolled.
- Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
// C++ code // #include <LiquidCrystal_I2C.h> // defining constants const int buttonPin = 12; const int ledPin = 13; // global variables int buttonState = 0; int die; // defining lcd object LiquidCrystal_I2C lcd_1(32, 16, 2); void setup() { // lcd setup lcd_1.init(); lcd_1.setCursor(0, 0); lcd_1.backlight(); lcd_1.display(); // button setup pinMode(buttonPin, INPUT); // random seed randomSeed(analogRead(0)); // button setup pinMode(ledPin, OUTPUT); } void refreshDisplay(int arg) { lcd_1.clear(); lcd_1.setCursor(0, 0); lcd_1.print(arg); } int rollDice() { // Check if the button is pressed if (digitalRead(buttonPin) == HIGH) { // Generate a random number between 1 and 6 (inclusive) int randomNumber = random(1, 7); refreshDisplay(randomNumber); digitalWrite(ledPin, HIGH); delay(1000); return randomNumber; } else { // If button is not pressed, return -1 as an indication digitalWrite(ledPin, LOW); return -1; } } void loop() { // only for debugging die = rollDice(); Serial.println(die); }
- Output: Check here
- Conclusion: This project effectively demonstrates the integration of push buttons, LEDs, and LCD displays with Arduino to create a simulated dice roll. It serves as a practical example for understanding user input, random number generation, and visual feedback in embedded systems.
- Course learning outcome
- Understanding digital input with Arduino.
- Implementing random number generation.
- Interfacing and controlling LED and LCD displays.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW4
- Title: Interfacing Arduino with SR04 Ultrasonic Sensor for Distance Measurement and buzzer for alert
- Objective: The objective of this project is to create a simulated parking sensor system by interfacing an SR04 ultrasonic sensor with a buzzer. The system aims to detect obstacles in a parking space and provide audible feedback to the user through the buzzer, mimicking the behavior of a real parking sensor.
- Brief theory
- SR04 Sensor: The SR04 is an ultrasonic distance sensor that measures distance by emitting ultrasonic waves and calculating the time it takes for the waves to bounce back after hitting an obstacle. It consists of a transmitter, receiver, and control circuit.
- Buzzer: A buzzer is an electromechanical device that produces sound when an electric current is passed through it. It is commonly used in electronic projects to provide audible alerts or feedback to users.
- Parking Sensor: In real-world applications, parking sensors use ultrasonic sensors to detect nearby obstacles when parking a vehicle. They provide feedback to the driver through visual or audible signals to assist in parking maneuvers.
- Interfacing block diagram: Check tinkercad
- Algorithm
- Initialize the Arduino board and configure the SR04 sensor and buzzer pins.
- Continuously trigger the SR04 sensor to send ultrasonic waves and measure the time it takes for the waves to bounce back.
- Calculate the distance to the nearest obstacle based on the time-of-flight of the ultrasonic waves.
- If an obstacle is detected within a certain threshold distance, activate the buzzer to emit an audible alert.
- Adjust the frequency or intensity of the buzzer based on the proximity of the obstacle to simulate different warning levels.
- Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
const int triggerPin = 6; // Trigger pin of the ultrasonic sensor const int echoPin = 7; // Echo pin of the ultrasonic sensor const int buzzerPin = 9; // Buzzer pin long duration; int distance; void setup() { pinMode(triggerPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(buzzerPin, OUTPUT); Serial.begin(9600); // Initialize serial communication at 9600 bps } void loop() { // Clear the trigger pin digitalWrite(triggerPin, LOW); delayMicroseconds(2); // Set the trigger pin HIGH for 10 microseconds digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); // Read the echo pin, and calculate the distance duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back) Serial.print("Distance: "); Serial.println(distance); // Set buzzer beeping rate based on distance if (distance < 10) { tone(buzzerPin, 1000); // Continuous beep delay(100); // Small delay to avoid overload noTone(buzzerPin); Serial.println("TRIPLE CAUTION, high frequency!!!"); } else if (distance < 20) { tone(buzzerPin, 1000); delay(200); noTone(buzzerPin); delay(200); Serial.println("DOUBLE CAUTION, mid frequency!!!"); } else if (distance < 30) { tone(buzzerPin, 1000); delay(400); noTone(buzzerPin); delay(400); Serial.println("CAUTION, low frequency!!!"); } else if (distance < 50) { tone(buzzerPin, 1000); delay(800); noTone(buzzerPin); delay(800); Serial.println("Appropriate distace, v low frequency!!!"); } else { noTone(buzzerPin); // No beep } delay(1000); // Delay between readings }
- Output: Check here
- Conclusion: This project demonstrates the implementation of a simulated parking sensor system using an SR04 ultrasonic sensor and a buzzer. By interfacing these components with an Arduino board and analyzing sensor data, the system can provide audible feedback to users when obstacles are detected, aiding in parking maneuvers. While this simulation does not replace the functionality of real parking sensors, it serves as an educational and prototyping tool for understanding sensor interfacing and feedback mechanisms.
- Course learning outcomes:
- Understanding of ultrasonic sensor operation and distance measurement.
- Implementation of buzzer control for audible alerts.
- Application of sensor data analysis for obstacle detection.
- Integration of sensor feedback systems with microcontroller-based projects.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW5 (refer this)
Title
Create a Program to Make a Counter Using a 7-Segment Display (Counting from 0-9 and then Back to 0)Objective
To design and implement a program that controls a 7-segment display to function as a counter, incrementing from 0 to 9 and then resetting back to 0, using a USB connection to a computer for power and programming.Brief Theory
A 7-segment display is an electronic display device consisting of seven LEDs (segments) arranged in a rectangular fashion. By illuminating specific segments, it can display decimal numerals and some alphabets. In this project, a microcontroller (such as an Arduino) will be programmed to control the 7-segment display via a USB connection to a computer. The counter will increment from 0 to 9, after which it will reset to 0 and continue counting. This project involves understanding both hardware interfacing and software programming to achieve the desired functionality.Interfacing Block Diagram and manual calculations if any
Check tinkercadAlgorithm
Initialize System
- Set up the microcontroller (e.g., Arduino) with the necessary libraries and configurations.
- Initialize the pins connected to the 7-segment display as outputs.
Display Initialization
- Ensure the 7-segment display is properly initialized to show the number 0 at start.
Counter Logic
- Set an initial counter value to 0.
- Enter a loop to increment the counter value by 1 at regular intervals (eg., every second).
- Update the 7-segment display to show the current counter value.
- If the counter value exceeds 9, reset it to 0.
Loop and Update Display
- Continuously check and update the counter value and display it.
- Implement a mechanism to reset the counter if needed (e.g., via a button press).
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
unsigned const int A = 13; unsigned const int B = 12; unsigned const int C = 11; unsigned const int D = 10; unsigned const int E = 9; unsigned const int F = 8; unsigned const int G = 7; unsigned const int H = 6; void setup(void) { pinMode(A, OUTPUT); pinMode(B, OUTPUT); pinMode(C, OUTPUT); pinMode(D, OUTPUT); pinMode(E, OUTPUT); pinMode(F, OUTPUT); pinMode(G, OUTPUT); pinMode(H, OUTPUT); } //My Functions void zero(void) { digitalWrite(A, LOW); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, HIGH); digitalWrite(E, HIGH); digitalWrite(F, HIGH); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void one(void) { digitalWrite(A, LOW); digitalWrite(B, LOW); digitalWrite(C, LOW); digitalWrite(D, HIGH); digitalWrite(E, LOW); digitalWrite(F, LOW); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void two(void) { digitalWrite(A, HIGH); digitalWrite(B, LOW); digitalWrite(C, HIGH); digitalWrite(D, HIGH); digitalWrite(E, HIGH); digitalWrite(F, HIGH); digitalWrite(G, LOW); digitalWrite(H, LOW); } void three(void) { digitalWrite(A, HIGH); digitalWrite(B, LOW); digitalWrite(C, HIGH); digitalWrite(D, HIGH); digitalWrite(E, LOW); digitalWrite(F, HIGH); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void four(void) { digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, LOW); digitalWrite(D, HIGH); digitalWrite(E, LOW); digitalWrite(F, LOW); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void five(void) { digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, LOW); digitalWrite(E, LOW); digitalWrite(F, HIGH); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void six(void) { digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, LOW); digitalWrite(E, HIGH); digitalWrite(F, HIGH); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void seven(void) { digitalWrite(A, LOW); digitalWrite(B, LOW); digitalWrite(C, HIGH); digitalWrite(D, HIGH); digitalWrite(E, LOW); digitalWrite(F, LOW); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void eight(void) { digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, HIGH); digitalWrite(E, HIGH); digitalWrite(F, HIGH); digitalWrite(G, HIGH); digitalWrite(H, LOW); } void nine(void) { digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, HIGH); digitalWrite(E, LOW); digitalWrite(F, HIGH); digitalWrite(G, HIGH); digitalWrite(H, LOW); } // Start void loop(void) { zero(); delay(1000); one(); delay(1000); two(); delay(1000); three(); delay(1000); four(); delay(1000); five(); delay(1000); six(); delay(1000); seven(); delay(1000); eight(); delay(1000); nine(); delay(1000); }
Output (Printout)
Check hereConclusion
The project successfully demonstrates the use of a microcontroller to control a 7-segment display counter. The counter increments from 0 to 9 and then resets to 0, providing a simple yet effective example of hardware interfacing and programming. This project enhances understanding of both the hardware and software aspects of embedded systems.Course Learning Outcome
- Gain practical experience with microcontroller development boards such as Arduino.
- Learn to interface and control a 7-segment display.
- Develop skills in programming and algorithm design for hardware control.
- Understand the basics of hardware interfacing and electronic component control.
- Acquire knowledge of integrating microcontrollers with computer-based programming.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
Feel free to fill in the specific details and code as you develop the project.
TW5 (don’t refer this)
- Title: Interfacing Arduino with a 16x2 LCD Display as a stopwatch
- Objective: The objective of this project is to interface an Arduino board with a 16x2 LCD display to create a stopwatch. The stopwatch will be capable of measuring elapsed time with precision and displaying it on the LCD screen.
- Brief theory
- Arduino: Arduino is an open-source electronics platform based on easy-to-use hardware and software. It consists of a microcontroller board and a development environment for writing and uploading code to the board. Arduino boards are commonly used in various projects for automation, control, and data logging.
- 16x2 LCD Display: A 16x2 LCD (Liquid Crystal Display) module is a type of alphanumeric display that can display 16 characters per line and has 2 lines. It is widely used in electronic projects for displaying text-based information such as sensor readings, messages, or time.
- Stopwatch: A stopwatch is a timekeeping device used to measure elapsed time with precision. It typically consists of a start/stop button and a reset button to control the timing operation.
- Interfacing block diagram: Check tinkercad
- Algorithm
- Initialize the Arduino board and configure the connections for the 16x2 LCD display.
- Implement functions to control the LCD display, including functions for clearing the display, setting the cursor position, and printing characters or strings.
- Implement a function to start, stop, and reset the stopwatch.
- Continuously update the LCD display to show the elapsed time while the stopwatch is running.
- Handle user input from external buttons to control the stopwatch operations.
- Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
// https://aeroarduino.com/arduino-hobbyist/stopwatch-with-arduino-and-lcd-on-tinkercad/ // https://youtu.be/Sx8P1-MxHIQ // https://youtu.be/cjVaV6UrckU //https://www.tinkercad.com/things/4GNAuVVRqRL #include <LiquidCrystal.h> //PIN 5 R/W to Ground, for writing //LCD Mode : 4 data pin //Functions: Start, stop, saving up to 4 partial time in memory. //10 millis = 1 hundredth of a second. The chronometer measures hour, minutes, seconds, and hundredths of a second. //Buttons with internal Pullup, so if they get pressed we get LOW const int start = 8; //Start the stopwatch const int pausa = 9; //Stop const int partial = 10; //Save a partial const int scroll_partial = 11; //If paused, check the 4 last saved partial int x = 0; //Variable to manage the loop //LCD int lcdclear = 0; //this to variables are needed for managing int Display = 0; //the display, to clear and print //chronometer int cents = 0; int seconds = 0; int minutes = 0; int hours = 0; const int interval = 10; //Every 10 milliseconds i increase 1 cent unsigned long previousMillis = 0; int c1, c2, s1, s2, m1, m2, h; //Variables used to put in the form //h:m2m1:s2s1:c2c1 //Partial: I save 4 partial, that can be seen if stopwatch is stopped int partial2[7]; //penultimate partial (The one that stays in Old). The last partial stays in New: int partial3[7]; int partial4[7]; int scrolling = 0; //Used to scroll the saved partial times LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // RS-Enable-D4-D5-D6-D7 in that digitalPin void setup() { pinMode(start, INPUT_PULLUP); //In the schematic from right to left pinMode(pausa, INPUT_PULLUP);//there are start-pausa-partial-scroll_partial pinMode(partial, INPUT_PULLUP); pinMode(scroll_partial, INPUT_PULLUP); lcd.begin(16,2); lcd.print("Press start"); } void loop() { if (x == 0) { //Initially is 0 while(digitalRead(start) == HIGH) {}; //Until i press the button, the chronometer doesn't start x++; //When i press the button, i go out from this cycle, x++ and i cannot return here anymore } if (lcdclear == 0){ //Condition to clear the display, used in the various functions lcd.clear(); lcdclear++; } if (Display == 0){ //Also this is used to clear display lcd.home(); lcd.print("Now: "); //With this condition, i can print "Now: " one single time, otherwise the chronometer wouldn't be precise Display++; scrolling = 0; //When i exit from the partial menu, then if i go in the partial menu again i always get in PAR1 and PAR2 } chronometer(); //At the end of every increase, i control if stop is pressed. And also if the partial function is pressed pause(); f_partial(); } void chronometer(void){ //This function print: "New: Actual time" unsigned long currentMillis = millis(); //If for the updating. If it is true, it means 1 cent of a second had passed. Update cents, minutes, seconds, hours and then i write on the lcd if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; cents++; if (cents == 100){ cents = 0; seconds++; if (seconds == 60) { seconds = 0; minutes++; if (minutes == 60){ minutes = 0; hours++; if (hours == 24) hours = 0; } } } int cent = cents; int sec = seconds; int minu = minutes; //Taking the digits separeted h = hours; //For the other funcionts, so i can put hours = 0 and h still is the last value c1 = cent%10; cent /= 10; c2 = cent%10; s1 = sec%10; sec /= 10; s2 = sec%10; m1 = minu%10; minu /= 10; m2 = minu%10; lcd.setCursor(6, 0); lcd.print(h); lcd.print(':'); lcd.print(m2); lcd.print(m1); lcd.print(':'); lcd.print(s2); lcd.print(s1); lcd.print(':'); lcd.print(c2); lcd.print(c1); } } void scrollPartial(void){ while(digitalRead(scroll_partial) == LOW) {}; //Debounce, as long as i press the button the real function doesn't start if (scrolling == 0) { //Visualize the last 2 partials lcd.clear(); lcd.home(); lcd.print("PAR1:"); lcd.setCursor(6, 0); lcd.print(h); lcd.print(':'); lcd.print(m2); lcd.print(m1); lcd.print(':'); lcd.print(s2); lcd.print(s1); lcd.print(':'); lcd.print(c2); lcd.print(c1); lcd.setCursor(0, 1); lcd.print("PAR2:"); lcd.setCursor(6, 1); lcd.print(partial2[0]); lcd.print(':'); lcd.print(partial2[1]); lcd.print(partial2[2]); lcd.print(':'); lcd.print(partial2[3]); lcd.print(partial2[4]); lcd.print(':'); lcd.print(partial2[5]); lcd.print(partial2[6]); Display = 0; //When i press start the display must be cleared lcdclear = 0; //When i press start the display must be cleared cents = seconds = minutes = hours = 0; scrolling++; } else if (scrolling == 1){ //Visualize 3th and 4th partial lcd.clear(); lcd.home(); lcd.print("PAR3:"); lcd.setCursor(6, 0); lcd.print(partial3[0]); lcd.print(':'); lcd.print(partial3[1]); lcd.print(partial3[2]); lcd.print(':'); lcd.print(partial3[3]); lcd.print(partial3[4]); lcd.print(':'); lcd.print(partial3[5]); lcd.print(partial3[6]); lcd.setCursor(0, 1); lcd.print("PAR4:"); lcd.setCursor(6, 1); lcd.print(partial4[0]); lcd.print(':'); lcd.print(partial4[1]); lcd.print(partial4[2]); lcd.print(':'); lcd.print(partial4[3]); lcd.print(partial4[4]); lcd.print(':'); lcd.print(partial4[5]); lcd.print(partial4[6]); Display = 0; //When i press start the display must be cleared lcdclear = 0; //When i press start the display must be cleared cents = seconds = minutes = hours = 0; scrolling = 0; } } void pause(void){ //If pause is pressed, i stop in this function until start doesn't get pressed again if (digitalRead(pausa) == HIGH) return; else if (digitalRead(pausa) == LOW){ //Stuck in this cycle until i press start while(digitalRead(start) == HIGH) { if (digitalRead(scroll_partial) == LOW) //If i press the button for seeing the partial, i enter in that function scrollPartial(); //When scrollPartial() ends, i'm still in this function, so if i press start the chronometer starts back normal } } } void f_partial(void){ //If this button is pressed, i put the current value of New in Old, and a new crhonometer starts if (digitalRead(partial) == HIGH) return; else if (digitalRead(partial) == LOW ){ lcd.clear(); lcd.setCursor(0, 1); //The values calculated in the function chronometer can be used, h,m,s,c lcd.print("Old: "); lcd.setCursor(6, 1); lcd.print(h); lcd.print(':'); lcd.print(m2); lcd.print(m1); lcd.print(':'); lcd.print(s2); lcd.print(s1); lcd.print(':'); lcd.print(c2); lcd.print(c1); //When i come here, i've got the old values for h,m,s,c, i save it in the partial array Display = 0; //The new is written again cents = 0; seconds = 0; minutes = 0; hours = 0; partial4[0] = partial3[0]; //Partial4[] is updated with the old partial3[] partial4[1] = partial3[1]; partial4[2] = partial3[2]; partial4[3] = partial3[3]; partial4[4] = partial3[4]; partial4[5] = partial3[5]; partial4[6] = partial3[6]; partial3[0] = partial2[0]; //Partial3[] is updated with the old partial2[] partial3[1] = partial2[1]; partial3[2] = partial2[2]; partial3[3] = partial2[3]; partial3[4] = partial2[4]; partial3[5] = partial2[5]; partial3[6] = partial2[6]; partial2[0] = h; //Update partial2 with OLD partial2[1] = m2; partial2[2] = m1; partial2[3] = s2; partial2[4] = s1; partial2[5] = c2; partial2[6] = c1; while(digitalRead(partial) == LOW) {}; //Debounce, until i press the button i stay here } }
- Output: Check here
- Conclusion: This project demonstrates the integration of an Arduino board with a 16x2 LCD display to create a stopwatch. By leveraging the capabilities of Arduino in conjunction with the LCD display, users can implement a functional timing device suitable for various applications, such as sports, experiments, or projects requiring time measurement.
- Course learning outcomes
- Understanding of interfacing techniques for LCD displays with Arduino.
- Implementation of timing and control logic for stopwatch functionality.
- Practical application of microcontroller-based timing systems.
- Introduction to user interface design and interaction using external buttons.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW6
1. Title
Interface an Arduino to a 7-Segment and 16x2 LCD Display (Interfacing Arduino to Show a T-Minus Countdown on the 16x2 LCD and 7-Segment Display, and Show “LAUNCH” When the Counter Reaches 0)
2. Objective
To design and implement a program that controls both a 7-segment display and a 16x2 LCD display using an Arduino. The system will display a T-minus countdown on both displays and show “LAUNCH” when the countdown reaches 0.
3. Brief Theory
A 7-segment display is used to display individual digits by illuminating specific segments, while a 16x2 LCD display can show 16 characters on each of its two lines. In this project, an Arduino microcontroller will be used to control both displays. The Arduino will count down from a specified number (T-minus countdown) and simultaneously update both displays with the current countdown value. When the countdown reaches 0, the displays will show the word “LAUNCH”. This project involves understanding both hardware interfacing and software programming to achieve the desired functionality.
4. Interfacing Block Diagram and manual calculations if any
Check tinkercad
Algorithm
Initialize System
- Set up the Arduino with the necessary libraries for controlling the 7-segment display and the 16x2 LCD display.
- Initialize the pins connected to the 7-segment display and the LCD as outputs.
Display Initialization
- Ensure the 16x2 LCD display is properly initialized and ready to display text.
- Ensure the 7-segment display is properly initialized to show the initial countdown value.
Set Initial Countdown Value
- Set a variable for the countdown starting value (e.g., T-minus 10).
Countdown Logic
- Enter a loop to decrement the countdown value by 1 at regular intervals (e.g., every second).
- Update both the 7-segment display and the 16x2 LCD display to show the current countdown value.
- If the countdown value reaches 0, display “LAUNCH” on the 16x2 LCD and clear the 7-segment display or show 0.
Loop and Update Display
- Continuously check and update the countdown value and display it.
- Implement a mechanism to start the countdown (e.g., via a button press).
Code
|
|
Output (Printout)
Check hereConclusion
The project successfully demonstrates the use of an Arduino to control both a 7-segment display and a 16x2 LCD display. The system accurately performs a T-minus countdown, displaying the countdown on both displays and showing “LAUNCH” when the countdown reaches 0. This project enhances understanding of hardware interfacing and programming for multiple display types.Course Learning Outcome
- Gain practical experience with Arduino microcontroller development.
- Learn to interface and control a 7-segment display and a 16x2 LCD display.
- Develop skills in programming and algorithm design for countdown timers.
- Understand the basics of hardware interfacing and multiple display management.
- Acquire knowledge of integrating microcontrollers with various display components.
- References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW7
Title
Interface Buzzer with Raspberry PiObjective
To design and implement a system that interfaces a buzzer with a Raspberry Pi, allowing the buzzer to be controlled programmatically.Brief Theory
A buzzer is an audio signaling device commonly used for alarms, timers, and user notifications. It can be controlled by a microcontroller or single-board computer such as the Raspberry Pi. By sending a signal from the Raspberry Pi’s GPIO pins to the buzzer, it can be turned on or off. This project involves understanding the basics of GPIO (General-Purpose Input/Output) pin control on the Raspberry Pi and using Python programming to manage the buzzer’s operation.Interfacing Block Diagram and manual calculations if any
Check google driveAlgorithm
Initialize System
- Set up the Raspberry Pi and ensure it has the necessary software installed (e.g., Raspbian OS, Python, GPIO libraries).
- Connect the buzzer to one of the GPIO pins on the Raspberry Pi (e.g., GPIO18) and connect the other terminal of the buzzer to a ground (GND) pin.
Library Import and GPIO Setup
- Import the necessary libraries for GPIO control in the Python script.
- Set up the GPIO pin connected to the buzzer as an output pin.
Buzzer Control Logic
- Write a function to turn the buzzer on and off by sending a high or low signal to the GPIO pin.
- Implement a loop or condition to control the buzzer based on specific events or time intervals.
Execution and Testing
- Run the Python script to control the buzzer.
- Test different scenarios such as turning the buzzer on for a set duration, creating a beeping pattern, or responding to an input signal.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# @Auth Xtrans Solutions Pvt. Ltd. # Program to test Buzzer # Connect RM9 to RM17 import time import RPi.GPIO as gpio gpio.setwarnings(False) gpio.setmode(gpio.BOARD) gpio.setup(38, gpio.OUT) try: while(1): gpio.output(38,0) print("Buzzer OFF") time.sleep(1) gpio.output(38,1) print("Buzzer ON") time.sleep(1) #gpio.cleanup() except KeyboardInterrupt: gpio.cleanup() exit
Output (Printout)
Check google driveConclusion
The project successfully demonstrates how to interface a buzzer with a Raspberry Pi and control it programmatically using Python. This setup can be used in various applications such as alarms, notifications, and user feedback systems. The project enhances understanding of GPIO pin control and basic electronics interfacing with a Raspberry Pi.Course Learning Outcome
- Gain practical experience with the Raspberry Pi single-board computer.
- Learn to interface and control a buzzer using GPIO pins.
- Develop skills in Python programming for hardware control.
- Understand the basics of electronic component interfacing.
- Acquire knowledge of integrating Raspberry Pi with various peripherals.
References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW8
Title
Interface Raspberry Pi with LDR Sensor and Buzzer (So When LDR Sensor Stops Detecting Light, the Buzzer Turns On)Objective
To design and implement a system that interfaces an LDR (Light Dependent Resistor) sensor and a buzzer with a Raspberry Pi. The system will monitor the light level using the LDR sensor and activate the buzzer when the light level drops below a certain threshold.Brief Theory
An LDR sensor changes its resistance based on the amount of light it detects; it has higher resistance in the dark and lower resistance in the light. This varying resistance can be used to measure light intensity. A buzzer is an audio signaling device that can be controlled via GPIO pins on a Raspberry Pi. In this project, the Raspberry Pi reads the LDR sensor’s value and triggers the buzzer when the light level falls below a predefined threshold. This involves understanding analog-to-digital conversion (since the Raspberry Pi lacks built-in ADC), GPIO pin control, and Python programming.Interfacing Block Diagram and manual calculations if any
Check google driveAlgorithm
Initialize System
- Set up the Raspberry Pi with necessary software installed (e.g., Raspbian OS, Python, GPIO libraries, and an ADC like MCP3008 if needed).
- Connect the LDR sensor in a voltage divider configuration to an ADC (e.g., MCP3008) if using one. Connect the ADC to the Raspberry Pi’s SPI pins.
- Connect the buzzer to one of the GPIO pins on the Raspberry Pi (e.g., GPIO18) and connect the other terminal of the buzzer to a ground (GND) pin.
Library Import and GPIO/ADC Setup
- Import the necessary libraries for GPIO and ADC control in the Python script.
- Set up the GPIO pin connected to the buzzer as an output pin.
- Initialize the ADC to read values from the LDR sensor.
Light Level Detection Logic
- Read the value from the LDR sensor through the ADC.
- Determine a threshold value for light detection (e.g., set a value below which the light is considered to be “not detected”).
Buzzer Control Logic
- Continuously monitor the LDR sensor’s value.
- If the sensor value drops below the threshold, turn the buzzer on by sending a high signal to the GPIO pin.
- If the sensor value is above the threshold, turn the buzzer off by sending a low signal to the GPIO pin.
Execution and Testing
- Run the Python script to monitor the LDR sensor and control the buzzer.
- Test the system by changing the light levels and observing the buzzer’s response.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import RPi.GPIO as gpio import time gpio.setwarnings(False) gpio.setmode(gpio.BOARD) gpio.setup(38,gpio.OUT) gpio.setup(33,gpio.IN) try: while(1): light=gpio.input(33) if light==0: gpio.output(38,0) print("Light Detected , Buzzer off") time.sleep(1) elif light==1: gpio.output(38,1) print("Light not detected , Buzzer on") time.sleep(1) except KeyboardInterrupt: gpio.cleanup() exit
Output (Printout)
Check google driveConclusion
The project successfully demonstrates how to interface an LDR sensor and a buzzer with a Raspberry Pi. The system monitors light levels using the LDR sensor and activates the buzzer when the light level drops below a certain threshold. This setup can be used for applications such as intruder alarms or light-sensitive alerts. The project enhances understanding of analog sensor interfacing, GPIO control, and ADC usage with a Raspberry Pi.Course Learning Outcome
- Gain practical experience with the Raspberry Pi single-board computer.
- Learn to interface and control an LDR sensor and a buzzer using GPIO pins.
- Develop skills in Python programming for hardware control.
- Understand the basics of analog-to-digital conversion and sensor interfacing.
- Acquire knowledge of integrating Raspberry Pi with various peripherals.
References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW9
Title
Using DHT-11 to read the current temperature, humidity and sending the data to the cloud using ThingSpeak APIObjective
To design a system using DHT-11 sensor to measure temperature and humidity, and transmit the data to the cloud using the ThingSpeak API for real-time monitoring and analysis.Brief Theory Explain briefly about:
- DHT-11 sensor: Introduction, working principle (how it measures temperature and humidity).
- ThingSpeak: Introduction to IoT platform, overview of how it allows for data collection, visualization, and analysis.
Interfacing Block Diagram and manual calculations if any
Check google driveAlgorithm
Imports and Initialization:
- Import necessary libraries (adafruit_dht, board, RPi.GPIO, requests, datetime, time).
- Import ThingSpeak configuration (THINGSPEAK_API_KEY, THINGSPEAK_URL) from thingspeak_config.
Function
get_readings()
:- Initializes DHT11 sensor (adafruit_dht.DHT11 on board.D4).
- Reads temperature (temperature_c) and humidity.
- Converts temperature to Fahrenheit (temperature_f) if valid.
- Returns readings or error message.
Function
send_to_thingspeak(temperature_c, temperature_f, humidity)
:- Sends sensor data (temperature_c, temperature_f, humidity) to ThingSpeak.
- Includes timestamp and API key in the HTTP POST request.
- Prints success or failure messages based on response status.
Function
main()
:- Loops 20 times to collect and send sensor data to ThingSpeak.
- Uses
get_readings()
to fetch data andsend_to_thingspeak()
to transmit it. - Includes a 5-second delay between iterations.
Execution (
if __name__ == '__main__'
):- Executes
main()
function to start data collection and transmission.
- Executes
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
import adafruit_dht import board from RPi import GPIO import requests import datetime import time import thingspeak_config as config # thingspeak constants THINGSPEAK_API_KEY = config.THINGSPEAK_API_KEY # Replace with your API key THINGSPEAK_URL = config.THINGSPEAK_URL_SEND # URL to send data to ThingSpeak def get_readings(): try: # Initialize the DHT device inside the route function dht_device = adafruit_dht.DHT11(board.D4) temperature_c = dht_device.temperature humidity = dht_device.humidity # Check if readings are valid if temperature_c is not None and humidity is not None: temperature_f = int(temperature_c * (9 / 5) + 32) return { 'temperature_c': temperature_c, 'temperature_f': temperature_f, 'humidity': humidity } else: return {'error': 'Failed to retrieve data from sensor'} except RuntimeError as error: # Catch runtime errors from the sensor return {'error': str(error)} finally: # Cleanup the sensor after use dht_device.exit() def send_to_thingspeak(temperature_c, temperature_f, humidity): current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # sending the data response = requests.post(THINGSPEAK_URL, { 'api_key': THINGSPEAK_API_KEY, 'field1': current_time, 'field2': temperature_c, 'field3': temperature_f, 'field4': humidity }) if response.status_code != 200: print(f'Failed to send data to ThingSpeak: {response.text}') if response.status_code == 200: print(f'Successfully sent data to ThingSpeak: {response.text}') def main(): for i in range(20): readings_json = get_readings() send_to_thingspeak(readings_json['temperature_c'], readings_json['temperature_f'], readings_json['humidity']) time.sleep(5) if __name__ == '__main__': main()
Output (Printout)
Check google driveConclusion
Utilizing ThingSpeak API for data retrieval enhances IoT applications by providing real-time access to stored sensor data. This capability enables timely decision-making and monitoring of environmental conditions, contributing to efficient IoT deployments.Course learning outcome
This project aligns with the learning outcomes of understanding and implementing IoT data management solutions. By utilizing ThingSpeak API, skills such as API integration, data retrieval, and real-time monitoring are developed, essential for modern IoT applications.References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019
TW10
Title
Using ThingSpeak API to check and receive the latest data stored in the cloudObjective
To demonstrate how to use the ThingSpeak API to retrieve the latest data entries from a specific channel stored in the ThingSpeak cloud platform.Brief Theory
ThingSpeak API for Data RetrievalThingSpeak provides an API that allows seamless integration with IoT applications for retrieving stored data. Here’s an elaboration:
RESTful API: ThingSpeak’s API follows REST principles, which means it uses standard HTTP methods (GET, POST, etc.) for data retrieval. This makes it accessible and easy to integrate into various applications.
Endpoints: Key endpoints include:
- Latest Entry: Retrieves the most recent data entry from a specified channel.
- Channel Feeds: Retrieves a set number of entries (feeds) from a channel, useful for historical data analysis.
- Field Feeds: Allows retrieval of specific fields within a channel entry, facilitating selective data extraction.
Authentication:
- API Keys: Authentication is managed through API keys, which are included in API requests to ensure secure access to channel data.
Integration with Applications:
- ThingSpeak API enables integration with external applications and services for data visualization, analysis, and automation.
- Integration with platforms like MATLAB allows for advanced data processing and visualization capabilities.
Interfacing Block Diagram and manual calculations if any
Check google driveAlgorithm
Imports and Initialization:
- Import necessary libraries (
requests
). - Import ThingSpeak configuration (
THINGSPEAK_READ_API_KEY
,THINGSPEAK_CHANNEL_ID
,THINGSPEAK_URL
) fromthingspeak_config
.
- Import necessary libraries (
Function
read_from_thingspeak()
:- Sends a GET request to ThingSpeak (
THINGSPEAK_URL
) with parameters:api_key
: Read API key (THINGSPEAK_READ_API_KEY
).results
: Number of results to retrieve (1 in this case).
- Checks if the request is successful (status code 200).
- Parses the JSON response and retrieves the latest feed (
feeds[0]
). - Prints the latest feed information:
- Timestamp (
created_at
). - Temperature in Celsius (
field2
). - Temperature in Fahrenheit (
field3
). - Humidity (
field4
).
- Timestamp (
- Handles cases where no data is available or if there’s an error.
- Sends a GET request to ThingSpeak (
Function
main()
:- Calls
read_from_thingspeak()
to fetch and display the latest data from ThingSpeak.
- Calls
Execution (
if __name__ == '__main__':
):- Executes
main()
function when the script is run directly.
- Executes
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
import requests import thingspeak_config as config # ThingSpeak read API constants THINGSPEAK_READ_API_KEY = config.THINGSPEAK_READ_API_KEY # Replace with your read API key THINGSPEAK_CHANNEL_ID = config.THINGSPEAK_CHANNEL_ID # Replace with your channel ID THINGSPEAK_URL = config.THINGSPEAK_URL_RECV # URL to read data from ThingSpeak def read_from_thingspeak(): try: # Send GET request to ThingSpeak response = requests.get(THINGSPEAK_URL, params={'api_key': THINGSPEAK_READ_API_KEY, 'results': 1}) # Check if request was successful if response.status_code == 200: data = response.json() feeds = data['feeds'] if feeds: latest_feed = feeds[0] print('Latest Feed:') print(f"Datetime: {latest_feed['created_at']}") print(f"Temperature (C): {latest_feed['field2']}") print(f"Temperature (F): {latest_feed['field3']}") print(f"Humidity: {latest_feed['field4']}") else: print('No data available') else: print(f'Failed to read data from ThingSpeak: {response.text}') except Exception as e: print(f'Error: {e}') def main(): read_from_thingspeak() if __name__ == '__main__': main()
Output (Printout)
Check google driveConclusion
Utilizing ThingSpeak API for data retrieval enhances IoT applications by providing real-time access to stored sensor data. This capability enables timely decision-making and monitoring of environmental conditions, contributing to efficient IoT deployments.Course learning outcome
This project aligns with the learning outcomes of understanding and implementing IoT data management solutions. By utilizing ThingSpeak API, skills such as API integration, data retrieval, and real-time monitoring are developed, essential for modern IoT applications.References
- Arduino Official Website: https://www.arduino.cc/
- Tinkercad: https://www.tinkercad.com/users/3yIYe1Hze1e
- GitHub: https://github.com/AumPauskar/micro-iot-projects/
- Arshdeep Bagha, Vijay Madishetti, Internet of Things A Hands- on Approach, Universities Press, 2014
- Sudip Misra, Anandarup Mukherjee, Arijit Roy, Introduction to IoT, Cambridge University Press, 2021
- Mayur Ramgir, Internet of Things- Architecture, Implementation, and Security, Pearson Education India, 2019