Optical sensors. Photoresistors in MK circuits. How to use photoresistors, photodiodes and phototransistors Street lighting photoresistor on Arduino

  1. Phototoresist: http://ali.ski/5GDvP7
  2. Diodes and resistors: http://fas.st/KK7DwjyF
  3. Development board: http://ali.ski/rq8wz8
  4. Arduino uno: http://ali.ski/gC_mOa

In this tutorial we will connect a photoresistor to Arduino. which will control the built-in LED.

Photoresistor: The resistance of photoresistors decreases when exposed to light and increases in darkness. Photoresistors are easy to use, but react rather slowly to changes in light levels and have a very low efficiency. accuracy. Typically, the resistance of photoresistors can vary from 50 ohms in daylight to more than 10 megohms in the dark.

We will connect the photoresistor itself to ground through a 10 kOhm resistor and we will connect the same leg to the Arduino analog pin A0, the second leg of the photoresistor will be connected to the 5 volt Arduino. All this is clearly shown in the diagram at the beginning of the article.

After correctly connecting the photoresistor to the Arduino, you need to copy the code below, paste it into the Arduino ide program and load all this program code into the Arduino.

Int PhotosensorPin = A0; //Indicate the pin to which the Photoresistor is connected unsigned int sensorValue = 0; //Declare a variable to store values. void setup() ( pinMode(13, OUTPUT); Serial.begin(9600); ) void loop() ( sensorValue = analogRead(PhotosensorPin); // Read values ​​from the photoresistor if(sensorValue<700) digitalWrite(13, HIGH); //Включаем else digitalWrite(13, LOW); // Выключаем Serial.print(sensorValue, DEC); //Вывод данных с фоторезистора (0-1024) Serial.println(""); delay(500); }

After loading the program code into the Arduino, you need to open the port monitor.

Now, if light falls on the photoresistor and the built-in LED is turned off, cover the photoresistor with your hand and you will see that at some point the LED will turn on! You can also see changes in the value from the photoresistor in the port monitor.

A demonstration of how the photoresistor works can be seen in the video below.

Video:

A light sensor is a device that allows our device to evaluate the level of light. Why is such a sensor needed? For example, for a street lighting system to turn on the lamps only when night falls on the city. Another application of light sensors is to detect obstacles for a robot traveling through a maze. Or line detection by a robotic tracker (LineFollower). But in these two cases, a special light source is used in conjunction with a light sensor. We will start with a simple example, and connect one of the most common sensors - a photoresistor - to the Arduino Uno microcontroller. As the name suggests, a photoresistor is a resistor that changes its resistance depending on the light falling on it. This radio element looks like this: Photoresistors differ in resistance range. For example:

  • VT83N1 - 12-100 kOhm;
  • VT93N2 - 48-500 kOhm.
This means that in the dark the resistance of the photoresistor is 12 kOhm, and under a certain test illumination it is 100 kOhm. Specifically in the case of these LEDs, the test illumination had the following parameters: illumination -10 Lux, and color warmth - 2856K. In addition to the photoresistor, light sensors often use a photodiode and a phototransistor. Both look like typical LEDs:

1. Connection

In order to connect our photoresistor to Arduino Uno, you will need to remember. After all, at the output of the photoresistor circuit we will receive a certain voltage, in the range from 0 to 5 Volts, which we will need to turn into a very specific number with which the microcontroller program will already work. Keeping in mind that the Arduino Uno has 6 analog inputs on legs A0-A5, we connect the photoresistor according to the following diagram:

Layout appearance


Look what happened. We simply built a regular voltage divider, the upper arm of which will change depending on the level of light incident on the photoresistor. We apply the voltage taken from the lower side to the analog input, which converts it into a number from 0 to 1024.

2. Program

