Datasheets, service manuals, circuits, electronics, components, CAD

https://www.radioradar.net/en/measurements_technics/sensors_make_sense_arduino.html

Sensors make Sense. For Arduino and more

Sensors are either analog or digital. Analog values are read in via an A-D input, whereas for digital signals a simple Port connection frequently adequate. In some cases, however, sensors have dual outputs, one analog and one digital.

A glance at the sensor combo kit (available from Elektor [1]) reveals seven superficially identical PCBs equipped with differing sensors. All of them have one analog output AO and one digital output DO. As you know, to create a digital signal from an analog one, we use a comparator. There is one of these included on each of these boards, or more precisely an LM393 dual differential comparator.

 

Sensors equipped with comparators

When we examine the circuit of the board in Figure 1 more closely, its function becomes clear. Once more we find the actual sensor in a voltage divider that this time is preset with a 25-turn precision trimmer pot. A second voltage divider made up from two 100 kΩ resistors provides a reference voltage of 2.5 V for the comparator. The temperature sensor (Digital Temp) can now be adjusted so that the sensor voltage at the desired temperature will likewise be exactly 2.5 V. A rising temperature at the NTC sensor makes the comparator switch on the digital output DO, whilst a falling temperature switches it off. The second comparator connected downstream operates only the status LED. Thanks to these LEDs we can test all seven sensors without any need for software.

Sensors with comparators

Figure 1. Sensors with comparators.

 

The circuit does not include a bypass capacitor (see inset), meaning that any variations or spikes on the supply voltage may affect the operation. The length of the wiring and other random factors can also have some influence. In actual fact with the temperature sensor and the heat rising, we find a narrow region in which the output oscillates, which is possibly caused by parasitic capacitance on the PCB. If we fit a small capacitor between the input and the second comparator output, we can see an oscillator in action. This is easy to recognize with the oscilloscope. The status LED on the sensor PCB shows it as well. When things warm up slowly, it lights up initially at half brightness (state of oscillation) and only after this does it reach full brilliance (stable condition). If the software behaves strangely, bear this point in mind.

The other sensors using this circuit behave in more or less the same way, even if the changes in the measured value are usually not so gradual. Most comparable with the NTC sensor is the phototransistor in the flame sensor. The dark housing allows the longer wavelengths to pass through preferentially, in order for flames to be detected. The Hall sensor differs in that it expects an operating voltage on its third pin. The fact that the reed switch is connected as an analog sensor may surprise you. But there are two out-of-phase outputs. When a magnet is brought closer, one output goes on and the other goes off. Sound and touch behave somewhat differently; normally they deliver a squarewave signal with rapid transitions. The two sound sensors employ one large and one small electret microphone. With the pot adjusted correctly, half waves of loud sound Figure 1. Sensors with comparators. signals appear at the output as square waves. This must be taken into account during your evaluation testing. In the same way the touch sensor generally provides a 50 Hz squarewave signal (60 Hz in North America) when activated.

The comparator circuit delivers a sharp switchover point, without any hysteresis. This means that with a slow change of temperature, a region can occur in which the output flutters a bit. In a program you can take account of this and poll the digital output only at longer intervals. Or you could use the analog output signal AO direct from the voltage divider and evaluate this, something that we'll describe in greater detail below. Unlike the analog NTC sensor already described, you will then have the advantage that a desired temperature can be set externally using the pot.

It's also interesting to note that the digital output of this board can control an actuator directly, without any assistance from a microcontroller. Output DO is connected to the input of the relay PCB. That's it - the temperature controller or thermostat is complete. Admittedly without hysteresis, which in some applications could be problematic. If you feel like connecting one of the LEDs directly to the comparator, you need to bear in mind that a comparator has an open collector output. Therefore it switches down actively, so that in the High state only the pull-up of 10 kΩ supplies current, meaning that the LED does not illuminate very brightly. Nevertheless, applications are conceivable in which three separate sensors directly drive the three colors of an RGB LED (Figure 2), not with great intensity but clearly visible nevertheless. The resulting color mixture of pink perhaps then stands for "hot and loud".

Direct connection to RGB LED

Figure 2. Direct connection to RGB LED.

 

If you wish to control laser lights directly, you'll need to hook these up between DO and +5 V (Figure 3). On/Off reverses the situation, but you can now switch larger currents up to about 20 mA. With this arrangement an interesting experiment can be carried out: opto-thermal feedback. The laser is pointed precisely towards the NTC sensor (see header photograph). The switching temperature is then set exactly at the changeover point using the potentiometer. Once the correct position is found, the laser starts to flash. Here's how: when switched on, it warms the sensor slightly. The digital output switches on, which turns off the laser because of the inverted connection. This gives the sensor the chance to cool down again until the comparator flips and the sequence begins once more.

The laser on the comparator output

Figure 3. The laser on the comparator output.

 

Bypass capacitorsBypass capacitors

In many circuits we find capacitors wired between the supply voltage (VCC) and ground (GND). They improve the stability of the circuitry and help prevent radio interference. Whenever electronic circuitry uses a lengthy cable to the power supply it's not just the resistance of the wires in the cable that comes into play but also the inductivity. A piece of twin-conductor cable 1 m long can have an inductance of around 0.5 μH, according to the gauge (thickness) of the wires and the distance between them. From this arises an inductive resistance of 3 Ω at 1 MHz or 30 Ω at 10 MHz. If your circuit has a varying current load, effectively you have an alternating current in the supply lead and with this some voltage drop. Typical problems with voltage drop of this kind are susceptibility to radio interference and vulnerability to failures in the passive elements of the circuit. The long (from a radio perspective) cable can also act as an antenna. Then you have radio-frequency (RF) signals radiating that potentially may exceed the permitted limits. Conversely pulses of interference may induce brief fluctuations in the supply voltage that might interfere with the correct functioning of a circuit.

DC motors will produce a varying load on the current source and can lead to radio interference. This is why capacitors are connected direct to the supply terminals and are generally called anti-interference or suppressor capacitors. The DC motor in an RC model cannot function without these, as otherwise it would interfere with its own receiver onboard. Microcontrollers like the Arduino also require a capacitor

between GND and VCC, as otherwise they would not pass their test for electromagnetic compatibility. In this case they are usually called decoupling capacitors, because any radiofrequency currents can be diverted or decoupled by taking a shortcut through this capacitor mostly commonly of 100 nF. The older expression 'blocking capacitor' used for these components has fallen out of fashion.

Our sensors are all definitely not particularly susceptible to interference problems of this kind. If you do wish to employ a cable longer than 12 inches (30 cms), you should connect a bypass capacitor of 100 nF direct to the sensor between the supply terminals (see image).

 

Software-based Schmitt trigger

When you have a transition region a comparator can generate highly volatile output states. A Schmitt trigger helps mitigate this by displacing the transition points that set the switch-on and switch-off points. An example is switching on at 25 degrees Celsius and off at 20 C, as discussed regarding the NTC sensor (Analog Temp) in first part of this series.

All the sensors on the comparator board also have an analog output, as you know. There is nothing to stop you making a comparison in the software, and in so doing, building in some appropriate hysteresis. Because all the sensors are adjusted using the trimpot to a switching point of 2.5 V, the same software can be used for the differing sensors.

In the software the two outputs B.2 (LED 2 on the Elektor Extension Shield, see Part 1 [2]) and B.5 (LED on the Arduino board) are used as outputs. There's a specific reason for switching them in antiphase. You might connect the dual-color LED to both outputs. Or you might hook up actuators of this kind between both outputs, which in reality still require a series (dropper) resistor but in this situation would at least see two internal resistances in series. This class of actuators also includes the SMD RGB LED and the infrared LED. The color-changing LED discussed later on belongs in this category too, but it includes a reverse-voltage protection diode, which will not tolerate the inverted voltage level cheerfully. In this case you are better off using a genuine 'real' dropper resistor.

The sample Bascom code in Listing 1 evaluates the raw data from the A-D converter (as always, all of the code samples can be downloaded from the Elektor Magazine website [3]). The center of the measurement range represents a value of 512. The switching threshold points in this example lie at 509 and 515. With around 5 mV per A-D step we then have a hysteresis of 30 mV. The program also controls LED2 on the Extension Shield. This means you can compare the switchover with that on the sensor board yourself. The software offers two slightly displaced switchover points as opposed to the sharply defined switching point of the sensor-comparator. The complete program additionally displays the analog sensor voltage, both on the LCD of the Shield and on the terminal screen. This helps you find the correct trimmer setting.

Listing 1. A comparator with hysteresis (Comparator.bas).

Do

   D = Getadc(2)

   If D > 514 Then  Portb.2 = 0

   If D > 514 Then  Portb.5 = 1

   If D < 510 Then  Portb.2 = 1

   If D < 510 Then  Portb.5 = 0

. . .

  Waitms 500

Loop

The Arduino version of the program (Listing 2) differs little from the BASIC example. The analog signals can be displayed without additional overheads using a serial plotter. Figure 4 shows signals from the microphone sensor. This program can be used again for all seven sensors on the red comparator PCB.

Listing 2. The Arduino comparator.

//Comparator AD1

. . .

void loop() {

   value = analogRead(sensorPin);

   if (value > 514) {

        digitalWrite (output1, 1);

        digitalWrite (output2, 0);

   }

   if (value < 510) {

        digitalWrite (output1, 0);

        digitalWrite (output2, 1);

   }

   Serial.println(value);

   lcd.setCursor(0, 0);

   lcd.print(value);

   lcd.print (” ”);

  delay(50);

}

 

 

Microphone signals

Figure 4. Microphone signals.

 

OscillatorsOscillators

One of Murphy's Laws states that when you construct an oscillator it never oscillates, whereas when you make an amplifier it oscillates all the time.

There's something in this observation, which is why it's always worth looking closely when your circuit turns into an oscillator and 'starts to hoot' as people say. An oscillator consists fundamentally of an amplifier and some matching feedback from the output to the input.

The signal fed back must moreover have the correct phase relationship. If the voltage at the input rises directly, the same should happen at the output, only correspondingly amplified. Then it's sufficient to feed back a part of the output signal to the input using a capacitor - and now you have an oscillator.

An amplifier of this kind can be constructed with two transistors, in which both of them rotate the phase by 180 degrees. Or you can use an op-amp or an integrated loudspeaker amplifier.

A single amplifier stage with one transistor in grounded emitter mode turns the phase through 180 degrees. Rising
input voltage will make the output voltage drop. All the same, you can build an oscillator with only one transistor. All you need do is ensure that the phase is reversed accordingly. You can do this, for instance, using several capacitors and resistors (phase-shift oscillator). Or use a transformer for the feedback (Meissner oscillator). If the oscillator still observes Murphy's Law and doesn't oscillate, all you normally need to do is reverse one of the two windings to get the phase right. So it's likely that the small buzzer is constructed in this way ( image ). The 'loudspeaker' has two windings, which at the same time make a transformer.

If you construct an amplifier with multiple stages and higher overall gain, it may actually be not that easy to prevent selfoscillation. Signals from the output can sneak back to the input via the supply voltage, which you may be able to avoid using a fairly large bypass capacitor. Or some small capacity may exist between the output and input wiring. In extreme cases the only remedy that can still solve this problem is a physical screening (shielding) plate.

 

Polling contact sensors

The touch sensor does not produce a slowly varying signal, but rather a (normally) squarewave signal of 50 or 60 Hz. Were you to use this for controlling a relay, the result would be wavering, noisy and inelegant. However, the signal can be improved in software (Listing 3 and Listing 4). The digital output in this case is connected to AD1. Yes, this is an analog input but you can also use it as a digital input Port. The result of polling it will be 1 or 0 and can be copied direct to an output Port. Here we chose B2 (Arduino pin 10), because it can also control the LED2 on the Shield. Additionally B5 is also controlled, as that's where the Arduino-internal LED is located. Externally you can also hook up another LED or the laser light.

Listing 3. Input and output Port in Bascom.

Dim D As Boolean

Config Portb = Output

Do

    Portb.2 = Pinc.1

    D = Pinc.1 Xor 1

    Portb.5 = D

    Waitms 21

Loop

 

Listing 4. Input and output Port using Arduino-C.

//Touch1 A2 > 10, 13

#include <LiquidCrystal.h>

int input = A2;

int output1 = 10;

int output2 = 13;

 

void setup() {

    pinMode(output1, OUTPUT);

    pinMode(output2, OUTPUT);

}

void loop() {

    digitalWrite (output1, digitalRead(input));

    digitalWrite (output2, 1-digitalRead(input));

    delay(21);

}

The program consists of a simple loop that has a waiting time of 21 ms built in. If you now tap the touch sensor, the output flashes. What actually happens is that touching it applies a 50 Hz interference signal to the base of the Darlington transistor. Therefore we get a 50 Hz squarewave signal on the digital output, i.e. a cycle duration of 20 ms. If we now sample this signal using a slightly different frequency, you obtain a significantly smaller frequency. The cycle duration 21 ms indicates a sampling frequency of around 48 Hz. The difference 50 Hz - 48 Hz = 2 Hz appears in antiphase at outputs B2 and B5.

It may not be self-evident that we can control a transistor in this manner. Usually we specify a base current and determine the bias point in this way. With small signals, things would not work without base current. The person touching the sensor is seen as one plate of a capacitor, with the second plate formed by all the wires and cables located in the environment. A base current would charge this capacitor so far negative that the transistor would block completely. It works only because every bipolar transistor contains a zener diode in the range 7 V to 10 V between base and emitter (see Figure 5). The idle state mains hum voltage of a person is generally significantly higher than 10 Vpp. Therefore an alternating current flows, with its positive half-wave driving the transistor.

