CHAPTER 11 Sensors
In this chapter we will do:
• Sensor Types:
Tactile sensors / switches, Shaft encoders
• General data input
Polling vs Interrupts
• A/D converters
• Infrared position sensitive devices (PSD)
Bräunl 2024 1
Sensors
General Remarks
• There are millions of different sensor types
• You have to select the right one for your
application and budget and read the specs
• Some sensors require also input from CPU
E.g. activation/deactiv., triggering data transfer, …
• Our scope here is more on interfacing sensors
than on understanding the sensors themselves
Bräunl 2024 2
Sensors
Typical Sensor Outputs Examples
• Binary signal (0 or 1) Ø Tactile sensor
• Analog signal (e.g. 0..5V) Ø Inclinometer
• Timing signal (e.g. PWM) Ø Gyroscope
• Serial link (RS232 or USB) Ø GPS Module
• Parallel link Ø Digital Camera
Bräunl 2024 3
1. Binary Sensors
Tactile sensor / switch VCC
• Easy to be interfaced R (e.g. 5kW)
input signal
• Use a resistor and link
Micro
to digital input of CPU
or latch
GND
“active low”
Bräunl 2024 4
1. Binary Sensors
Tactile sensor / switch with internal resistor
• Easy to be interfaced VCC
input signal
• Use a resistor and link
Micro
to digital input of CPU
or latch
GND
“active low”
Bräunl 2024 5
VCC
input signal R (e.g. 5kW)
Contact Bounce Effect
GND
Problem:
• When activating switch, contact moves up and down
several times (“contact bounce” or “switch bounce”)
• Bad when counting pulses or in user menus
à incorrect results !
Metal tongue bounces
up and down
Bräunl 2024 6
VCC
input signal R (e.g. 5kW)
Contact Bounce Effect
GND
input
“open” “closed”
t
switch bounce effect, typically within 10ms
time of actual pressing down
Bräunl 2024 Measurement: Jack Ganssle, Baltimore MD 7
VCC
input signal R (e.g. 5kW)
Debouncing
GND
Solutions:
• Hardware:
Analog: resistor-capacitor circuit
Digital: flip-flop with single-pole/double-throw switch
• Software:
Wait certain delay time before allowing next change
Bräunl 2024 8
VCC
input signal R (e.g. 5kW)
Debouncing
GND
Solutions:
• Hardware:
Analog: resistor-capacitor circuit
Digital: flip-flop with single-pole/double-throw switch
RS-Latch
single-pole/
double-throw
Bräunl 2024 Circuits: Jack Ganssle, Baltimore MD 9
VCC
input signal R (e.g. 5kW)
Debouncing
GND
Solutions:
• Software V1:
Always wait certain delay time, e.g. 50ms
int read(); /* assume reading from port B */
{ usleep(50000); /* sleep 50,000 micro-sec */
return PINB;
}
Bräunl 2024 10
VCC
input signal R (e.g. 5kW)
Debouncing
GND
Solutions:
• Software:
Wait certain delay time only when required (when change)
int read(); /* assume reading from port B */
{ int val;
static int old_val, last_time; /* in ms */
val = PINB;
if (val == old_val) return val;
else { /* values differ */
while (time_now()<last_time+50) /*wait*/;
old_val=val; last_time=time_now();
return val;
}
}
Bräunl 2024 11
2. Encoder
Shaft encoder
• incremental or absolute position
Siemens star
incremental encoder (optical) Absolute encoder (optical, Gray encoding)
Note: cheaper and more accurate Note: Only single bit changes at any time!
If 2 more more change, which one first?
Bräunl 2024 12
Encoder
Bräunl 2024 Images: FrontrangeRobotics, DirectIndustry, Wikipedia, MathWorks 13
Encoder
Incremental encoder
• Usually requires 2 sensors to determine
speed and direction
• See motor control
Technology
• Magnet + hall sensors (incremental)
• Optical sensors with black/white segments
(incremental)
Bräunl 2024 14
Encoder
2 sensors
Magnet + Hall sensor Optical: black/white segments
Bräunl 2024 Photo: Faulhaber 15
Encoder
• Encoder signal (2 lines) are connected to
microcontroller like 2 binary sensors
(2 digital input lines)
• Microcontrollers usually have special internal
registers for pulse counting
Þ This is done in parallel to normal calculations
Þ Does not slow down the CPU
Bräunl 2024 16
3. General Data Input
A data transfer can be
1. CPU-initiated (“polling”)
2. Device-initiated (“interrupt”)
CPU device
Bräunl 2024 17
Polling
Read device input without interrupt
digital input line
device
CPU
Task: Count pulses,
e.g. from encoder
“You need to be quick …”
Bräunl 2024 18
Polling
Example Program: Count pulses (active low)
void loop()
{ static int counter = 0;
if (!(digitalRead(ENC))
counter++;
} Read enc. input
Check for value 0
Is this correct?
Bräunl 2024 19
Polling
Program is not correct!
because it may count single pulse twice or more!
• Depending on controller speed
• Controller may also miss a short pulse if too slow,
but we assume for now this is not the case
We want to count the falling edges 1à0
Bräunl 2024 20
Polling
Second Try: Count pulses (active low, use dig. input)
void loop()
{ static int counter = 0, previous = 0, now = 1;
now = digitalRead(ENC); // read input line 1
if (!now && previous) counter++;
previous = now;
} if ( now==0 &&
previous==1 )
Is this correct?
Bräunl 2024 21
Polling
Program should work now!
if ( now ==0 &&
previous ==1 )
We want to count the falling edges 1à 0
n=1 n=0 n=1 n=1 n=0 n=0 n=1 n=0 n=1 n=0 n=1
p=1 p=1 p=0 p=1 p=1 p=0 p=0 p=1 p=0 p=1 p=0
Bräunl 2024 22
Encoder on ESP32
void setup()
{ pinMode(ENC, INPUT_PULLUP);
}
void loop()
{ static int count=0, E, E_old=0;
E = digitalRead(ENC); // read encoder
if (!E && E_old) count++;
E_old=E;
}
Bräunl 2024 23
Encoder Counts up or down
How to extend program for up/down counting?
Bräunl 2024 24
Quadrature Encoder
A quadrature encoder is like a car’s
odometer, but can run forwards or
backwards
Example Readings (hex): Calculated Speed (new – old)
• Start: 0000 ––
• 1. read: 0005 5–0 = +5
• 2. read: 0003 3–5 = -2
• 3. read: FFFE -2–3 = -5 (rollover)
• 4. read: 0002 2–(-2) = +4 (rollover)
Bräunl 2024 Graphics: Videohive.net 25
Encoder Counting Methods
All works well, or?
• Counting in the "foreground" program wastes compute
time that may be required for other tasks
• Counting in "foreground" may take too long, so it misses
counts for faster signals (e.g. wheel spinning faster).
à Solution: Interrupts
(See are specialised libraries: ESP32Encoder.h)
Bräunl 2024 26
4. Interrupts
Bräunl 2024 27
Device Input Summary
• CPU-initiation à Polling
– CPU initiates read/write with IN/OUT instruction
– Timing relies only on CPU
– May have to do this in loop in case device is not ready
à “busy-wait loop” à loss of CPU time à inefficient
• Device-initiated à Interrupts
– Device signals CPU that it is ready via special interrupt line
– CPU interrupts whatever it was doing and calls special “interrupt
service routine” (ISR)
– CPU returns to previous task after finishing ISR (like subroutine)
Bräunl 2024 28
Interrupts
Read device data with interrupt
CPU
interrupt line
IRQ1’ device
• Controller has several interrupt lines with different priorities
• Interrupts can come from internal sources (e.g. timer interrupt)
or external sources (e.g. sensor via interrupt request line)
Bräunl 2024 29
Interrupts
• Execution of one program (user) is temporarily
suspended for another program with higher priority
(somewhat like a unscheduled subroutine call)
• Sometimes also called exception
• Interrupts can be raised either by software (special
CPU command) or by hardware (external signals
linked to CPU interrupt lines)
• Many embedded systems have interrupts that occur
at regular time intervals (e.g. every 0.01s)
Þ timer interrupts
Bräunl 2024 30
Interrupts
Example Program: Count pulses (use interrupt)
Step 1: Write routine that is called when an interrupt arrives
Step 2: Associate interrupt with this routine (initialization)
Unfortunately, this is where standard C/C++ stops –
Requires special library functions.
Bräunl 2024 31
TTGO/ESP32 Interrupt Example
Bräunl 2024 32
5. Digital Sensors
Digital sensors are
• usually more complex than analog sensors
• often more accurate than analog sensors
• sometimes analog sensors with built-in A/D
converters
Bräunl 2024 33
Digital Sensors
Example: Sharp GP2D02
• Available as digital or analog
version (GP2D05)
• Versatile optical distance
measurement sensor
(requires reflective surfaces)
• Uses infrared LED and light
detector
• Often called PSD (position
sensitive device)
• Measurement range 6cm - 80cm
• Accuracy: about 1cm
Bräunl 2024 Photo: Sharp 34
Digital Sensors
Physical dimensions
Block diagram
Bräunl 2024 Source: Sharp 35
Sensors
Signal vs. true distance
Can you see a problem?
Bräunl 2024 Source: Sharp 36
PSD Sensor: Sensor value over real distance
Sensor
readout
Not unique!
Must adhere to specified
operating range!
Actual distance
Bräunl 2024 37
Digital Sensors
Bräunl 2024 Source: Sharp 38
Digital Sensors
How to interface this sensor to a controller?
• Hardware
• Software
Bräunl 2024 39
PSD Sensor Interface
1. Hardware
+5V
PSD
out1 Vin Measurement
CPU in1
Output
Gnd
Bräunl 2024 Diagram: Sharp 40
SET
PSD Sensor Interface
2. Software PSD
int psd()
{ int val=0;
digitalWrite(SET, LOW);
usleep(70000);
...
return val;
} TTGO Code
Bräunl 2024 41
Diagram: Sharp
SET
PSD Sensor Interface
2. Software PSD
int psd()
{ int result = 0;
digitalWrite(SET, LOW); // then wait …
while (!(digitalRead(PSD)) usleep(100); // wait ready sig.
for (int i=0, i<8; i++)
{ digitalWrite(SET, HIGH); // set rising edge
usleep(200); // up-time
digitalWrite(SET, LOW); // set falling edge
result = (result<<1) | digitalRead(PSD);
usleep(200); // down-time
}
return result;
} TTGO Code
Bräunl 2024 42
Diagram: Sharp
PORTD(0)
PSD Sensor Interface
2. Software PINB(0)
int psd()
{ int result = 0;
PORTD=0; // then wait …
while (!(PINB&0x01) usleep(100); // wait for ready signal
for (int i=0, i<8; i++)
{ PORTD=1; // rising edge
usleep(200); // up-time
PORTD=0; // falling edge
result = (result<<1) | (PINB & 0x01); // read bit 0
usleep(200); // down-time
}
return result;
} Nano Code
Bräunl 2024 43
Diagram: Sharp
PSD Sensor Interface
Task: Compose data coming in sequentially
E.g. value 7 (0b0111) is sent serially as: 0, 1, 1, 1
Calculation:
Start: result = 0
1. Loop read 0: result = 2*0 + 0 = 0
2. Loop read 1: result = 2*0 + 1 = 1
3. Loop read 1: result = 2*1 + 1 = 3
4. Loop read 1: result = 2*3 + 1 = 7 finished
Bräunl 2024 44
6. Analog Sensors and A/D Converter
A number of sensors have analog output signal
rather than digital signals
Þ A/D converter is required to connect to CPU
Examples:
• Microphone
• Analog infrared distance sensor
• Analog compass
• Barometer sensor
Bräunl 2024 45
Analog Sensors
Bräunl 2024 Images: MediaCollege.com, MIT 46
A/D Converter
5, 10, 124, 17, 53, 229, 68, …
• Transform analog signal into a sequence of numbers
• Sampling rate and conversion number range will determine
digitizing quality (how accurately the signal will be digitized)
• There will be some information loss
• Signal has to be provided at correct level,
e.g. between 0 .. 5V
Bräunl 2024 47
A/D Converter
Version 1: Parallel
(e.g. 8 bit, direct connection to data bus)
data bus
microphone
CPU A/D
CS / enable
GND
Bräunl 2024 48
A/D Converter
Version 2: Serially digital
Provide clock signal to converter to read bit by bit
data bus
microphone
1bit data to dig. input
CPU serial clock A/D
GND
Bräunl 2024 49
A/D Converter
Version 3: Serially digital with multiple inputs
Requires an analog multiplexer
data bus
1bit data in + 1 bit data out several input lines
CPU serial clock A/D microphone
CS / enable compass
GND
Bräunl 2024 50
A/D Converter
Bräunl 2024 51
Source: Maxim
A/D Converter
Bräunl 2024 Source: Maxim 52
A/D Converter
Bräunl 2024 Source: Maxim 53
A/D Converter
Power consumption Power-up delay
Bräunl 2024 Source: Maxim 54
A/D Converter
Signal
conversion
Bräunl 2024 Source: Maxim 55
A/D Converter
Serial clock and serial data stream
Bräunl 2024 Source: Maxim 56
A/D Converter - Interface
1. Hardware A/D
out1 CS’ channel 1..8
out2 ser-clock
out3 data-in
CPU
in1 strobe
+5V
in2 data-out
Ref. voltage
4.7µF
Gnd
Bräunl 2024 57
A/D Converter - Interface
2. Software
int convert(int port) // range [0..7]
{ digitalWrite(out1, LOW);
// set 3 port bits on out3 while generating a clock on out2
for (int i=0; i<3; i++)
{ ...
Bräunl 2024 58
7. PWM Sensors
We have already seen PWM for:
• Velocity control for DC motors
• Position specification for servos
Now we see PWM for:
• Sensor data
• Examples:
– Accelerometer
– Gyroscope
– Inclinometer
Bräunl 2024 59
PWM Sensors
Gyroscope Inclinometer
(relative) (absolute)
V
neg. accelerat. –30 degrees
t
V no acceleration 0 degrees
t
V pos. accelerat. +30 degrees
Bräunl 2024 t 60
PWM Sensors
start timer stop timer
on rising edge on falling edge
Elapsed time (e.g. in µs) will then be the digital sensor value
Bräunl 2024 61
8. Sensor Calibration
Sensor output may be linear or non-
linear to measured dimension:
• Before a (digitized) sensor value can be used
in an embedded system, its data has to be
calibrated
• Linear relationship: a few initial measurements
are sufficient
• Non-linear measurements: complete
measurement table is required
• During runtime us:
formula for simple relationships
lookup table for arbitrary relationships
use interpolation for values between entries
(simple and efficient)
Bräunl 2024 Diagram: Sharp 62