Having connected the photoresistor according to a simple circuit, we begin to write a program. The first thing we will do is output the raw signal from the analog input to the serial port, in order to simply understand how the value at the A0 input changes. The corresponding program looks like: const int pinPhoto = A0; int raw = 0; void setup() ( Serial.begin(9600); pinMode(pinPhoto, INPUT); ) void loop() ( raw = analogRead(pinPhoto); Serial.println(raw); delay(200); ) Running this program with us in hackspace, we received the following values ​​from the sensor:
Now let’s cover the sensor with our hand:
It can be seen that the value changes greatly. From 830 in case of direct light, up to 500 in case of shading (the appearance of an obstacle in the path of light). Knowing this behavior, we can numerically determine the triggering threshold. Let it be equal to, say, 600. Not exactly 500, because we want to protect ourselves from accidental activation. Suddenly a fly flies over the sensor - it will be slightly shaded and show 530. Finally, we will add to the program some action that will be performed if the light level falls below a given threshold. The simplest thing we can do is to light the standard LED #13 on the Arduino. The result is a program like this: const int pinPhoto = A0; const int led = 13; int raw = 0; void setup() ( pinMode(pinPhoto, INPUT); pinMode(led, OUTPUT); ) void loop() ( raw = analogRead(pinPhoto); if(raw< 600) digitalWrite(led, HIGH); else digitalWrite(led, LOW); delay(200); } Накрываем датчик рукой (или выключаем свет в комнате) — светодиод зажигается. Убираем руку — гаснет. Работает, однако. А теперь представьте, что вы зажигаете не светодиод, а подаете сигнал на реле, которое включает лампу в подъезде вашего дома. Получаеся готовый прибор для экономии электроэнергии. Или ставите такой датчик на робота, и он при наступлении ночи ложится спать вместе с вами 🙂 В общем, как говорил профессор Фарнсворт, у датчика света тысяча и одно применение!

Automation of lighting supply in an apartment, house or street is achieved through the use of photo relays. If configured correctly, it will turn on the light when it gets dark and turn off during daylight hours. Modern devices contain a setting that allows you to set the trigger depending on the light level. They are an integral part of the “smart home” system, taking on a significant part of the responsibilities of the owners. The photo relay circuit first of all contains a resistor that changes the resistance under the influence of light. It is easy to assemble and configure with your own hands.

Operating principle

The connection diagram for a photo relay includes a sensor, an amplifier and a photoconductor PR1 changes resistance under the influence of light. At the same time, the magnitude of the electric current passing through it changes. The signal is amplified by a composite transistor VT1, VT2 (Darlington circuit), and from it goes to the actuator, which is K1.

In the dark, the resistance of the photosensor is several mOhms. Under the influence of light it decreases to several kOhms. In this case, transistors VT1, VT2 open, turning on relay K1, which controls the load circuit through contact K1.1. Diode VD1 does not allow self-induction current to pass when the relay is turned off.

Despite its simplicity, the photo relay circuit is highly sensitive. To set it to the required level, resistor R1 is used.

The supply voltage is selected according to the relay parameters and is 5-15 V. The winding current does not exceed 50 mA. If it is necessary to increase it, more powerful transistors and relays can be used. The sensitivity of the photo relay increases with increasing supply voltage.

Instead of a photoresistor, you can install a photodiode. If a sensor with increased sensitivity is needed, circuits with phototransistors are used. Their use is advisable in order to save electricity, since the minimum response limit of a conventional device is 5 lux, when surrounding objects are still distinguishable. The threshold of 2 lux corresponds to deep twilight, after which darkness sets in 10 minutes later.

It is advisable to use a photo relay even with manual lighting control, since you can forget to turn off the light, and the sensor will “take care” of this on its own. It is easy to install and the price is quite affordable.

Characteristics of photocells

The choice of photo relay is determined by the following factors:

  • photocell sensitivity;
  • supply voltage;
  • switching power;
  • external environment.

Sensitivity is characterized as the ratio of the resulting photocurrent to the external light flux and is measured in μA/lm. It depends on frequency (spectral) and light intensity (integral). To control lighting in everyday life, the last characteristic is important, depending on the total luminous flux.

The rated voltage can be found on the device body or in the accompanying document. Foreign-made devices may have different supply voltage standards.

The load on its contacts depends on the power of the lamps to which the photo relay is connected. Lighting photo relay circuits can provide for direct switching of lamps through sensor contacts or through starters when the load is high.

Outdoors, the twilight switch is placed under a sealed transparent cover. It provides protection from moisture and precipitation. When working in cold periods, heating is used.

Factory made models

Previously, the photo relay circuit was assembled by hand. Now this is not necessary, since devices have become cheaper and functionality has expanded. They are used not only for external or internal lighting, but also for controlling plant watering, ventilation systems, etc.

1. Photo relay FR-2

Factory-made models are widely used in automation devices, for example, to control street lighting. You can often see lights burning during the day that you forgot to turn off. With photo sensors, there is no need for manual lighting control.

The industrially manufactured photo relay circuit fr-2 is used for automatic control of street lighting. Relay K1 is also here. The FSK-G1 photoresistor with resistors R4 and R5 are connected to the base of transistor VT1.

Power is supplied from a single-phase 220 V network. When the illumination is low, the resistance of FSK-G1 is large and the signal based on VT1 is not enough to open it. Accordingly, transistor VT2 is also closed. Relay K1 is energized and its operating contacts are closed, keeping the lamps lit.

When the illumination increases to the operating threshold, the resistance of the photoresistor decreases and opens, after which relay K1 turns off, opening the power supply circuit for the lamps.

2. Types of photo relay

The choice of models is large enough so that you can choose the right one:

  • with a remote sensor located outside the product body, to which 2 wires are connected;
  • Lux 2 - a device with high reliability and quality level;
  • photo relay with 12 V power supply and load no higher;
  • module with a timer mounted on a DIN rail;
  • IEC devices from a domestic manufacturer with high quality and functionality;
  • AZ 112 - automatic machine with high sensitivity;
  • ABB, LPX are reliable manufacturers of European quality devices.

Methods for connecting a photo relay

Before purchasing a sensor, you need to calculate the power consumed by the lamps and take it with a margin of 20%. With a significant load, the circuit of a street photo relay provides for the additional installation of an electromagnetic starter, the winding of which must be switched on through the contacts of the photo relay, and switch the load with power contacts.

This method is rarely used at home.

Before installation, the supply voltage of ~220 V is checked. The connection is made from a circuit breaker. The photo sensor is installed in such a way that the light from the flashlight does not fall on it.

The device uses terminals to connect wires, which makes installation easier. If they are missing, a junction box is used.

Thanks to the use of microprocessors, the connection diagram of the photo relay with other elements has acquired new functions. A timer and a motion sensor were added to the action algorithm.

It is convenient when the lamps automatically turn on when a person passes along a landing or along a garden path. Moreover, operation occurs only in the dark. Due to the use of a timer, the photo relay does not react to headlights from passing cars.

The simplest connection diagram for a timer with a motion sensor is serial. For expensive models, special programmable circuits have been developed that take into account various operating conditions.

Photo relay for street lighting

To connect the photo relay, the circuit is applied to its body. It can be found in the documentation for the device.

Three wires come out of the device.

  1. Neutral conductor - common for lamps and photo relays (red).
  2. Phase - connected to the device input (brown).
  3. Potential conductor for supplying voltage from the photo relay to the lamps (blue).

The device operates on the principle of phase interruption or phase switching. Color markings may vary from manufacturer to manufacturer. If there is a ground conductor in the network, it is not connected to the device.

In models with a built-in sensor, which is located inside a transparent case, the street lighting operates autonomously. You just need to supply power to it.

Options with remote sensors are used when the electronic content of the photo relay is conveniently placed in the control panel with other devices. Then there is no need for stand-alone installation, power wiring and maintenance at height. The electronic unit is placed indoors, and the sensor is taken outside.

Features of photo relay for street lighting: diagram

When installing a photo relay outdoors, you need to take into account some factors.

  1. Availability of supply voltage and matching power of contacts and load.
  2. Installation of devices near flammable materials and in an aggressive environment is not allowed.
  3. The base of the device is located at the bottom.
  4. There should be no moving objects in front of the sensor, such as tree branches.

The wires are connected through an outdoor junction box. It is fixed next to the photo relay.

Selecting a photo relay

  1. The ability to adjust the response threshold allows you to adjust the sensitivity of the sensor depending on the time of year or in cloudy weather. The result is energy savings.
  2. A minimum of labor costs is required when installing a photo relay with a built-in sensitive element. This does not require any special skills.
  3. The timer relay is well programmable for its needs and operation in the set mode. You can set the device to turn off at night. Indication on the device body and push-button control make settings easy.

