Arduino & IoT Fundamentals

Inputs, Outputs and Sensors

35 分

Digital inputs: buttons

const int BUTTON = 2;
const int LED = 13;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);   // internal resistor: reads HIGH when not pressed
  pinMode(LED, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  bool pressed = digitalRead(BUTTON) == LOW;
  digitalWrite(LED, pressed ? HIGH : LOW);
  if (pressed) Serial.println("Button pressed");
  delay(20);                        // crude debounce
}

Open the Serial Monitor at the same baud rate to see messages: your main debugging tool.

Analog inputs

int raw = analogRead(A0);                 // 0–1023 on Uno (resolution varies by board)
float volts = raw * (5.0 / 1023.0);

Use for potentiometers, light-dependent resistors and analog sensors.

PWM outputs

analogWrite(pin, 0–255) rapidly switches a pin to simulate varying power: dimming LEDs, controlling motor speed (through a driver), servo-like effects.

Sensors you will meet

Sensor Measures Interface
DHT22 / BME280 temperature, humidity (BME280: pressure) digital / I²C
HC-SR04 distance (ultrasonic) digital pulses
PIR motion digital
Soil moisture soil water analog
Photoresistor light analog

Communication buses

  • I²C: two wires (SDA, SCL) shared by many devices with different addresses; common for sensors and small displays.
  • SPI: faster, more wires; displays and SD cards.
  • UART (Serial): GPS modules, other boards.

Install libraries through the Library Manager and start from their examples.

Avoid delay() in real projects

delay() stops everything. Use timing with millis() so your program can read sensors, update displays and handle buttons at the same time:

unsigned long last = 0;
void loop() {
  if (millis() - last >= 2000) { last = millis(); readSensor(); }
  handleButtons();
}

Exercise

Build a mini weather station: a BME280 (or DHT22) printing temperature and humidity to the Serial Monitor every two seconds, an LED that lights above a temperature threshold, and a button to toggle units, all without delay().

Check yourself

  • What does INPUT_PULLUP do?
  • Why replace delay() with millis() timing?
  • How do several I²C devices share two wires?

進捗はこのブラウザーにのみ保存されます。

レビューに提出(10 ポイント)