Lesson 12 / 12100%

Lesson 12

Sensors and Servo Motor

28 min

Measure temperature and distance, and drive a servo motor with the Servo library.

Measuring temperature with the TMP36

The TMP36 is a small three-legged sensor that outputs a voltage varying linearly with temperature. It is very simple to connect: one leg to 5V, one to GND, and the middle leg to input A0. Pay close attention to the orientation: with the flat face turned toward you, the legs are in the order 5V, signal, GND from left to right.

Wiring diagram: the TMP36 sensor seen from the front (flat side) with its three legs connected to 5V, A0 and GND.

According to the component's datasheet, it outputs 0.5 V at 0 °C, with a change of 10 mV per degree. To get the temperature, you convert the reading to volts, then apply the sensor's formula.

thermometer.ino
const int sensorPin = A0;

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

void loop() {
  int reading = analogRead(sensorPin);
  float voltage = reading * 5.0 / 1023.0;
  float temperature = (voltage - 0.5) * 100.0;

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" C");

  delay(1000);
}

Put your finger on the sensor: you will see the temperature slowly rise. Readings may fluctuate by a degree or two: this is normal with this kind of inexpensive sensor.

Measuring a distance with the HC-SR04

The HC-SR04 is an ultrasonic sensor, like a bat's sonar. It sends out an inaudible sound pulse, waits for its echo, and measures the elapsed time: the farther away the obstacle is, the longer the echo takes to come back. It has four pins: VCC(5V), Trig (triggers the measurement), Echo(returns the duration) and GND.

Wiring diagram: an HC-SR04 sensor with VCC on 5V, Trig on pin 7, Echo on pin 6 and GND on GND.Diagram: the principle of the ultrasonic sensor (a wave is emitted, reflects off an obstacle, and the echo returns) with the distance formula.

Sound travels about 0.034 cm per microsecond. The echo makes a round trip, so the total time must be divided by two:

distance = duration × 0.034 / 2
distance (cm) = duration (microseconds) × 0.034 / 2
distance.ino
const int trigPin = 7;
const int echoPin = 6;

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

float measureDistance() {
  // 10-microsecond pulse on Trig
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Duration of the pulse received on Echo (in microseconds)
  long duration = pulseIn(echoPin, HIGH, 30000);

  return duration * 0.034 / 2;
}

void loop() {
  float distance = measureDistance();

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(300);
}

Good to know

The HC-SR04 measures from 2 cm to about 4 m. The third parameter ofpulseIn() is a maximum wait time (30,000 microseconds): beyond that, the function returns 0, which prevents the program from blocking if no echo comes back. A value of 0 therefore means "nothing detected".

Controlling a servo motor

A servo motor is a small motor that can move to a precise angle, usually between 0 and 180 degrees. It is used for robot arms, flaps, barriers... It has three wires:brown or black (GND), red (5V) andorange or yellow (signal, connected to a digital pin such as 9).

To simplify control, Arduino provides a librarycalled Servo, already installed. You include it with #include.

servo_sweep.ino
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9);   // the servo is connected to pin 9
}

void loop() {
  for (int angle = 0; angle <= 180; angle += 2) {
    myServo.write(angle);
    delay(15);
  }
  for (int angle = 180; angle >= 0; angle -= 2) {
    myServo.write(angle);
    delay(15);
  }
}

Power supply

A small servo motor can be connected directly to the board, but it draws current when starting up and when stalled. For larger motors, or several servo motors, you need an external power supply. Neverconnect a regular (DC) motor directly to a pin on the board: you need a transistor or a dedicated driver circuit.

Controlling the servo with a potentiometer

servo_potentiometer.ino
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9);
}

void loop() {
  int reading = analogRead(A0);
  int angle = map(reading, 0, 1023, 0, 180);
  myServo.write(angle);
  delay(15);
}
GIF: a servo motor following the rotation of a potentiometer.

Exercise

Build a needle thermometer: a servo motor shows the temperature measured by the TMP36, mapping 15 °C to 0 degrees and 35 °C to 180 degrees withmap(). Remember to use whole-number values or to convert properly.