Tags: , , ,

Un robot está constituido por cuatro componentes principales: Motores para el movimiento, Mecánica para mantener las piezas unidas, sensores para que reaccionen al entorno y un código para controlarlas y crear la funcionalidad deseada.

Sensors plays an important role when dealing with autonomous robot. We’ll see here how to use them.

 

Presentation

The purpose of a sensor is to measure a physical value (velocity, angle, temperature, etc.). There are numerous sensors of different types passive and active (require powering). In this example, we use a photoresistor but it can be applied to other type of sensor.

Here is a list of sensor :

Passif:

  • photoresistor
  • tilt
  • push button

Actif:

  • infrared distance sensor
  • ultrasonic distance sensor

 

Wiring

Sensor have different wiring depending on the number of pin they use. Usually a sensor has 3 pins ground, voltage supply 5V and the signal. For passive sensor, a third output as to be created to read the voltage at its ends.

pushbutton scheme

infrared sensor scheme

Base code to read sensor

Depending on its type, sensor can return two informations: a state (presence or not) or a continous voltage value.

To read a state, the function to use is digitalRead(). It returns a level HIGH or LOW which represent the voltage applied on the digital pin (0, 1 , 2, etc.).

/*Read digital state*/
// Constants
#define DELAY 500 // Delay between two measurements in ms

// Parameters
const int sensorPin = 2; // Pin connected to sensor

//Variables
int sensorState; // state from the sensor

void setup(void) {
  Serial.begin(9600);
  pinMode(sensorPin,INPUT);
}

void loop(void) {
  sensorState = digitalRead(sensorPin);
 
  if (sensorState == HIGH) {
     Serial.print("Sensor state is HIGH ");
  } else {
     Serial.print("Sensor state is LOW ");
  }
  delay(DELAY);
}

 

To read a continuous value, the function we use is analogRead() . It returns a value between 0 and 1023 representing the voltage applied on the Arduino analog pin (A0, A1, A2, etc.).

/*Read analog signal*/
// Constants
#define DELAY 500 // Delay between two measurements in ms

// Parameters
const int sensorPin = A0; // Pin connected to sensor

//Variables
int sensorVal; // Analog value from the sensor

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

void loop(void) {
  sensorVal = analogRead(sensorPin);
  Serial.print("Sensor reading = ");
  Serial.println(sensorVal); // the analog reading
  delay(DELAY);
}

 

Use cases

Measure temperature and humidity with sensor DHT11

Measure temperature with sensor LM35

Distance measurement with sensor HC-SR04

 Luminosity measurement with a photoresistor