Conclusion

The use of a photo relay allows you to automatically control the period of lamp switching on. Now there is no longer any need to become a lamplighter. The photo relay circuit, without human intervention, turns on the lights on the streets in the evenings and turns them off in the morning. The devices can control the lighting system, which increases its resource and makes operation easier.

Light sensors (lighting), built on the basis of photoresistors, are quite often used in real Arduino projects. They are relatively simple, not expensive, and easy to find and buy in any online store. The Arduino photoresistor allows you to control the light level and respond to its changes. In this article we will look at what a photoresistor is, how a light sensor based on it works, and how to properly connect the sensor to Arduino boards.

A photoresistor, as the name suggests, is directly related to resistors, which are often found in almost any electronic circuit. The main characteristic of a conventional resistor is the value of its resistance. Voltage and current depend on it; using a resistor we set the required operating modes of other components. As a rule, the resistance value of a resistor practically does not change under the same operating conditions.

Unlike a conventional resistor, photoresistor can change its resistance depending on the level of ambient light. This means that the parameters in the electronic circuit will constantly change; first of all, we are interested in the voltage dropping across the photoresistor. By recording these voltage changes on the analog pins of the Arduino, we can change the logic of the circuit, thereby creating devices that adapt to external conditions.

Photoresistors are quite actively used in a wide variety of systems. The most common application is street lighting. If night falls on the city or it becomes cloudy, the lights turn on automatically. You can make an economical light bulb for the home from a photoresistor that turns on not according to a schedule, but depending on the lighting. You can even make a security system based on a light sensor, which will be triggered immediately after a closed cabinet or safe is opened and illuminated. As always, the scope of application of any Arduino sensors is limited only by our imagination.

What photoresistors can be bought in online stores

The most popular and affordable sensor option on the market are mass-produced models from Chinese companies, clones of products from the manufacturer VT. It’s not always possible to figure out who and what exactly this or that supplier produces, but to get started with photoresistors, the simplest option is quite suitable.

A novice Arduino user can be advised to buy a ready-made photo module that looks like this:


This module already has all the necessary elements for easily connecting a photoresistor to the Arduino board. Some modules implement a comparator circuit and provide a digital output and a trim resistor for control.

A Russian radio amateur can be advised to turn to the Russian PA sensor. Available on sale are FR1-3, FR1-4, etc. - were produced back in Soviet times. But, despite this, FR1-3 is a more accurate detail. From this follows the difference in price. For FR they ask for no more than 400 rubles. FR1-3 will cost more than a thousand rubles apiece.

Photoresistor marking

Modern labeling of models produced in Russia is quite simple. The first two letters are PhotoResistor, the numbers after the dash indicate the development number. FR -765 - photoresistor, development 765. Usually marked directly on the body of the part

The VT sensor has a resistance range indicated in the marking diagram. For example:

  • VT83N1 - 12-100kOhm (12K – illuminated, 100K – in the dark)
  • VT93N2 - 48-500kOhm (48K – illuminated, 100K – in the dark).

Sometimes, to clarify information about models, the seller provides a special document from the manufacturer. In addition to the operating parameters, the accuracy of the part is also indicated there. All models have a sensitivity range in the visible part of the spectrum. Collecting light sensor You need to understand that the accuracy of operation is a relative concept. Even for models from the same manufacturer, the same batch, or the same purchase, it can differ by 50% or more.

At the factory, the parts are tuned to wavelengths ranging from red to green light. Most people also “see” infrared radiation. Particularly precise parts can even detect ultraviolet light.

Advantages and disadvantages of the sensor

The main disadvantage of photoresistors is spectrum sensitivity. Depending on the type of incident light, the resistance can vary by several orders of magnitude. The disadvantages also include the low speed of reaction to changes in illumination. If the light blinks, the sensor does not have time to react. If the frequency of change is quite high, the resistor will generally stop “seeing” that the illumination is changing.

The advantages include simplicity and accessibility. Direct change in resistance depending on the light falling on it allows you to simplify the electrical connection circuit. The photoresistor itself is very cheap, it is included in numerous Arduino kits and constructors, and therefore is available to almost any novice Arduino maker.

Connecting a photoresistor to Arduino

In projects arduino The photoresistor is used as a light sensor. Receiving information from it, the board can turn relays on or off, start engines, and send messages. Naturally, we must connect the sensor correctly.

The connection diagram for the light sensor to the Arduino is quite simple. If we use a photoresistor, then in the connection diagram the sensor is implemented as a voltage divider. One arm changes depending on the illumination level, the second one supplies voltage to the analog input. In the controller chip, this voltage is converted into digital data through an ADC. Because When the resistance of the sensor decreases when light hits it, the value of the voltage falling across it will also decrease.

Depending on which arm of the divider we placed the photoresistor in, either increased or decreased voltage will be supplied to the analog input. If one leg of the photoresistor is connected to ground, then the maximum voltage value will correspond to darkness (the resistance of the photoresistor is maximum, almost all the voltage drops across it), and the minimum value will correspond to good lighting (resistance is close to zero, voltage is minimal). If we connect the photoresistor arm to the power supply, the behavior will be the opposite.

Installing the board itself should not cause any difficulties. Since the photoresistor has no polarity, it can be connected from either side; it can be soldered to the board, connected with wires using a circuit board, or used with ordinary clips (crocodile clips) for connection. The power source in the circuit is the Arduino itself. Photoresistor one leg is connected to the ground, the other is connected to the ADC board (in our example - AO). We connect a 10 kOhm resistor to the same leg. Naturally, you can connect a photoresistor not only to analog pin A0, but also to any other.

A few words about the additional 10 K resistor. It has two functions in our circuit: limiting the current in the circuit and generating the required voltage in the circuit with a divider. Current limitation is necessary in a situation where a fully illuminated photoresistor sharply reduces its resistance. And voltage generation is for predictable values ​​on the analog port. In fact, for normal operation with our photoresistors, a resistance of 1K is enough.

By changing the resistor value we can “shift” the sensitivity level to the “dark” and “light” sides. So, 10 K will give a quick switching of the onset of light. In the case of 1K, the light sensor will more accurately detect high light levels.

If you use a ready-made light sensor module, the connection will be even simpler. We connect the output of the VCC module to the 5V connector on the board, GND to ground. We connect the remaining pins to the Arduino connectors.

If the board has a digital output, then we send it to digital pins. If it’s analog, then go to analog. In the first case, we will receive a trigger signal - the illumination level has been exceeded (the trigger threshold can be adjusted using an adjustment resistor). From the analog pins we will be able to obtain a voltage value proportional to the actual illumination level.

An example sketch of a light sensor on a photoresistor

We connected the circuit with the photoresistor to the Arduino and made sure that everything was done correctly. Now all that remains is to program the controller.

Writing a sketch for a light sensor is quite simple. We only need to remove the current voltage value from the analog pin to which the sensor is connected. This is done using the analogRead() function we all know. We can then perform some actions depending on the light level.

Let's write a sketch for a light sensor that turns on or off an LED connected according to the following circuit.

The operating algorithm is as follows:

  • Determine the signal level from the analog pin.
  • We compare the level with the threshold value. The maximum value will correspond to darkness, the minimum value will correspond to maximum illumination. Let's choose a threshold value equal to 300.
  • If the level is less than the threshold, it is dark, you need to turn on the LED.
  • Otherwise, turn off the LED.
#define PIN_LED 13 #define PIN_PHOTO_SENSOR A0 void setup() ( Serial.begin(9600); pinMode(PIN_LED, OUTPUT); ) void loop() ( int val = analogRead(PIN_PHOTO_SENSOR); Serial.println(val); if ( val< 300) { digitalWrite(PIN_LED, LOW); } else { digitalWrite(PIN_LED, HIGH); } }

By covering the photoresistor (with your hands or a light-proof object), we can observe the LED turning on and off. By changing the threshold parameter in the code, we can force the light bulb to turn on/off at different lighting levels.

When installing, try to place the photoresistor and LED as far apart from each other as possible so that less light from the bright LED falls on the light sensor.

Light sensor and smooth change in backlight brightness

