# IoT Project Tutorial: Simulating Traffic Light Control with Raspberry Pi Pico **Author:** Tariq Habach **Student ID:** th223ap ## Short Project Description This IoT project tutorial introduces a captivating exploration into the realm of the Internet of Things (IoT). By crafting a simulation of a traffic light control system using the versatile Raspberry Pi Pico microcontroller, participants will merge physical components like LEDs with programming to emulate the behavior of a real traffic light system. This hands-on project aims to provide a practical understanding of IoT device programming concepts and their application in real-world scenarios. - Estimated Time for the Project: The project can typically be completed within a few hours, depending on familiarity with the hardware and programming concepts. The duration may vary based on individual learning pace and previous experience. ![](https://hackmd.io/_uploads/HJOoFHZT2.png) ## Objective The primary objective of this project is to gain a practical understanding of IoT device programming and data transmission. By simulating a traffic light control system, we will explore how IoT devices can be effectively programmed to manage real world scenarios. Through this project, we will discover fundamental principles in IoT development and lay the groundwork for further exploration in the field. ## List of Materials To successfully complete this project, we will need the following materials: - Raspberry Pi Pico: A powerful microcontroller that will serve as the brain of our IoT device. - Breadboard and Jumper Wires: Essential for building the circuit and connecting components. - Three LEDs (Red, Yellow, Green): These LEDs will simulate the traffic light signals. - Three Current-Limiting Resistors: We'll choose appropriate resistor values to regulate current for each LED. - Micro USB Cable: Required to power the Raspberry Pi Pico. - Computer with Thonny IDE: Thonny provides an easy-to-use environment for coding the microcontroller. ### Where to Buy and Cost The "Start Kit - Applied IoT at Linnaeus University 2023" is available for purchase from [Electrokit's website](https://www.electrokit.com/produkt/start-kit-applied-iot-at-linnaeus-university-2023/). The cost of the kit is mentioned on the website, and it includes all the components listed above. ## Computer Setup Setting up the computer for this project involves several steps: 1. Install Thonny IDE (mac): Download and install Thonny IDE, which will serve as our development environment. 2. Connect Raspberry Pi Pico: Use a Micro USB cable to connect the Raspberry Pi Pico to the computer. 3. Open Thonny IDE: Launch Thonny and create a new Python file to start coding. 4. Copy Code: Copy the provided code and paste it into the Python file. 5. Modify Wi-Fi Credentials: Update the code with the Wi-Fi SSID and password. 6. Upload Code: Upload the modified code to the Raspberry Pi Pico using Thonny IDE. ## Assembling the Hardware Components Assembling the hardware components involves the following specific steps: ### Wiring LEDs 1. **Red LED:** Connect the anode (longer leg) of the red LED to a GPIO pin (e.g., Pin 2) on the Raspberry Pi Pico. Connect the cathode (shorter leg) of the LED to the ground (GND) pin using a current-limiting resistor. 2. **Yellow LED:** Similarly, connect the yellow LED's anode to another GPIO pin (e.g., Pin 3) and the cathode to the ground pin with a resistor. 3. **Green LED:** Connect the green LED's anode to a GPIO pin (e.g., Pin 4) and the cathode to the ground pin with a resistor. ### Adding Resistors 1. **Current-Limiting Resistors:** For each LED, attach an appropriate current-limiting resistor in series with the cathode (shorter leg). The value of the resistor depends on the LED's specifications and the desired brightness. Refer to the LED's datasheet for recommended resistor values. ### Breadboard Arrangement 1. **Place Components:** Organize the Raspberry Pi Pico, LEDs, and resistors on the breadboard. Insert the LED anodes and resistor legs into the breadboard's appropriate rows. Ensure that each component has a secure connection. 2. **Connect Ground (GND):** Connect the GND pin of the Raspberry Pi Pico to the breadboard's ground rail. Also, connect the cathodes of all LEDs to the same ground rail. 3. **Connect GPIO Pins:** Connect the GPIO pins of the Raspberry Pi Pico (used for LEDs) to the breadboard's rows. Double check the connections and ensure that there are no loose wires. 4. **Check Connections:** Verify that all connections are correct, and components are securely connected. A well organized breadboard layout minimizes chances of errors. ![](https://hackmd.io/_uploads/r1lVjB-ah.png) ## Platform The chosen platform for this project is the Raspberry Pi Pico, a versatile microcontroller. This platform offers the advantage of direct programming using Thonny IDE, enabling us to harness IoT capabilities without complexity. While focusing on local development, the principles learned here can be extended to cloud-based IoT platforms for broader applications. ## The Code The provided code is the core of the project. It orchestrates the simulation of traffic light behavior and data transmission. ```python import network import urequests as requests import machine from time import sleep # Wi-Fi credentials WIFI_SSID = "COMHEM" WIFI_PASS = "" # Ubidots credentials TOKEN = "" DEVICE_LABEL = "" RED_VARIABLE_LABEL = "red_light" YELLOW_VARIABLE_LABEL = "yellow_light" GREEN_VARIABLE_LABEL = "green_light" # GPIO pins for the traffic lights RED_PIN = 2 YELLOW_PIN = 3 GREEN_PIN = 4 # Set up Wi-Fi def connect_wifi(): wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): print('Connecting to WiFi...') wlan.active(True) wlan.connect(WIFI_SSID, WIFI_PASS) while not wlan.isconnected(): pass print('Connected to WiFi:', WIFI_SSID) # Builds the JSON to send the request def build_json(variable, value): try: data = {variable: {"value": value}} return data except: return None # Sending data to Ubidots RESTful Webserice def send_data(device, variable, value): try: url = f'https://industrial.api.ubidots.com/api/v1.6/devices/{device}' headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"} data = build_json(variable, value) if data is not None: print('Sending data:', data) req = requests.post(url=url, headers=headers, json=data) req.close() except: pass # Main loop def main(): connect_wifi() red_led = machine.Pin(RED_PIN, machine.Pin.OUT) yellow_led = machine.Pin(YELLOW_PIN, machine.Pin.OUT) green_led = machine.Pin(GREEN_PIN, machine.Pin.OUT) while True: # Update traffic light status red_led.value(1) send_data(DEVICE_LABEL, RED_VARIABLE_LABEL, 1) sleep(5) yellow_led.value(1) red_led.value(0) send_data(DEVICE_LABEL, YELLOW_VARIABLE_LABEL, 2) sleep(2) green_led.value(1) yellow_led.value(0) send_data(DEVICE_LABEL, GREEN_VARIABLE_LABEL, 3) sleep(5) green_led.value(0) if __name__ == "__main__": main() ``` ## Transmitting Data / Connectivity Data transmission is facilitated through Wi-Fi connectivity and interaction with the Ubidots platform. The modified code now incorporates variables for each traffic light and their corresponding switches. Upon starting the code, these variables initiate the simulation, turning on the respective switches and triggering the traffic light sequence. The code establishes a Wi-Fi connection, enabling communication between the Raspberry Pi Pico and the Ubidots platform. ![](https://hackmd.io/_uploads/r1O5AHZp3.png) As the simulation progresses, the status of each traffic light, represented by the switches, is updated in real-time. Timestamps are also included to provide context for each status change. The code utilizes HTTPS requests to send this data to the Ubidots platform. The timing intervals for data transmission are determined by the sleep intervals integrated into the code. This modified approach enriches the project by allowing dynamic interaction with the traffic light simulation and provides a more comprehensive representation of a real-world scenario. ## Data Presentation When it comes to presenting the data collected from the traffic light simulation, the Ubidots platform offers a robust solution that allows for intuitive visualization and insightful analysis. Here are some key points about how the data is presented: ### Dashboard Visualization Ubidots empowers users to create interactive dashboards that bring the traffic light simulation data to life. Through customizable widgets and visual components, users can design dashboards that display real-time traffic light statuses and patterns. Below are visual examples of how the dashboard might look: ![](https://hackmd.io/_uploads/rkSqPHba2.png) ### Data Storage and Frequency The data from the traffic light simulation is saved in the Ubidots database at regular intervals. This frequency can be customized based on the requirements of your project. For instance, data might be saved every few seconds, minutes, or even hours, depending on the level of granularity needed for analysis. ### Choice of Database Ubidots utilizes a cloud-based database to store the collected data. The choice of this database is rooted in its scalability and accessibility. Cloud-based databases enable easy management of large volumes of data and provide remote access to the information from anywhere with an internet connection. ### Automation and Triggers Automation and triggers enhance the data collection process by allowing actions to be executed based on specific conditions. In the context of the traffic light simulation, you can set up triggers to activate when certain events occur, such as changes in traffic flow patterns. These triggers can initiate notifications, alerts, or even specific actions, enhancing the real-world applicability of the simulation data. By leveraging Ubidots' automation capabilities, you can create a system that responds dynamically to variations in the simulated traffic environment. ## Final Thoughts In conclusion, this project has been enhanced by integrating variables and switches to initiate and control the traffic light simulation in real-time. This approach aligns with the principles of IoT by enabling remote monitoring and interaction with the simulated scenario. By embarking on this project, you have not only gained expertise in IoT device programming but also demonstrated the potential of IoT solutions in managing practical scenarios. As a next step, consider exploring further customization, integrating external sensors for more realistic simulations, or even applying machine learning techniques to optimize traffic flow patterns. ![](https://hackmd.io/_uploads/HyJV1OWT3.jpg) ![](https://hackmd.io/_uploads/rJP3l8Zan.png)