A sensor is an element which can turn a physical outer stimulus into an output signal which then can be used for further analysis, the management or decision making. People also use sensors like eyes, ears and skin for gaining information about the outer world and act accordingly to their aims and needs. Sensors can be divided into multiple categories by the parameter that is perceived from the environment.
Usually, every natural phenomenon – temperature, weight, speed, etc. – needs specially customised sensors which can change every phenomenon into electronic signals that could be used by microprocessors or other devices. Sensors can be divided into many groups according to the physical nature of their operations – touch, light, an electrical characteristic, proximity and distance, angle, environment and other sensors.
A pushbutton is an electromechanical sensor that connects or disconnects two points in a circuit when the force is applied. Button output discrete value is either HIGH or LOW.
A microswitch, also called a miniature snap-action switch, is an electromechanical sensor that requires a very little physical force and uses tipping-point mechanism. Microswitch has three pins, two of which are connected by default. When the force is applied, the first connection breaks and one of the pins is connected to the third pin.
The most common use of a pushbutton is as an input device. Both force solutions can be used as simple object detectors, or as end switches in the industrial devices.
An example code:
int buttonPin = 2; //Initialization of a push button pin number int buttonState = 0; //A variable for reading the push button status void setup() { Serial.begin(9600); //Begin serial communication pinMode(buttonPin, INPUT); //Initialize the push button pin as an input } void loop() { //Read the state of the push button value buttonState = !digitalRead(buttonPin); //Check if the push button is pressed. If it is, the buttonState is HIGH if (buttonState == HIGH) { //Print out text in the console Serial.println("The button state is HIGH - it is pressed."); } else { Serial.println("The button state is LOW - it is not pressed."); } delay(10); //Delay in between reads for stability }
A force sensor predictably changes resistance, depending on the applied force to its surface. Force-sensing resistors are manufactured in different shapes and sizes, and they can measure not only direct force but also the tension, compression, torsion and other types of mechanical forces. The voltage is measured by applying and measuring constant voltage to the sensor.
Force sensors are used as control buttons or to determine weight.
An example code:
//Force Sensitive Resistor (FSR) is connected to the analog 0 pin int fsrPin = A0; //The analog reading from the FSR resistor divider int fsrReading; void setup(void) { //Begin serial communication Serial.begin(9600); //Initialize the FSR analog pin as an input pinMode(fsrPin, INPUT); } void loop(void) { //Read the resistance value of the FSR fsrReading = analogRead(fsrPin); //Print Serial.print("Analog reading = "); Serial.println(fsrReading); delay(10); }
Capacitive sensors are a range of sensors that use capacitance to measure changes in the surrounding environment. A capacitive sensor consists of a capacitor that is charged with a certain amount of current until the threshold voltage. A human finger, liquids or other conductive or dielectric materials that touch the sensor, can influence a charge time and a voltage level in the sensor. Measuring charge time and a voltage level gives information about changes in the environment.
Capacitive sensors are used as input devices and can measure proximity, humidity, fluid level and other physical parameters or serve as an input for electronic device control.
//Capacitive sensor is connected to the digital 2 pin int touchPin = 2; //The digital reading value from the sensor boolean touchReading = LOW; //The variable that stores the previous state value boolean lastState = LOW; void setup() { //Begin serial communication Serial.begin(9600); //Initialize the capacitive sensor analog pin as an input pinMode(touchPin, INPUT); } void loop() { //Read the digital value of the capacitive sensor touchReading = digitalRead(touchPin); //If the new touch has appeared if (currentState == HIGH && lastState == LOW){ Serial.println("Sensor is pressed"); delay(10); //short delay } //Save previous state to see relative changes lastState = currentState; }
A photoresistor is a sensor that perceives light waves from the environment. The resistance of the photoresistor is changing depending on the intensity of light. The higher is the intensity of the light; the lower is the resistance of the sensor. A light level is determined by applying a constant voltage sensor and measuring it. Photodiodes, compared to photoresistors, are slower and more influenced by temperature; thus, they are more imprecise.
Photoresistors are often used in the energy effective street lightning.
An example code:
//Define an analog A0 pin for photoresistor int photoresistorPin = A0; //The analog reading from the photoresistor int photoresistorReading; void setup() { //Begin serial communication Serial.begin(9600); //Initialize the analog pin of a photoresistor as an input pinMode(photoresistorPin, INPUT); } void loop() { //Read the value of the photoresistor photoresistorReading = analogRead(photoresistorPin); //Print out value of the photoresistor reading to the serial monitor Serial.println(photoresistorReading); delay(10); //Short delay }
A photodiode is a sensor that converts the light energy into electrical current. A current in the sensor is generated by exposing a p-n junction of a semiconductor to the light. Information about the light intensity can be determined by measuring a voltage level. Photodiodes are reacting to the changes in the light intensity very quickly. Solar cells are just large photodiodes.
Photodiodes are used as precise light level sensors, receivers for remote control, electrical isolators and proximity detectors.
An example code:
//Define an analog A0 pin for photodiode int photodiodePin = A0; //The analog reading from the photodiode int photodiodeReading; void setup() { //Begin serial communication Serial.begin(9600); //Initialize the analog pin of a photodiode as an input pinMode(photodiodePin, INPUT); } void loop() { //Read the value of the photodiode photodiodeReading = analogRead(photodiodePin); //Print out the value of the photodiode reading to the serial monitor Serial.println(photodiodeReading); delay(10); //Short delay }
A phototransistor is a light controlled electrical switch. In the exposed Base pin received light level, changes the amount of current, that can pass between two phototransistor pins – a collector and an emitter. A phototransistor is slower than the photodiode, but it can conduct more current.
Phototransistors are used as the optical switches, proximity sensors and electrical isolators.
An example code:
//Define an analog A1 pin for phototransistor int phototransistorPin = A1; //The analog reading from the phototransistor int phototransistorReading; void setup() { //Begin serial communication Serial.begin(9600); //Initialize the analog pin of a phototransistor as an input pinMode(phototransistorPin, INPUT); } void loop() { //Read the value of the phototransistor phototransistorReading = analogRead(phototransistorPin); //Print out the value of the phototransistor reading to the serial monitor Serial.println(phototransistorReading); delay(10); //short delay }
Electrical characteristic sensors are used to determine whether the circuit of the device is working properly. When the voltage and current sensors are used concurrently, the consumed power of the device can be determined.
A voltage sensor is a device or circuit for voltage measurement. A simple DC (direct current) voltage sensor consists of a voltage divider circuit with the optional amplifier for very small voltage occasions. For measuring the AC (alternating current), a transformer is added to a lower voltage; then it is connected to the rectifier to rectify AC to DC, and finally, an optoelectrical isolator is added for measuring circuit safety.
A voltage sensor can measure electrical load and detect a power failure. Examples of IoT applications are monitoring of appliance, line power, power coupling, power supply and sump pump.
The example code:
//Define an analog A1 pin for voltage sensor int voltagePin = A1; //The analog reading from the voltage sensor int voltageReading; float vout = 0.0; float vin = 0.0; float R1 = 30000.0; // 30 kΩ resistor float R2 = 7500.0; // 7.5 kΩ resistor void setup() { //Begin serial communication Serial.begin(9600); //Initialize the analog pin of a voltage sensor as an input pinMode(voltagePin, INPUT); } void loop() { //Read the value of the voltage sensor voltageReading = analogRead(voltagePin); vout = (voltageReading * 5.0) / 1024.0; vin = vout / (R2/(R1+R2)); Serial.print("Voltage is: "); //Print out the value of the voltage to the serial monitor Serial.println(vin); delay(10); //Short delay }
A current sensor is a device or a circuit for current measurement. A simple DC sensor consists of a high power resistor with low resistance. The current is obtained by measuring the voltage on the resistor and applying formula proportional to the voltage. Other non-invasive measurement methods involve hall effect sensors for DC and AC and inductive coils for AC. Current sensors are used to determine the power consumption, to detect whether the device is turned on, short circuits.
The example code:
//Define an analog A0 pin for current sensor const int currentPin = A0; //Scale factor of the sensor use 100 for 20 A Module and 66 for 30 A Module int mVperAmp = 185; int currentReading; int ACSoffset = 2500; double Voltage; double Current; void setup(){ Serial.begin(9600); } void loop(){ currentReading = analogRead(currentPin); Voltage = (currentReading / 1024.0) * 5000; //Gets you mV Current = ((Voltage - ACSoffset) / mVperAmp); //Calculating current value Serial.print("Raw Value = " ); //Shows pre-scaled value Serial.print(currentReading); Serial.print("\t Current = "); //Shows the voltage measured //The '3' after current allows to display 3 digits after decimal point Serial.println(Current,3); delay(1000); //Short delay
An optocoupler is a device that combines light emitting and receiving devices. Mostly it is a combination of the infrared light-emitting diode (LED) and a phototransistor. Other optical semiconductors can be a photodiode and a photoresistor. There are two main types of optocouplers:
An example code:
int optoPin = A0; //Initialize an analog A0 pin for optocoupler int optoReading; //The analog value reading from the optocoupler int objecttreshold = 1000; //Object threshold definition int whitetreshold = 150; //White colour threshold definition void setup () { //Begin serial communication Serial.begin(9600); //Initialize the analog pin of the optocoupler as an input pinMode(optoPin, INPUT); } void loop () { optoReading = analogRead(optoPin); //Read the value of the optocoupler Serial.print ("The reading of the optocoupler sensor is: "); Serial.println(optoReading); //When the reading value is lower than the object threshold if (optoReading < objecttreshold) { Serial.println ("There is an object in front of the sensor!"); //When the reading value is lower than the white colour threshold if (optoReading < white threshold) { Serial.println ("Object is in white colour!"); } else { //When the reading value is higher than the white colout threshold Serial.println ("Object is in dark colour!"); } } else { //When the reading value is higher than the object thershold Serial.println ("There is no object in front of the sensor!"); } delay(500); //Short delay }
Infrared (IR) proximity sensor is used to detect objects and to measure the distance to them, without any physical contact. IR sensor consists of an infrared emitter, a receiving sensor or array of sensors and a signal processing logic. The output of a sensor differs depending on the type – simple proximity detection sensor outputs HIGH or LOW level when an object is in its sensing range, but sensors which can measure distance outputs an analogue signal or use some communication protocol, like I2C to send sensor measuring results. IR sensors are used in robotics to detect obstacles starting from few millimetres to several meters and in mobile phones to help detect accidental button touching.
An example code:
int irPin = A0; //Define an analog A0 pin for IR sensor int irReading; //The analog reading from the IR sensor void setup() { //Begin serial communication Serial.begin(9600); //Initialize the analog pin of a IR sensor as an input pinMode(irPin, INPUT); } void loop() { //Read the value of the IR sensor irReading = analogRead(irPin); //Print out the value of the IR sensor reading to the serial monitor Serial.println(irReading); delay(10); //Short delay }
Ultrasound (ultrasonic) sensor measures the distance to objects by emitting ultrasound and measuring its returning time. The sensor consists of an ultrasonic emitter and receiver; sometimes, they are combined in a single device for emitting and receiving. Ultrasonic sensors can measure greater distances and cost less than infrared sensors, but are more imprecise and interfere which each other measurement if more than one is used. Simple sensors have trigger pin and echo pin, when the trigger pin is set high for the small amount of time ultrasound is emitted and on echo pin, response time is measured. Ultrasonic sensors are used in car parking sensors and robots for proximity detection.
Examples of IoT applications are robotic obstacle detection and room layout scanning.
An example code:
int trigPin = 2; //Define a trigger pin D2 int echoPin = 4; //Define an echo pin D4 void setup() { Serial.begin(9600); //Begin serial communication pinMode(trigPin, OUTPUT); //Set the trigPin as an Output pinMode(echoPin, INPUT); //Set the echoPin as an Input } void loop() { digitalWrite(trigPin, LOW); //Clear the trigPin delayMicroseconds(2); //Set the trigPin on HIGH state for 10 μs digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); //Read the echoPin, return the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); //Calculating the distance distance= duration*0.034/2; //Printing the distance on the Serial Monitor Serial.print("Distance: "); Serial.println(distance); }
The motion detector is a sensor that detects moving objects, most people. Motion detectors use different technologies, like passive infrared sensors, microwaves and Doppler effect, video cameras and previously mentioned ultrasonic and IR sensors. Passive IR sensors are the simplest motion detectors that sense people trough detecting IR radiation that is emitted through the skin. When the motion is detected, the output of a motion sensor is a digital HIGH/LOW signal.
Motion sensors are used for security purposes, automated light and door systems. As an example in IoT, the PIR motion sensor can be used to detect motion in security systems a house or any building.
An example code:
//Passive Infrared (PIR) sensor output is connected to the digital 2 pin int pirPin = 2; //The digital reading from the PIR output int pirReading; void setup(void) { //Begin serial communication Serial.begin(9600); //Initialize the PIR digital pin as an input pinMode(pirPin, INPUT); } void loop(void) { //Read the digital value of the PIR motion sensor pirReading = digitalRead(pirPin); //Print out Serial.print("Digital reading = "); Serial.println(pirReading); if(pirReading == HIGH) { //Motion was detected Serial.println("Motion Detected"); } delay(10); }
A potentiometer is a type of resistor, the resistance of which can be adjusted using a mechanical lever. The device consists of three terminals. The resistor between the first and the third terminal has fixed value, but the second terminal is connected to the lever. Whenever the lever is turned, a slider of the resistor is moved, it changes the resistance between the second terminal and side terminals. Variable resistance causes the change of the voltage variable, and it can be measured to determine the position of the lever. Thus, potentiometer output is an analogue value.
Potentiometers are commonly used as a control level, for example, a volume level for the sound and joystick position. They can also be used for angle measurement in feedback loops with motors, for example, in servo motors.
An example code:
//Potentiometer sensor output is connected to the analog A0 pin int potentioPin = A0; //The analog reading from the potentiometer output int potentioReading; void setup(void) { //Begin serial communication Serial.begin(9600); //Initialize the potentiometer analog pin as an input pinMode(potentioPin, INPUT); } void loop(void) { //Read the analog value of the potentiometer sensor potentioReading = analogRead(potentioPin); Serial.print("Potentiometer reading = "); //Print out Serial.println(potentioReading); delay(10); }
An IMU is an electronic device, that consist of accelerometer, gyroscope and sometimes also a magnetometer. Combination of these sensors returns the orientation of the object in 3D space.
A gyroscope is a sensor that measures the angular velocity. The sensor is made of the microelectromechanical system (MEMS) technology and is integrated into the chip. The output of the sensor can be either analogue or digital value of information, using I2C or SPI interface. Gyroscope microchips can vary in the number of axes they can measure. The available number of the axis is 1, 2 or 3 axes in the gyroscope. For gyroscopes with 1 or 2 axes, it is essential to determine which axis the gyroscope measures and to choose a device according to the project needs. A gyroscope is commonly used together with an accelerometer, to determine the orientation, position and velocity of the device precisely. Gyroscope sensors are used in aviation, navigation and motion control.
A magnetometer is the sensor, that can measure the orientation of the device to the magnetic field of the Earth. A magnetometer is used in outdoor navigation for mobile devices, robots, quadcopters.
An accelerometer measures the acceleration of the object. The sensor uses a microelectromechanical system (MEMS) technology, where capacitive plates are attached to springs. When acceleration force is applied to the plates, the capacitance is changed; thus, it can be measured. Accelerometers can have 1 to 3 axis. On 3-axis, the accelerometer can detect orientation, shake, tap, double tap, fall, tilt, motion, positioning, shock or vibration of the device. Outputs of the sensor are usually digital interfaces like I2C or SPI. For precise measurement of the object movement and orientation in space, the accelerometer is often used together with a gyroscope. Accelerometers are used for measuring vibrations of cars, industrial devices, buildings and to detect volcanic activity. In IoT applications, it can be used as well for accurate motion detection for medical and home appliances, portable navigation devices, augmented reality, smartphones and tablets.
The example code:
//Library for I2C communication #include <Wire.h> //Downloaded from https://github.com/adafruit/Adafruit_Sensor #include <Adafruit_Sensor.h> //Downloaded from https://github.com/adafruit/Adafruit_BNO055 #include <Adafruit_BNO055.h> #include <utility/imumaths.h> Adafruit_BNO055 bno = Adafruit_BNO055(55); void setup(void) { bno.setExtCrystalUse(true); } void loop(void) { //Read sensor data sensors_event_t event; bno.getEvent(&event); //Print X, Y And Z orientation Serial.print("X: "); Serial.print(event.orientation.x, 4); Serial.print("\tY: "); Serial.print(event.orientation.y, 4); Serial.print("\tZ: "); Serial.print(event.orientation.z, 4); Serial.println(""); delay(100); }
A temperature sensor is a device that is used to determine the temperature of the surrounding environment. Most temperature sensors work on the principle that the resistance of the material is changed depending on its temperature. The most common temperature sensors are:
The main difference between sensors is the measured temperature range, precision and response time. Temperature sensor usually outputs the analogue value, but some existing sensors have a digital interface [1].
The temperature sensors most commonly are used in environmental monitoring devices and thermoelectric switches. In IoT applications, the sensor can be used for greenhouse temperature monitoring, warehouse temperature monitoring to avoid frozen fire suppression systems and tracking temperature of the soil, water and plants.
An example code:
//Thermistor sensor output is connected to the analog A0 pin int thermoPin = 0; //The analog reading from the thermistor output int thermoReading; void setup(void) { //Begin serial communication Serial.begin(9600); //Initialize the thermistor analog pin as an input pinMode(thermoPin, INPUT); } void loop(void) { //Read the analog value of the thermistor sensor thermoReading = analogRead(thermoPin); Serial.print("Thermistor reading = "); //Print out Serial.println(thermoReading); delay(10); }
A humidity sensor (hygrometer) is a sensor that detects the amount of water or water vapour in the environment. The most common principle of the air humidity sensors is the change of capacitance or resistance of materials that absorb the moisture from the environment. Soil humidity sensors measure the resistance between the two electrodes. The resistance between electrodes is influenced by soluble salts and water amount in the soil. The output of a humidity sensor is usually an analogue signal value [2].
Example IoT applications are monitoring of humidor, greenhouse temperature and humidity, agriculture, art gallery and museum environment.
An example code [3]:
#include <dht.h> dht DHT; #define DHT_PIN 7 void setup(){ Serial.begin(9600); } void loop() { int chk = DHT.read11(DHT_PIN); Serial.print("Humidity = "); Serial.println(DHT.humidity); delay(1000); }
A sound sensor is a sensor that detects vibrations in a gas, liquid or solid environments. At first, the sound wave pressure makes mechanical vibrations, who transfers to changes in capacitance, electromagnetic induction, light modulation or piezoelectric generation to create an electric signal. The electrical signal is then amplified to the required output levels. Sound sensors, can be used to record sound, detect noise and its level.
Sound sensors are used in drone detection, gunshot alert, seismic detection and vault safety alarm.
An example code:
//Sound sensor output is connected to the digital 7 pin int soundPin = 7; //Stores sound sensor detection readings int soundReading = HIGH; void setup(void) { //Begin serial communication Serial.begin(9600); //Initialize the sound detector module pin as an input pinMode(soundPin, INPUT); } void loop(void) { //Read the digital value whether the sound has been detected soundReading = digitalRead(soundPin); if (soundPin==LOW) { //When sound detector detected the sound Serial.println("Sound detected!"); //Print out } else { //When the sound is not detected Serial.println("Sound not detected!"); //Print out } delay(10); }
Gas sensors are a sensor group, that can detect and measure a concentration of certain gasses in the air. The working principle of electrochemical sensors is to absorb the gas and to create current from an electrochemical reaction. For process acceleration, a heating element can be used. For each type of gas, different kind of sensor needs to be used. Multiple different types of gas sensors can be combined in a single device as well. The single gas sensor output is an analogue signal, but devices with multiple sensors used to have a digital interface.
Gas sensors are used for safety devices, to control air quality and for manufacturing equipment. Examples of IoT applications are air quality control management in smart buildings and smart cities or toxic gas detection in sewers and underground mines.
An example code:
int gasPin = A0; //Gas sensor output is connected to the analog A0 pin int gasReading; //Stores gas sensor detection reading void setup(void) { Serial.begin(9600); //Begin serial communication pinMode(gasPin, INPUT); //Initialize the gas detector pin as an input } void loop(void) { gasReading = analogRead(gasPin); //Read the analog value of the gas sensor Serial.print("Gas detector value: "); //Print out Serial.println(gasReading); delay(10); //Short delay }
A level sensor detects the level of fluid or fluidised solid. Level sensors can be divided into two groups:
Level sensors can be used as smart waste management, for measuring tank levels, diesel fuel gauging, liquid assets inventory, chemical manufacturing high or low-level alarms and irrigation control.
An example code:
int levelPin = 6; //Liquid level sensor output is connected to the digital 6 pin int levelReading; //Stores level sensor detection reading void setup(void) { Serial.begin(9600); //Begin serial communication pinMode(levelPin, INPUT); //Initialize the level sensor pin as an input } void loop(void) { levelReading = digitalRead(levelPin); //Read the digital value of the level sensor Serial.print("Level sensor value: "); //Print out Serial.println(levelReading); delay(10); //Short delay }
A Hall effect sensor detects strong magnetic fields, their polarities and the relative strength of the field. In the Hall effect sensors, a magnetic force influences current flow through the semiconductor material and creates a measurable voltage on the sides of the semiconductor. Sensors with analogue output can measure the strength of the magnetic field, while digital sensors give HIGH or LOW output value, depending on the presence of the magnetic field.
Hall effect sensors are used in magnetic encoders for speed measurements and magnetic proximity switches because it does not require contact, and it ensures high reliability. Example application can be sensing the position of rotary valves.
Thw example code:
int hallPin = A0; //Hall sensor output is connected to the analog A0 pin int hallReading; //Stores hallsensor detection reading void setup(void) { Serial.begin(9600); //Begin serial communication pinMode(hallPin, INPUT); //Initialize the hallsensor pin as an input } void loop(void) { hallReading = analogRead(hallPin); //Read the analog value of the hall sensor Serial.print("Hall sensor value: "); //Print out Serial.println(hallReading); delay(10); //Short delay }
A GPS receiver is a device, that can receive information from a global navigation satellite system and calculate its position on the Earth. GPS receiver uses a constellation of satellites and ground stations to compute position and time almost anywhere on the Earth. GPS receivers are used for navigation only in the outdoor area because it needs to receive signals from the satellites. The precision of the GPS location can vary.
A GPS receiver is used for device location tracking. Real world applications might be, i.e., pet, kid or personal belonging location tracking.
The example code [4]:
#include <SoftwareSerial.h> SoftwareSerial SoftSerial(2, 3); unsigned char buffer[64]; //Buffer array for data receive over serial port int count=0; //Counter for buffer array void setup() { SoftSerial.begin(9600); //The SoftSerial baud rate Serial.begin(9600); //The Serial port of Arduino baud rate. } void loop() { if (SoftSerial.available()) //If date is coming from software serial port // ==> Data is coming from SoftSerial shield { while(SoftSerial.available()) //Reading data into char array { buffer[count++]=SoftSerial.read(); //Writing data into array if(count == 64)break; } Serial.write(buffer,count); //If no data transmission ends, //Write buffer to hardware serial port clearBufferArray(); //Call clearBufferArray function to clear //The stored data from the array count = 0; //Set counter of while loop to zero } if (Serial.available()) //If data is available on hardware serial port // ==> Data is coming from PC or notebook SoftSerial.write(Serial.read()); //Write it to the SoftSerial shield } void clearBufferArray() //Function to clear buffer array { for (int i=0; i<count;i++) { buffer[i]=NULL; } //Clear all index of array with command NULL }