Skip to content

常用传感器 ​

传感器是 Arduino 项目里最容易「看起来简单、实际踩坑」的部分。这里整理三个最常用的:温湿度、超声波测距、光敏。

DHT11 温湿度 ​

便宜、够用,但精度一般(温度 ±2°C,湿度 ±5%),采样间隔建议不小于 1 秒。

接线 ​

DHT11Arduino
VCC5V
GNDGND
DATA引脚 2(需要 10kΩ 上拉到 5V,很多模块自带)

代码 ​

先装库:Arduino IDE → 库管理器 → 搜索 DHT sensor library(Adafruit)。

cpp
#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  float t = dht.readTemperature();
  float h = dht.readHumidity();

  if (isnan(t) || isnan(h)) {
    Serial.println("DHT 读取失败");
    return;
  }

  Serial.print("温度: ");
  Serial.print(t);
  Serial.print(" C, 湿度: ");
  Serial.print(h);
  Serial.println(" %");

  delay(2000);
}

HC-SR04 超声波测距 ​

通过发射超声波、接收回波的时间差算距离。有效范围大约 2cm–400cm。

接线 ​

HC-SR04Arduino
VCC5V
GNDGND
Trig引脚 9
Echo引脚 10

代码 ​

cpp
const int trigPin = 9;
const int echoPin = 10;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH, 30000);
  if (duration == 0) {
    Serial.println("无回波");
    return;
  }

  float cm = duration * 0.0343 / 2.0;
  Serial.print(cm);
  Serial.println(" cm");

  delay(200);
}

声速按 343 m/s 计算,除以 2 是因为声音走了一个来回。

光敏电阻 ​

配合分压电路,把光强变化转成电压变化。

接线 ​

5V ── 光敏电阻 ── A0 ── 10kΩ ── GND

代码 ​

cpp
void setup() {
  Serial.begin(9600);
}

void loop() {
  int value = analogRead(A0);   // 0–1023
  Serial.println(value);
  delay(200);
}

数值越小通常表示越亮(取决于分压位置),实际方向可以遮住传感器观察变化。

I2C OLED(顺带一提) ​

0.96 寸 SSD1306 是常见搭配,只用两根信号线:

OLEDArduino
VCC3.3V 或 5V(看模块)
GNDGND
SCLA5(Uno)
SDAA4(Uno)

库用 Adafruit SSD1306 + Adafruit GFX。I2C 地址通常是 0x3C,扫描不到时先跑一个 I2C scanner 确认。

踩坑清单 ​

  • 读数全 0 或全 1023:先查共地,再查模块供电。
  • DHT 一直返回 NaN:采样太快、上拉电阻缺失、或引脚接错。
  • 超声波偶尔跳变:正常现象,取多次中位数或加超时判断。
  • 多个 I2C 设备冲突:确认地址不同;相同地址需要 TCA9548A 之类的多路器。

记录 Arduino 与 Vibe Coding 的实践 · 纯静态站点,无广告、无追踪