th223ap
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully