To come in
Sewerage and drainpipes portal
  • Connecting a rotary encoder to a computer via USB
  • Homemade TV backlight from USB
  • Evaluation of methods for measuring low frequencies on the Arduino Brief description of the frequency meter FC1100-M2
  • Photoresistor and LEDs on Arduino
  • Line transformer tvs
  • Complementary FET Hi-Fi Amplifier
  • Connecting the photoresistor to the arduino nano. Photo relay diagram and connection rules

    Connecting the photoresistor to the arduino nano.  Photo relay diagram and connection rules

    A light sensor is a device that allows our device to assess the level of illumination. What is such a sensor for? 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 obstacle detection by a robot traveling through a maze. Or line detection by a robot tracker (LineFollower). But in these two cases, a special light source is used in tandem 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 implies, a photoresistor is a resistor that changes its resistance depending on the light incident on it. This radio element looks like this: Photoresistors differ in the range of resistance. For example:

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

    1. Connection

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

    Layout appearance


    See what happened. We simply built a conventional voltage divider, the upper arm of which will change depending on the level of light falling on the photoresistor. We apply the voltage removed from the lower arm to the analog input, which converts it to a number from 0 to 1024.

    2. Program

    Having connected the photoresistor according to a simple scheme, we begin to write a program. The first thing we'll do is feed the raw signal from the analog input to the serial port, just to understand how the value at input A0 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);) By running this program from us in the hackspace, we got the following values ​​from the sensor:
    Now let's cover the sensor with our hand:
    It can be seen that the value varies greatly. From 830 in case of direct light hit, to 500 in case of shading (the appearance of an obstacle in the path of light). Knowing this behavior, we can numerically determine the trigger threshold. Let it be equal, say, 600. Not exactly 500, because we want to protect ourselves from accidental triggering. Suddenly a fly will fly over the sensor - it will slightly shade and show 530. Finally, add to the program some action that will be performed if the illumination level falls below the specified threshold. The simplest thing we can do is turn on the regular LED # 13 on the Arduino. It turns out the following program: 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); } Накрываем датчик рукой (или выключаем свет в комнате) — светодиод зажигается. Убираем руку — гаснет. Работает, однако. А теперь представьте, что вы зажигаете не светодиод, а подаете сигнал на реле, которое включает лампу в подъезде вашего дома. Получаеся готовый прибор для экономии электроэнергии. Или ставите такой датчик на робота, и он при наступлении ночи ложится спать вместе с вами 🙂 В общем, как говорил профессор Фарнсворт, у датчика света тысяча и одно применение!
    1. Photoresistor: 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 the Arduino. which will drive the built-in LED.

    Photoresistor: The resistance of photoresistors decreases when exposed to light and increases in darkness. Photoresistors are easy to use, but they are slow enough to react to changes in the level of illumination and are very low. accuracy. Typically, the resistance of photoresistors can range from 50 ohms in daylight to more than 10 megohms in the dark.

    We will connect the photoresistor itself to the ground through a 10 kΩ resistor and we will connect the same leg to the analog pin of Arduino A0, the second leg of the photoresistor will be connected to 5 volts of the 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; // Specify 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 hits the photoresistor and the built-in LED is off, cover the photoresistor with your hand and you will see that at some point the LED turns on! You can also see changes in the value from the photoresistor in the port monitor.

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

    Video:

    The built-in ADC of the microcontroller, considered in the previous part of the review, allows you to easily connect various analog sensors to the Arduino board, which convert the measured physical parameters into electrical voltage.

    An example of the simplest analog sensor is a variable resistor connected to a board, as shown in Fig. 1. It can be of any type, for example, SP3-33-32 (Fig. 2). The resistor value in the diagram is indicated roughly and can be either less or more. However, it should be remembered that the lower the resistance of the variable resistor, the more current it consumes from the power supply of the microcontroller. And when the resistance of the signal source (in this case, the variable resistor) is more than 10 kOhm, the ADC of the microcontroller works with large errors. Note that the resistance of the variable resistor as a signal source depends on the position of its slider. It is equal to zero in its extreme positions and maximum (equal to a quarter of the nominal resistance) in the middle position.

    Rice. 1. Scheme of connecting a variable resistor to the board

    Rice. 2.SP3-33-32

    It is convenient to use a variable resistor when you need to change the parameter smoothly, and not in steps (discretely). As an example, consider the work shown in table. 1 program that changes the brightness of the LED depending on the position of the variable resistor slider. The U = U / 4 line is needed in the program in order to convert a ten-bit binary number returned by the ADC to an eight-bit one, which is accepted as the second operand by the analogWrite () function. In the case under consideration, this is done by dividing the original number by four, which is equivalent to discarding the two least significant bits.

    Table 1.

    A variable resistor of a suitable design can serve as a rotary angle or linear displacement sensor. Likewise, many radioelements can be connected to it: photoresistors, thermistors, photodiodes, phototransistors. In short, devices, the electrical resistance of which depends on certain environmental factors.

    In fig. 3 shows the connection diagram of the photoresistor to the Arduino. When the illumination changes, its electrical resistance changes and, accordingly, the voltage at the analog input of the Arduino board. The FSK-1 photoresistor indicated in the diagram can be replaced with any other, for example, SF2-1.

    Rice. 3. Wiring diagram of photoresistor to Arduino

    Table 2 shows a program that turns an Arduino board with a photoresistor connected to it into the simplest light meter. While working, it periodically measures the voltage drop across the resistor connected in series with the photoresistor, and transmits the result in arbitrary units through the serial port to the computer. They will be displayed on the screen of the Arduino debug terminal, as shown in Fig. 4. As you can see, at a certain moment, the measured voltage dropped sharply. This happened when a brightly lit photodiode was obscured by an opaque screen.

    Table 2.

    Rice. 4. The image on the screen of the Arduino debug terminal

    To obtain illumination values ​​in lux (standard SI units), you need to multiply the results obtained by a correction factor, but you will have to choose it experimentally, and individually for each photoresistor. This requires an exemplary light meter.

    A phototransistor or photodiode (Figure 5) is connected to the Arduino in a similar way. Using several light-sensitive devices, it is possible to construct the simplest vision system for a robot. It is also possible at a new technical level to implement many classical designs known to a wide circle of radio amateurs - a cybernetic model of a moth or a model of a tank that moves into the light.

    Rice. 5. Wiring diagram of photodiode to Arduino

    Similarly to the photoresistor, a thermistor is connected to the Arduino (Fig. 6), which changes its electrical resistance depending on the temperature. Instead of the MMT-4 thermistor indicated in the diagram, the main advantage of which is a sealed housing, you can use almost any other, for example, MMT-1 or imported.

    Rice. 6. Wiring diagram for thermistor to Arduino

    After appropriate calibration, such a device can be used to measure temperature in all kinds of home weather stations, thermostats and similar structures.

    It is known that almost all LEDs can serve not only as light sources, but also as its receivers - photodiodes. The fact is that the crystal of the LED is in a transparent case and therefore its p-n junction is available for light from external sources. In addition, the body of the LED, as a rule, has the shape of a lens that focuses external radiation on this junction. Under its influence, for example, the reverse resistance of the pn junction changes.

    By connecting the LED to the Arduino board according to the diagram shown in Fig. 7, one and the same LED can be used both for its intended purpose and as a photosensor. A program illustrating this mode is shown in Table. 3. Its idea is that first a reverse voltage is applied to the pn junction of the LED, charging its capacity. The LED cathode is then isolated, configuring as an input the Arduino pin to which it is connected. After that, the program measures the duration of the discharge of the capacitance of the p-n junction of the LED by its own reverse current, depending on the external illumination, to the level of logical zero.

    Rice. 7. Diagram of connecting the LED to the Arduino board

    Table 3

    In the above program, the variable t is described as unsigned int - an unsigned integer. A variable of this type, unlike a regular int, which takes values ​​from -32768 to +32767, does not use its most significant bit to store the sign and can take values ​​from 0 to 65535.

    The program calculates the discharge time in the while (digitalRead (K)! = 0) t ++ loop. This cycle is executed, each time increasing the value of t by one, until the condition enclosed in brackets is true, that is, until the voltage at the cathode of the LED drops to a logic low level.

    Sometimes it is required for the robot not only to receive information about the illumination of the surface on which it moves, but also to be able to determine its color. A color sensor of the underlying surface is implemented, illuminating it alternately with LEDs of different glow colors and comparing the levels of signals reflected from it under different illumination using a photodiode. The connection diagram of the elements of the color sensor with the Arduino board is shown in Fig. 8, and the program serving it is in Table. 4.

    Rice. 8. Connection diagram of the elements of the color sensor with the Arduino board

    Table 4

    The procedure for measuring the signals received by the photodiode under different illumination of the surface of the signals is repeated many times, and the results obtained are accumulated to exclude random errors. The program then selects the largest of the accumulated values. This makes it possible to roughly judge the color of the surface. For a more accurate determination of the color, it is necessary to complicate the processing of the results, taking into account not only the largest of them, but also its ratio with the smaller ones. It is also necessary to take into account the real brightness of LEDs of different glow colors, as well as the spectral characteristics of the applied photodiode.

    An example of the design of a color sensor consisting of four LEDs and a photodiode is shown in Fig. 9. The optical axes of the LEDs and the photodiode should converge at one point on the investigated surface, and the devices themselves are located as close to it as possible in order to minimize the influence of extraneous light.

    Rice. 9. An example of the design of a color sensor from four LEDs and a photodiode

    The assembled sensor requires careful individual calibration on surfaces of different colors. It boils down to a selection of coefficients by which the measurement results obtained under different lighting conditions should be multiplied before comparison. A robot equipped with such a sensor can be taught to perform interesting motion algorithms. For example, he will be able to move around the working field of the same color, without violating the boundaries of the "forbidden" zones, painted in a different color.

    The electrical resistance of which changes under the influence of light rays falling on the light-sensitive surface and does not depend on the applied voltage, like a conventional resistor.

    Photoresistors are most commonly used to detect the presence or absence of light, or to measure the intensity of light. In the dark, their resistance is very high, sometimes reaching 1 MΩ, but when the LDR sensor is exposed to light, its resistance drops sharply, down to several tens of ohms, depending on the light intensity.

    Photoresistors have a sensitivity that changes with the wavelength of light. They are used in many devices, although they are inferior in popularity to photodiodes and phototransistors. Some countries have banned LDRs due to their lead or cadmium content for environmental reasons.

    Definition: A photoresistor is a photosensitive element whose resistance decreases in intense light and increases in its absence.

    Photoresistor characteristics

    Types of photoresistors and principle of operation

    Based on the materials used in production, photoresistors can be divided into two groups: with internal and external photoelectric effect. In the production of photoresistors with internal photoelectric effect, unalloyed materials such as silicon or germanium are used.

    The photons that hit the device cause electrons to move from the valence band to the conduction band. As a result of this process, a large number of free electrons appear in the material, thereby improving electrical conductivity and, consequently, decreasing resistance.

    Photoresistors with external photoelectric effect are made from materials with the addition of an impurity called a dopant. The dopant creates a new energy band on top of the existing valence band, populated by electrons. These electrons require less energy to make the transition to the conduction band due to the smaller energy gap. The result is that the photoresistor is sensitive to different wavelengths of light.

    Despite all this, both types show a reduction in resistance when illuminated. The higher the light intensity, the more the resistance drops. Therefore, the resistance of the photoresistor is an inverse, non-linear function of light intensity.

    The photoresistor in the diagrams is indicated as follows:

    Photoresistor sensitivity versus wavelength

    The sensitivity of the photoresistor depends on the wavelength of the light. If the wavelength is outside the operating range, then the light will have no effect on the LDR. We can say that LDR is not sensitive in this range of light wavelengths.

    Different materials have different unique spectral waveform response curves versus sensitivity. Externally light-dependent resistors are generally designed for longer wavelengths, with a tendency towards infrared (IR). When working in the infrared range, care must be taken to avoid overheating, which can affect measurements due to thermal effect changes in the resistance of the photoresistor.

    The following figure shows the spectral response of photoconductive detectors made of various materials.

    Photoresistor sensitivity

    Photoresistors have a lower sensitivity than photodiodes and phototransistors. Photodiodes and phototransistors are semiconductor devices that use light to control the flow of electrons and holes through a PN junction, while photoresistors lack this PN junction.

    If the luminous flux is at a stable level, then the resistance can still change significantly due to temperature changes, since LDRs are also sensitive to temperature changes. This quality of the photoresistor makes it unsuitable for accurately measuring light intensity.

    Photoresistor inertness

    Another interesting property of the photoresistor is that there is an inertness (delay time) between changes in illumination and changes in resistance.

    In order for the resistance to drop to a minimum in full illumination, it takes about 10 ms of time, and about 1 second for the resistance of the photoresistor to rise to a maximum after it is dimmed.

    For this reason, LDR cannot be used in devices where sudden changes in lighting must be taken into account.

    Photoresistor design and properties

    For the first time, photoconductivity was discovered in Selene, later other materials with similar properties were discovered. Modern photoresistors are made from lead sulfide, lead selenide, indium antimonide, but most often from cadmium sulfide and cadmium selenide. Popular cadmium sulfide LDRs are referred to as CDS photoresistors.

    To make a cadmium sulfide photoresistor, highly purified cadmium sulfide powder is mixed with inert binders. Then, this mixture is pressed and sintered. In a vacuum, a photosensitive layer in the form of a winding path is applied to the base with the electrodes. Then, the base is placed in a glass or plastic shell to prevent contamination of the photosensitive element.

    The spectral response curve of cadmium sulfide matches the human eye. The peak sensitivity wavelength is about 560-600 nm, which corresponds to the visible part of the spectrum. It should be noted that devices containing lead or cadmium are not RoHS compliant and are prohibited for use in countries that adhere to RoHS laws.

    Application examples of photoresistors

    Photoresistors are most often used as light sensors when it is required to detect the presence or absence of light or to record the intensity of light. Examples are street light switches and photoexposure meters. As an example of using a photoresistor, we give a photo relay circuit for street lighting.

    Photo relay for street lighting

    This photo relay circuit automatically turns on street lighting when night falls and turns off when it gets light. In fact, you can use this scheme to implement any type of automatic night lighting.

    When the photoresistor (R1) is illuminated, its resistance decreases, the voltage drop across the variable resistor R2 will be high, as a result of which the transistor VT1 opens. The VT1 collector (BC107) is connected to the base of the VT2 transistor (SL100). Transistor VT2 is closed and the relay is de-energized. When night falls, the LDR resistance increases, the voltage across the variable resistor R2 drops, the transistor VT1 closes. In turn, the transistor VT2 opens and supplies voltage to the relay, which turns on the lamp.

    Photoresistors give you the ability to determine the intensity of the light.

    They are small, inexpensive, require little energy, are easy to use, and are virtually indestructible.

    It is because of this that they are often used in toys, gadgets, and gadgets. Of course, DIY projects based on Arduino could not ignore these wonderful sensors.

    Photoresistors are essentially resistors that change their resistance (measured in ohms) depending on how much light hits their sensing elements. As mentioned above, they are very cheap, have different sizes and specifications, but most of them are not very accurate. Each photoresistor behaves slightly differently from the other, even if they are from the same batch from the manufacturer. Differences in readings can be up to 50% or more! So you shouldn't count on precision measurements. They are mainly used to determine the overall level of illumination in specific, "local" rather than "absolute" conditions.

    Photoresistors are an excellent choice for solving problems like "it is dark or light around", "is there something in front of the sensor (that limits the flow of light)", "which area has the maximum illumination level."


    Average technical characteristics of photoresistors

    The specifications below are for photoresistors from the Adafruit store. These photoresistors have similar characteristics to the PDV-P8001. Almost all photoresistors have different technical characteristics, although they work very similarly. If the seller gives you a link to the datasheet of your photoresistor, read them, and not what is stated below.

    • Size: Round, 5mm (0.2 ") in diameter (other photoresistors can be up to 12mm / 0.4" in diameter!).
    • Price: about $ 1.00 at the Adafruit store.
    • Resistance range: 200 kΩ (dark) to 10 kΩ (light).
    • Sensing Range: Sensors capture wavelengths from 400 nm (violet) to 600 nm (orange).
    • Power supply: any with a voltage of up to 100 V, use an average current of about 1 mA (depending on the supply voltage).

    Problems when using multiple sensors

    If, when adding additional sensors, it turns out that the temperature is inconsistant, this means that the sensors overlap each other when reading information from different analog pins. This can be fixed by adding two readouts with delays and displaying the first.

    Light level measurement

    As we said before, the resistance of the photoresistor changes depending on the level of illumination. When it is dark, the resistance of the resistor increases to 10 megohms. As the light level increases, the resistance falls. The graph below shows the approximate sensor resistance under different lighting conditions. Do not forget that the characteristics of each individual photoresistor will be slightly different, these characteristics only reflect the general trend.


    Please note that the characteristic is non-linear, but has a logarithmic character.

    Photoresistors do not perceive the entire range of light waves. In most versions, they are sensitive to light waves in the range between 700 nm (red) and 500 nm (green).


    That is, an indication of a light wavelength range that corresponds to blue will not be as effective as an indication of a green / yellow range!

    What is the unit of measure "lux"?

    Most datasheets use lux (lx) to indicate resistance at a given light level. But what is it - lx? This is not the method we use to describe brightness, so it is tied directly to the sensor. Below is a table of correspondences, which was taken from Wikipedia.


    Photoresistor check

    The easiest way to test your photoresistor is to connect a multimeter in resistance measurement mode to two contacts of the sensor and track the change in resistance at the output when you cover the sensor with your palm, turn off the light in the room, etc. Since the resistance changes in large ranges, the automatic mode works well. If you do not have automatic mode or it does not work correctly, try the 1 MΩ and 1 kΩ range.



    Photoresistor connection

    Since photoresistors are essentially resistance, they have no polarity. This means that you can connect them with their legs "whatever you like" and they will work!


    Photoresistors are really unpretentious. You can solder them, install them on the breadboard, use the clips to connect. The only thing to do is to bend your "legs" too often, as they can easily break off.


    Using photoresistors

    Analog voltage reading method

    The simplest use case is to connect one leg to the power source and the other to ground through a pull-down resistor. After that, the point between the constant-value resistor and the variable resistor - the photoresistor - is connected to the analog input of the microcontroller. The figure below shows the wiring diagram for the Arduino.


    In this example, a 5V power supply is connected, but remember that you can just as well use a 3.3V supply. In this case, the analog voltage values ​​will be in the range from 0 to 5V, that is, approximately equal to the supply voltage.

    It works as follows: when the resistance of the photoresistor decreases, the total resistance of the photoresistor and the pull-down resistor decreases from 600 kOhm to 10 kOhm. This means that the current through both resistors increases, which causes the voltage across the 10K resistor to rise. That's all!


    This table shows approximate analog voltage values ​​based on illumination / resistance level with a 5 V supply voltage and a 10 kΩ pull-down resistor.

    If you want to use the sensor in a brightly lit area and use a 10K resistor, it will quickly blow out. That is, it will almost instantly reach the permissible voltage level of 5 V and will not be able to distinguish more intense lighting. In this case, you should replace the 10K resistor with a 1K resistor. With such a circuit, the resistor will not be able to detect the level of darkness, but it is better to determine the shades of the high level of illumination. In general, you should play with this depending on your conditions!

    Alternatively, you can also use the "Axel Benz" formula for basic measurements of the minimum and maximum resistance value with a multimeter and then find the resistance value of the resistor using: Pull down resistor = square root (Rmin * Rmax), which will give you a much better result. result in the form:


    The table above shows the approximate analog voltage values ​​when using a 5 V sensor with a 1 kΩ pull-down resistor.

    Do not forget that our method does not give us a linear dependence of voltage on illumination! In addition, each sensor is different in its characteristics. With an increase in the light level, the analog voltage will rise, and the resistance will fall:

    Vo = Vcc (R / (R + Photocell))

    That is, the voltage is inversely proportional to the resistance of the photoresistor, which, in turn, is inversely proportional to the level of illumination.

    A simple example of using a photoresistor

    This sketch takes the analog readings to determine the brightness of the LED. The darker it is, the brighter the LED will shine! Remember that an LED must be connected to a PWM pin for this example to work. In this case, pin 11 is used.


    This example assumes that you are familiar with the basics of Arduino programming.

    / * simple photoresistor test sketch.

    Connect one leg of the photoresistor to 5V, the other to the Analog 0 pin.

    Then connect a 10k resistor between Analog 0 and ground.

    Connect the LED through a resistor between pin 11 and ground. * /

    int photocellPin = 0; // sensor and 10k pull-down resistor connected to a0

    int photocellReading; // read analog values ​​from the sensor divider

    int LEDpin = 11; // connect the red LED to pin 11 (PWM pin)

    int LEDbrightness; //

    void setup (void) (

    // we will send debugging information to the serial monitor

    Serial.begin (9600);

    void loop (void) (

    Serial.println (photocellReading); // analog values ​​from the sensor

    // LED lights up brighter if the light level on the sensor decreases

    // this means that we have to invert the read values ​​from 0-1023 to 1023-0

    photocellReading = 1023 - photocellReading;

    // now we have to convert the range 0-1023 to 0-255, since this is the range analogWrite uses

    LEDbrightness = map (photocellReading, 0, 1023, 0, 255);

    analogWrite (LEDpin, LEDbrightness);


    You can try other resistors depending on the light level you want to measure!

    Simple code for analog light level measurements

    There are no calculations in the sketch, only the display of values ​​that are interpreted as lighting levels. This is enough for many projects.


    / * A simple photoresistor test sketch.

    Connect one leg of the photoresistor to 5V, the other to the Analog 0 pin.

    Then connect the pin of the 10k resistor to ground, and the second to the analog pin Analog 0 * /

    int photocellPin = 0; // sensor and 10k pull-down resistor connected to a0

    int photocellReading; // data read from the analog pin

    void setup (void) (

    // Pass the debugging information to the serial monitor

    Serial.begin (9600);

    void loop (void) (

    photocellReading = analogRead (photocellPin);

    Serial.print ("Analog reading =");

    Serial.print (photocellReading); // analog values

    if (photocellReading

    Serial.println ("- Dark");

    ) else if (photocellReading

    Serial.println ("- Dim");

    ) else if (photocellReading

    Serial.println ("- Light");

    ) else if (photocellReading

    Serial.println ("- Bright");

    Serial.println ("- Very bright");

    This check was carried out in the room during the day. I covered the sensor with my hand and then with a piece of cloth.


    Reading values ​​from the photoresistor without using analog pins

    Since photoresistors are essentially ordinary resistors, they can be used even if your microcontroller does not have analog pins (or if all analog pins are occupied). This method is based on the basic properties of resistors and capacitors. If you take a capacitor that can transfer potential and connect it to a power source (for example, 5V) through a resistor, the voltage change will occur gradually. The higher the resistance of the resistor, the slower the voltage will change.

    Below is a piece of the oscillogram that characterizes what exactly happens to the digital pin (yellow). The blue line shows when the Arduino sketch itself starts to work and when it finishes its work (a section of about 1.2 ms duration).


    If we draw simple analogies, then the capacitor acts as a basket, and the resistor acts as a tube. It will take a long time to fill the basket with the thin tube. Depending on the thickness of the tube, the filling speed of the basket will vary.


    In our case, the "basket" is a 0.1 μF ceramic resistor. You can experiment with the capacitance of the capacitor. And this indicator will directly affect the time. If you want to measure the light level, use a 1uF capacitor. If you are working in low light conditions, you can use a 0.01uF capacitor.

    / * a simple sketch to test the performance of the photoresistor.

    Connect one leg of the photoresistor to power, the other to pin 2.

    After that, connect one leg of the 0.1 uF capacitor to pin 2, and the other to ground * /

    int photocellPin = 2; // photoresistor connected to pin 2

    int photocellReading; // digital values

    int ledPin = 13; // you can use the built-in LED

    void setup (void) (

    // send information for debugging to be displayed in the serial monitor window

    Serial.begin (9600);

    pinMode (ledPin, OUTPUT); // use LED as output

    void loop (void) (

    // read readings from the sensor using RCtime technology

    photocellReading = RCtime (photocellPin);

    if (photocellReading == 30000) (

    // if the readings reach 30,000, this means that we have reached the limit value

    Serial.println ("Nothing connected!");

    Serial.print ("RCtime reading =");

    Serial.println (photocellReading); // stream of read analog data

    // the brighter, the more often the LED blinks!

    digitalWrite (ledPin, HIGH);

    delay (photocellReading);

    digitalWrite (ledPin, LOW);

    delay (photocellReading);

    // use digital pin to measure resistance

    // we do this by supplying current to the capacitor and

    // calculating how long it will take to reach Vcc / 2 (for most Arduinos this is 2.5V)

    int RCtime (int RCpin) (

    int reading = 0; // start at 0

    // initialize the pin as output and set it to LOW (ground)

    pinMode (RCpin, OUTPUT);

    digitalWrite (RCpin, LOW);

    // Now set the pin as input and ...

    pinMode (RCpin, INPUT);

    while (digitalRead (RCpin) == LOW) (// count the time it takes to get the HIGH value

    reading ++; // increment for timing

    if (reading == 30000) (

    // if we get to this level, the resistance is so great

    // that most likely nothing is connected!

    break; // go out of the loop

    Video of Arduino projects using photoresistors

    Changing the engine speed using a photoresistor:

    The robot tracks the trajectory for movement using a photoresistor:

    Leave your comments, questions and share your personal experience below. New ideas and projects are often born in the discussion!