You can modify the project so that the brightness of the LED changes depending on the level of illumination. We will add the following changes to the algorithm:

  • We will change the brightness of the light bulb via PWM, sending values ​​from 0 to 255 to the pin with the LED using analogWrite().
  • To convert the digital value of the light level from the light sensor (from 0 to 1023) into the PWM range of LED brightness (from 0 to 255), we will use the map() function.

Sketch example:

#define PIN_LED 10 #define PIN_PHOTO_SENSOR A0 void setup() ( Serial.begin(9600); pinMode(PIN_LED, OUTPUT); ) void loop() ( int val = analogRead(PIN_PHOTO_SENSOR); Serial.println(val); int ledPower = map(val, 0, 1023, 0, 255); // Convert the resulting value into the PWM signal level. The lower the illumination value, the less power we must supply to the LED via PWM. analogWrite(PIN_LED, ledPower); // Change brightness)

In the case of another connection method, in which the signal from the analog port is proportional to the degree of illumination, you will need to additionally “reverse” the value by subtracting it from the maximum:

Int val = 1023 – analogRead(PIN_PHOTO_RESISTOR);

Light sensor circuit using a photoresistor and relay

Examples of sketches for working with relays are given in the article on programming relays in Arduino. In this case, we do not need to make complex movements: after determining the “darkness,” we simply turn on the relay and apply the corresponding value to its pin.

#define PIN_RELAY 10 #define PIN_PHOTO_SENSOR A0 void setup() ( pinMode(PIN_RELAY, OUTPUT); digitalWrite(PIN_RELAY, HIGH); ) void loop() ( int val = analogRead(PIN_PHOTO_SENSOR); if (val< 300) { // Светло, выключаем реле digitalWrite(PIN_RELAY, HIGH); } else { // Темновато, включаем лампочку digitalWrite(PIN_RELAY, LOW); } }

Conclusion

Projects using a light sensor based on a photoresistor are quite simple and effective. You can implement many interesting projects, and the cost of equipment will not be high. The photoresistor is connected using a voltage divider circuit with additional resistance. The sensor is connected to an analog port to measure various light levels or to a digital one if all we care about is the fact of darkness. In the sketch, we simply read data from an analog (or digital) port and decide how to react to the changes. Let's hope that now such simple “eyes” will appear in your projects.

For our next project we will be using a photoresistor. And we will consider the implementation of a night light for the bedroom, which will automatically turn on when it is dark and turn off when it becomes light.

The resistance of a photoresistor depends on the light falling on it. Using a photoresistor in conjunction with a conventional 4.7 kOhm resistor, we get a voltage divider in which the voltage passing through the photoresistor changes depending on the light level.

We apply the voltage from the divider to the input of the Arduino ADC. There we compare the resulting value with a certain threshold and turn the lamp on or off.

The circuit diagram of the divider is shown below. When the illumination increases, the resistance of the photoresistor drops and, accordingly, the voltage at the divider output (and ADC input) increases. When the illumination drops, everything is the other way around.

The photo below shows the assembled circuit on a breadboard. Voltages 0V and 5V are taken from Arduino. Pin A0 is used as an ADC input.

Below is an Arduino sketch. In this tutorial we simply turn on and off the LED that is built into the Arduino board. You can connect a brighter LED to leg 13 (via a ~220 Ohm resistor). If you connect a more powerful load, such as an incandescent lamp, then it should be connected through a relay or thyristor.

There are commented sections in the program code, they are used for debugging. It will be possible to control the ADC value (from 0 to 1024). Also, you need to change the value 500 (on and off threshold) in the code to the one you select experimentally by changing the illumination.

/* ** Night light ** ** www.hobbytronics.co.uk */ int sensorPin = A0; // set the input leg for the ADC unsigned int sensorValue = 0; // digital value of the photoresistor void setup() ( pinMode(13, OUTPUT); Serial.begin(9600); // start serial data output (for testing) void loop() ( sensorValue = analogRead(sensorPin); // read value from photoresistor if(sensorValue<500) digitalWrite(13, HIGH); // включаем else digitalWrite(13, LOW); // выключаем // Для отладки раскомментируйте нижеследующие строки //Serial.print(sensorValue, DEC); // вывод данных с фоторезистора (0-1024) //Serial.println(""); // возврат каретки //delay(500); }