視窗輸入

1
2
3
Serial.begin(9600);
Serial.available();
Serial.read();

LED

1
2
digitalWrite(PIN, HIGH);
digitalWrite(PIN, LOW);

七段顯示器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#define NUM 8
int pins[NUM] = {4, 5, 8, 7, 6, 3, 2, 9};
#define t true
#define f false
boolean data[10][NUM] = {
{t, t, t, t, t, t, f, f},
{f, t, t, f, f, f, f, f},
{t, t, f, t, t, f, t, f},
{t, t, t, t, f, f, t, f},
{f, t, t, f, f, t, t, f},
{t, f, t, t, f, t, t, f},
{t, f, t, t, t, t, t, f},
{t, t, t, f, f, f, f, f},
{t, t, t, t, t, t, t, f},
{t, t, t, t, f, t, t, f}
};
void writeNumber(int n) {
for (int i = 0; i < NUM; i++) {
digitalWrite(pins[i], data[n][i] == t ? HIGH : LOW);
}
}

蜂鳴器

1
2
3
4
5
6
7
8
#define Do 1046
#define Re 1175
#define Mi 1319
#define Fa 1397
#define So 1568
int tune[] = {Do, Re, Mi, Fa, So};
tone(PIN, FREQUENCY, DURATION);
tone(10, tune[i], 500);

光敏電阻

1
analogRead(PIN);

LCD

1
2
3
4
5
6
7
8
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
lcd.begin(16, 2);
lcd.backlight(); // 開啟背光
lcd.noBacklight(); // 關閉背光
lcd.setCursor(0, 0); // 設定游標位置
lcd.print("Hello, world!"); // 輸出字串

溫溼度感測器

1
2
3
4
5
6
7
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
dht.begin(); // 初始化
dht.readTemperature(); // 讀取溫度
dht.readHumidity(); // 讀取濕度

超音波感測器

1
2
3
4
5
6
7
8
#define TRIG_PIN 2
#define ECHO_PIN 3
long duration, distance;
digitalWrite(trig, HIGH); // 發出超音波
delayMicroseconds(1000); // 1ms
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH); // 計算回波時間
distance = (duration / 2) / 29; // 計算距離