Contact sensor with Darlington transistor

Figure 5. Contact sensor with Darlington transistor.

 

You might expect that on the collector of the Darlington transistor we would also find an approximately equal squarewave signal. So let's also try coupling the analog output AO to the digital input A1. That's right; now the output flashes when the base is touched. However, the difference is that this time the output in idle mode is 'on', because the comparator on the sensor board inverts the signal.

It even works without the sensor board. At input A1 we have just a piece of insulated wire connected (Figure 6). If you then touch the outside of this insulation, it still flashes! This happens because the input of the controller has extremely high impedance. The wire, insulation and finger form a small coupling capacitor of a few picofarads in value. If an AC voltage is applied to the input, it is limited to the input voltage range by the internal protection diodes. The open input does admittedly have a disadvantage compared to the correct touch sensor. The idle state is not unambiguous, you see, which makes evaluation tricky.

Input Port used as contact sensor

Figure 6. Input Port used as contact sensor.

 

Processing switching signals

Up to now all we have done with our touch sensors is achieve flashing on the output. In reality we'd expect a contact switch to do rather more, namely switching something on. This is entirely feasible if we write our program somewhat differently. To manage this, all we need do is make sure that the switching-on process takes precedence and switching-off takes place after a short delay. Our Touch programs (Listing 5 and Listing 6) additionally employ a delay period of 10 μs and consequently interrogate the Port very frequently. Once a High state is detected, the program sets counter T to a value of 50000 and switches on the output. The counter decrements slowly and only after about 500 ms without any further pulse does the output switch off. Any further impulse that occurs will reset the counter High again and the timeout period is extended accordingly. Now everything functions as desired. The output goes on immediately if someone touches the sensor and goes off again, not when the contact ceases but after some delay. The function corresponds to a retriggerable monostable multivibrator. Now our touch sensor, with its Darlington transistor, is working the way we want it to. The squarewave signal on the digital output has been transformed into an unambiguous switching signal that will work even in environments without mains hum. Short pulses caused by static charge are sufficient to trigger the output.

Listing 5. Contact sensor and touch switch (Touch2.bas).

Dim T As Word

 

Config Portb = Output

 

Do

    If Pinc.1 = 1  Then T = 50000

    'If Pinc.1 = 0 Then T = 50000

    If T > 0 Then T = T - 1

    If T > 0 Then Portb.2 = 1 Else Portb.2 = 0

    If T > 0 Then Portb.5 = 0 Else Portb.5 = 1

    Waitus 10

Loop

 

Listing 6. Touch switch in Arduino-C.

void loop() {

    if (digitalRead(input) = = 1) timeout = 50000;

    //if (digitalRead(input) == 0) timeout = 50000;

    if (timeout > 0) timeout = timeout -1;

    if (timeout > 0) {

       digitalWrite (output1 , 1);

       digitalWrite (output2 , 0);

    }

    else {

       digitalWrite (output1 , 0);

       digitalWrite (output2 , 1);

   }

       delayMicroseconds(10);

}

There's a special reason why we chose the loop delay of 10 μs to be much smaller than necessary for a 50 Hz signal. The format of the program makes it equally suitable for use with the two sound sensors in the Sensor Kit, with which, according to the sound frequency being sampled, up to 10 kHz or more can appear on the output. Correct adjustment of the trimpot will give you a very usable speech switch that will also react to loud whistling, hooting or other noises. Even gentle tapping your finger on the microphone will set off the switch. The sensitivity depends very much on the precise setting of the pot. You need to keep in mind that this type of microphone normally delivers less than 1 mV. This means you must maintain the sensor voltage to the switching point within a few millivolts of accuracy in order for sound signals to make the comparator change level correctly.

 

Shock sensor

Certain other digital sensors, such as the Tap Module, are appropriate for this kind of sampling. This contains a spring that can close a contact when disturbed. Two very brief pulses are produced in this process. You need to be aware that the module has a pull-up resistor, meaning that the output voltage is +5 V when not operated and the pulses are 0 V. In this situation the sampling process needs to invert the input signal, which is marked in the software with a commented line. Alternatively in this case you might also connect +5 V and GND transposed and leave the software unaltered, as the polarity is of no interest to the switch and resistor.

The Shock Sensor was tested in the same way, in which an internal contact is closed for a short duration each time it is disturbed. The sensitivity of the Shock Sensor is greater than that of the Tap Module. The Tilt Switch (ball switch) can also be sampled in this manner. At the right degree of inclination a small ball rolls downwards and closes two contacts. If you shake the sensor rapidly to and fro, you can hear the ball rattling and watch the program triggering the output.

