Xin Yu
    • 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

      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.
      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

    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.
    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
    # 樹莓派進度 ## 硬體安裝 1. 連接樹莓派的周邊裝置 * 螢幕、HDMI連接線、鍵盤、滑鼠(實驗室) * SD卡、讀卡機、電源線(自備) 2. 格式化SD卡 3. 下載Raspbian映像檔 * 下載燒錄器(Raspberry Pi OS): * https://www.raspberrypi.com/software/ * 選擇系統: * ![](https://i.imgur.com/Mxm3100.png) * 選擇SD卡燒錄(這裡需要福堂老師的協助,因為多次嘗試發現有防寫機制,且顯示物理毀損,不知道是哪個硬體設備問題) ![](https://i.imgur.com/zbSOjl5.png) 4. 將燒錄好的SD卡插入樹莓派啟動 5. 啟動後會進入PIXEL桌面環境,要進行基本本地端設定 ## 在Windows遠端操作樹莓派 1. 在樹莓派啟用SSH、查詢IP位址 * ip:**192.168.12.225** * count:**microsevice** * password:**123456789** 2. 樹莓派端: (方法一)使用PuTTY工具 (方法二)VNC Server (參考步驟:https://mad-coding.medium.com/%E6%A8%B9%E8%8E%93%E6%B4%BE%E6%95%99%E5%AD%B8-%E7%94%A8%E7%AD%86%E9%9B%BB%E9%81%A0%E7%AB%AF%E9%81%99%E6%8E%A7%E6%A8%B9%E8%8E%93%E6%B4%BE-%E4%B8%8B-a98082064e0)(https://ithelp.ithome.com.tw/articles/10235452) 3. 筆電端:下載Windows VNC Viewer (https://www.realvnc.com/en/connect/download/viewer/) 安裝好後輸入樹莓派的 IP 位址加埠號 ## 更新/安裝python 檔 * 更新python套件: 進入樹莓派終端輸入密碼後更新套件 輸入指令`sudo apt-get update`(取得更新的檔案套件清單) 更新套件 指令 `sudo apt-get-y dist-upgrade` 清空 指令 `sudo apt-get clean` * python 安裝: 指令 `sudo apt-get install idle-python 2.7` 關閉小黑框回到首頁選**main menu editor** 選程式設計**編成** 把**IDLE (using python-2.7)** 打勾然後按確定 重複上一步**編成**步驟到IDLE **添加到菜單** 之後到桌面雙擊圖示就可以進到python 環境 * 安裝步驟參考網址:https://www.gushiciku.cn/pl/p7JU/zh-tw * 指令參考網址:https://yanwei-liu.medium.com/raspberry-pi%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E4%B8%89-%E6%8C%87%E4%BB%A4%E8%88%87%E5%8A%9F%E8%83%BD-b9e1a7a6a14 ## 開關燈泡程式碼 * python模組 * `$ sudo apt-get install python3-gpiozero` * 使用input控制LED * `$ sudo nano led1.py` ``` from gpiozero import LED led=LED(17) while True: print("\n0) down LED") print("1)open LED") print("2)exit") light=input("your choose(0/1/2): ") if light == "0": led.off() if light == "1": led.on() if light == "2": break ``` * `$ sudo python led1.py` * LED燈自行閃爍 ``` import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(17, GPIO.OUT) while True: GPIO.output(17,True) time.sleep(1) GPIO.output(17,False) time.sleep(1) ``` * 硬體接線: ![](https://i.imgur.com/GhXr6NM.png) * 參考網站: * https://dic.vbird.tw/iot_pi/unit06.php * https://www.youtube.com/watch?v=W56aWiuOZnk ### 執行結果 ![](https://i.imgur.com/zhuNiFe.png) ## 傳送資料至API 設定raspberry pi讓傳感器讀取data 下載marshmallow做python object和json字串的轉換 (ex. pip3 install requests marshmallow) 定義sensorschema class和json的屬性關係 (ex. data=fields.Str()/pin=fields.Int()) 定義readingschema class和json的屬性關係 用marshmallow dump()把讀進來的data轉換為json format去做HTTP request 設定url header告訴api我們要發送的json data (ex. header={'content-type':'application/j'}) requests.post發送我們要顯示的data (ex. requests.post(url,headers=header,data=json_temp)) https://www.youtube.com/watch?v=xOykNohLpAQ ## 讀API傳送過來的json檔 import json,request 定義我們要讀取的變數名稱 提出去讀url的request,放json 格式的api和要讀取的變數 (ex. url=requests.get('http://...'+cityid+'&units='+unit)) 設定變數放url讀出的內容 (ex. weather=json.load(url.text)) 後續接raspberry pi 讀到json data 後的開關燈 https://www.youtube.com/watch?v=7SRB0O4m9TY ## 數莓派和API的連接 Adafruit 作為IoT雲端平台,支援API,透過內建將資料圖形化,也可以當作一個操作的介面 總共分為三大核心Feeds(資料來源)/Dashboards(控制面板)/Triggers(觸發器) 網址: https://www.circuspi.com/index.php/2021/06/24/raspberry-pi-pico-iot/ https://www.youtube.com/watch?v=KaoYSJzywg8 ## 安裝套件 `$ sudo pip install flask` `$ sudo pip install rpi.gpio` `$ sudo pip install requests` ## ngrok設定 安裝-解壓縮-網頁登入取得 Authtoken (https://dashboard.ngrok.com/login ) 在樹莓派終端機執行 `./ngrok authtoken #Authtoken#` `./ngrok http 5000` 得到URL: http://11a9-122-116-105-235.ngrok-free.app ## 樹莓派 接API程式碼測試#1 ``` import requests from flask import Flask, request, jsonify import RPi.GPIO as GPIO app = Flask(__name__) GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # 定義 LED 初始狀態為關閉狀態 led_status = "off" # 定義外部 API 的 URL api_url = "https://your_api_url.com" @app.route('/led', methods=['POST']) def led(): # 獲取外部 API 中的 LED 狀態 global led_status response = requests.get(api_url) led_status = response.json()["led_status"] # 獲取 JSON 數據 req_data = request.get_json() # 獲取控制 LED 開關的參數 action = req_data['action'] # 根據參數控制 LED 的開關 if action == 'on': # 控制 LED 開 GPIO.output(18, GPIO.HIGH) # 控制 LED 開的代碼 led_status = "on" # 更新外部 API 的 LED 狀態 data = {"led_status": led_status} response = requests.post(api_url, json=data, headers={"Content-Type": "application/json"}) return jsonify({'message': 'LED is turned on', 'led_status': led_status}) elif action == 'off': # 控制 LED 關 GPIO.output(18, GPIO.LOW) # 控制 LED 關的代碼 led_status = "off" # 更新外部 API 的 LED 狀態 data = {"led_status": led_status} response = requests.post(api_url, json=data, headers={"Content-Type": "application/json"}) return jsonify({'message': 'LED is turned off', 'led_status': led_status}) else: return jsonify({'error': 'Invalid action'}) # 獲取 LED 的狀態 @app.route('/led', methods=['GET']) def get_led(): global led_status response = requests.get(api_url) led_status = response.json()["led_status"] return jsonify({'led_status': led_status}) if __name__ == '__main__': app.run() ``` ## 樹莓派 接API程式碼測試#2 ``` from flask import Flask, jsonify import requests import RPi.GPIO as GPIO app = Flask(__name__) GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # API for turning on the device @app.route('/on', methods=['GET']) def on(): GPIO.output(18, GPIO.HIGH) result = {'Result': 'Success'} return jsonify(result) # API for turning off the device @app.route('/off', methods=['GET']) def off(): GPIO.output(18, GPIO.LOW) result = {'Result': 'Success'} return jsonify(result) # API for getting the device state @app.route('/state', methods=['GET']) def state(): if GPIO.input(18) : result = {'State': 'on'} else: result = {'State': 'off'} return jsonify(result) if __name__ == '__main__': app.run(debug=True) ```

    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

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    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