---
# System prepended metadata

title: Arduino課程講義

---

# Arduino課程講義

https://reurl.cc/r5dqxN


## Arduino IDE 安裝
- [x] https://www.arduino.cc/en/software

## Arduino 設定
- [ ] File > Preferences > Additional board manager URLs
https://arduino.esp8266.com/stable/package_esp8266com_index.json
- [ ] Tools > Board “LOLIN(WEMOS) D1 R2 & mini”

## DHT11 Library Download

下載 dht11-master.zip

- https://codeload.github.com/adidax/dht11/zip/refs/heads/master



## 透過DHT取得溫濕度(亮度)的程式碼


```
#include <dht11.h>


dht11 DHT;

// setup() 會先被執行且只會執行一次
void setup() {
  // 設定serial傳輸率
  Serial.begin(9600);

  // 將 A0 設定為輸入
  pinMode(A0, INPUT);
}

// loop() 裡面的程式會不斷重複執行
void loop() {
  // 讀取 D2
  DHT.read(D2);

  // 讀取 D2 後的值寫到 serial port
  Serial.print("temperature:");
  Serial.print(DHT.temperature);
  Serial.print("    humidity:");
  Serial.print(DHT.humidity);
  
  // 讀取 A0 並將值轉化為 0~99
  Serial.print("    light:");
  Serial.println((map(analogRead(A0), 0, 1024, 0, 99)));

  // 等待 2 秒再抓取資料
  delay(2000);  
}
```


## Python

下載

- https://www.python.org/ftp/python/3.11.3/python-3.11.3-amd64.exe

安裝

- Add python.exe to PATH
- Install Now

## Python 程式

```bash
pip install serial
pip install pyserial
pip install pymysql

```

```python
import datetime
import serial
import serial.tools.list_ports
import pymysql

# 列出可用的 COM Port
ports = serial.tools.list_ports.comports()
for port in ports:
        print(f"{port.device}: {port.description}")

# 讀取資料, 按下 Ctrl-C 中斷
with serial.Serial('COM5', 9600) as ser:
    while True:
        line = ser.readline().decode('utf-8').strip()
        print(line)

```

## Arduino -> SQL Server

```python
import serial
import serial.tools.list_ports
import pyodbc

# 列出可用的 COM Port
ports = serial.tools.list_ports.comports()
for port in ports:
        print(f"{port.device}: {port.description}")

# 寫入資料庫
def insert(sql):
    with pyodbc.connect(conn_str) as conn:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()


# 建立SQL
def line_sql(line):
    if ('temperature' in line):
        list = line.split('    ')
        print(list)
        
        # 抓數字，加時間
        temp = list[0].split(':')[1]
        hum = list[1].split(':')[1]
        light = list[2].split(':')[1]
        
        sql = f'INSERT INTO dht (temp, hum, light) VALUES ({temp} {hum}, {light})'
        insert(sql)


# 讀取資料, 按下 Ctrl-C 中斷
with serial.Serial('COM5', 9600) as ser:
    while True:
        line = ser.readline().decode('utf-8').strip()
        # print(line)
        line_sql(line)

```

## Power BI Desktop

下載

- https://www.microsoft.com/en-us/download/details.aspx?id=58494



Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;