In point of fact all switching sensors can be polled or sampled meaningfully using this method, as well as press buttons (Button), reed switches (Mini Switch) and the reed switch on the comparator board. Using this type of time delay we can achieve effective debouncing of the switches. Just about every mechanical switch (apart from mercury switches, which are now banned in many territories, however, on account of the poisonous mercury in them) bounces momentarily one or more times when operated, generating several impulses to begin with. The software turns this into a single, elongated pulse. If you alter the period somewhat you can make a time switch, for instance to illuminate a staircase at night. The light can then be activated, according to the type of sensor, by loud speech, touch, tapping or advancing a magnet. Even the digital output of the temperature sensor could be polled in this way. This would simultaneously eliminate the problem of fluttering transitional states between Low and High.

With a minor alteration (Listing 7) the function of a comparator sensor could also be made clearer using the serial monitor. For this we additionally make use of the analog signal at AD2, while the digital output signal of the comparator carries on with the task of triggering the actual switching process. To display the output signal with only one channel, we raise the output in a High state by 100. You can then observe the original analog signal as if raised on a pedestal. Figure 7 shows the result for the sound sensor. You can see clearly that a sound signal must first exceed a certain level to switch the output state. At the end of all of the signals the software enables the laid down delay period, after which the output drops back down. Figure 8 portrays the work of the temperature sensor. For this the program is slowed down to an extent by a delay of 100 ms. During the measurement time-window the sensor was twice warmed by touching with a finger. You can spot clearly the inversion performed by the comparator: a falling voltage on the actual sensor switches on the comparator's output. Equally easy to recognize is a brief phase of oscillation in the region around the switchover point. The software suppresses these oscillations effectively.

Listing 7. Additional serial output.

void loop() {

    if (digitalRead(input) = = 1) timeout = 50;

    if (timeout > 0) timeout = timeout -1;

    if (timeout > 0) {

       digitalWrite (output1 , 1);

       digitalWrite (output2 , 0);

    }

    else {

      digitalWrite (output1 , 0);

      digitalWrite (output2 , 1);

    }

    Serial.

       println(analogRead(sensorPin)+100*digitalRead(output1));

      delay (20);

}

 

 

Switching using the sound sensor

Figure 7. Switching using the sound sensor.

 

Temperature sensor in action

Figure 8. Temperature sensor in action.

 

Buzzers and other actuators

At output B2 we can again attach the relay board. But there are yet more actuators that we can also put to use. Among these belongs the buzzer, a small active device that is provided initially with some protective foil. At 5 V the current consumption amounts to 25 mA. The buzzer can therefore be attached direct to a Port. The polarity is admittedly not completely unambiguous and depends on how the buzzer is soldered onto the board. On the sample device the signal and minus connections were transposed in fact and the S-pin need to be connected to GND. A test using the lab power supply also indicated that the buzzer begins to work already at 0.7 V and at a different frequency if the sound opening is blocked. Without even opening the housing, our experts were able to figure what lay inside: a free-running oscillator with a bipolar silicon transistor with the normal threshold voltage of 0.5 V to 0.7 V (naturally it insists on having the correct polarity of supply voltage). At the same time take care that you do not confuse the active buzzer with the passive one, which is more comparable to a small 16-Ω loudspeaker.

Another interesting actuator is the color-changing LED (Color Flash), in actual fact a three-color LED package with a built-in controller. This automatic LED produces a color transition between red, green and blue. This is another case requiring a dropper resistor, since color-change LEDs of this kind are in fact designed for 3 V. Incidentally, although there is indeed a resistor of 10 kΩ on the board, it is connected in parallel (Figure 9). For 5 V a dropper resistor of 100 Ω would work best. Here again, however, the compromise presented in the previous article works again: you can connect the LED between two Port pins, in order to achieve a degree of current limitation using the internal resistance of the Ports. Pin 12 (B4) is recommended for the opposite pole.

Color-changing LED

Figure 9. Color-changing LED.

 

Incidentally, the internal controller of the color-change LED, like most ICs, includes an inverse polarity-protection diode on its supply voltage connections and therefore reacts sulkily if you reverse the supply connections. Without the dropper resistor a reversed power connection could lead to destruction. This is vitally important: GND lies in the middle of the three connections. By the way, just for fun, you can also connect the passive mini-speaker in series. Then you can not only see the switching process but also hear it.

Web Links

[1] www.elektor.com/arduino-sensor-kit

[2] www.elektormagazine.com/160152

[3] www.elektormagazine.com/160173

Author: Burkhard Kainka (Germany)