Night light from an old light bulb, based on Arduino and WS2812. Tasks for independent solution

Probably everyone had a dream in childhood (and more than one). You can even try to remember the feeling that fills a child’s soul when his dream comes true, or that distant, familiar sparkle in his eyes... As a child, I dreamed of having my own night light.

Now I’m a 4th year student at BSUIR, and when we were told that a course project in circuit design can be done not on paper, but on a piece of hardware, it dawned on me: the night light that I so desired as a child can be made by myself. Moreover, make not just an object that will illuminate the room in the dark, but a device that can be easily controlled to suit any mood. Why not? I decided to add the ability to change colors using my hands: the closer my hand is to the night light, the brighter one of the colors (RGB) lights up. I would also like to control the night light using the remote control.

I’ll admit right away that I spotted the idea on the website cxem.net. Briefly, this example used an RGB matrix, which was controlled using shift registers, and ultrasonic distance sensors. But I thought that the matrix shines only in one direction, but I wanted the night light to shine on the sides.

Justification of the circuit elements


I turned my attention to Arduino microcontrollers. UNO is quite a suitable option for my idea, firstly because it is the most popular platform and the number of pins is not too large, unlike Mega, and secondly, you can connect an external power source to it, in my case it is 12V, unlike Nano , thirdly... well, I think we can stop at these two points. The platform is extremely popular all over the world due to the convenience and simplicity of the programming language, as well as its open architecture and program code.

More detailed information You can easily find information about this board on the Internet, so I won’t overload the article.

So, the basic requirements for the system. Required:
– sensors that will track the distance to an obstacle to control the system;
– sensor for reading signals from the remote control remote control;
– LEDs, which will provide the necessary lighting functionality;
– a control unit that will control the entire system.

The project requires rangefinders as distance sensors, each of which will correspond to a specific color: red, green, blue. Distance sensors will monitor the distance of the hand to the night light and the closer the hand is brought to a certain sensor, the stronger the color corresponding to this rangefinder will light up. Conversely, the further away the hand is, the less voltage is applied to the color corresponding to the sensor.

The most popular rangefinders on this moment these are Sharp GP2Y0A21YK and HC-SR04. Sharp GP2Y0A21YK is an infrared rangefinder. It is equipped with an IR emitter and an IR receiver: the first serves as the source of the beam, the reflection of which is caught by the second. At the same time, the IR rays of the sensor are invisible to the human eye and at such intensity are harmless.

Compared with the HC-SR04 ultrasonic sensor, this sensor has both advantages and disadvantages. The advantages include neutrality and harmlessness. The disadvantages are a shorter range and dependence on external interference, including some types of lighting.

Used as distance sensors for the project: ultrasonic rangefinders HC-SR04.
The operating principle of the HC-SR04 is based on the well-known phenomenon of echolocation. When using it, the emitter generates an acoustic signal, which, having been reflected from the obstacle, returns to the sensor and is registered by the receiver. Knowing the speed of propagation of ultrasound in air (approximately 340 m/s) and the delay time between the emitted and received signal, it is easy to calculate the distance to the acoustic barrier.

The TRIG input connects to any pin of the microcontroller. A pulse must be applied to this pin. digital signal duration 10 μs. Based on the signal at the TRIG input, the sensor sends a packet of ultrasonic pulses. After receiving the reflected signal, the sensor generates a pulse signal at the ECHO pin, the duration of which is proportional to the distance to the obstacle.

IR sensor. Of course, the signal required for remote control will be read and decoded from this sensor. TSOP18 differ from each other only in frequency. The VS1838B TSOP1838 sensor was selected for the project.

The project was based on the idea of ​​lighting the room in any color, which means that you will need 3 primary colors from which the lighting will be obtained: red, green, blue. Therefore, the SMD 5050RGB LED model was chosen, which will cope with the task perfectly.

Depending on the amount of voltage supplied to each LED, they will change the intensity of this lighting. The LED must be connected through a resistor, otherwise we risk ruining not only it, but also the Arduino. The resistor is needed in order to limit the current on the LED to an acceptable value. The fact is that the internal resistance of the LED is very low and, if you do not use a resistor, then such a current will pass through the LED that it will simply burn out both the LED and the controller.

The LED strips used in the project are powered by 12V.

Due to the fact that the voltage on the LEDs in the “off” state is 6V and it is necessary to regulate the power supply, which exceeds 5V, it is necessary to add transistors to the circuit in the switching mode. My choice fell on the BC547c model.

Let us briefly consider, for those who have forgotten, the principle of operation npn transistor. If you do not apply voltage at all, but simply short-circuit the base and emitter terminals, even if not short-circuit, but through a resistor of several ohms, it turns out that the base-emitter voltage is zero. Consequently, there is no base current. The transistor is closed, the collector current is negligibly small, just the same initial current. In this case, the transistor is said to be in the cutoff state. The opposite state is called saturation: when the transistor is completely open, so that there is nowhere to open further. With this degree of opening, the resistance of the collector-emitter section is so low that it is simply impossible to turn on the transistor without a load in the collector circuit; it will burn out instantly. In this case, the residual voltage on the collector can be only 0.3...0.5V.

These two states, saturation and cutoff, are used when the transistor operates in a switching mode, like a regular relay contact. The main meaning of this mode is that a small base current controls a large collector current, which is several tens of times greater than the base current. A large collector current is obtained due to external source energy, but still the current gain, as they say, is obvious. In our case, the microcircuit, whose operating voltage is 5V, includes 3 strips with LEDs operating from 12V.

Let's calculate the operating mode of the key cascade. It is necessary to calculate the value of the resistor in the base circuit so that the LEDs burn at full power. A necessary condition when calculating is that the current gain be greater than or equal to the quotient of dividing the maximum possible collector current by the minimum possible base current:

Therefore, the strips can have an operating voltage of 220V, and the base circuit can be controlled from a microcircuit with a voltage of 5V. If the transistor is designed to operate with such a voltage at the collector, then the LEDs will light without problems.
The voltage drop across the base-emitter junction is 0.77V, provided that the base current is 5mA and the collector current is 0.1A.
The voltage across the base resistor will be:

According to Ohm's Law:

From the standard range of resistances we select an 8.2 kOhm resistor. This completes the calculation.

I would like to draw your attention to one problem that I encountered. When using the IRremote library, the Arduino froze when adjusting the blue color. After a long and thorough search on the Internet, it turned out that this library uses Timer 2 by default for this Arduino model. Timers are used to control PWM outputs.

Timer 0 (System time, PWM 5 and 6);
Timer 1 (PWM 9 and 10);
Timer 2 (PWM 3 and 11).

Initially, I used PWM 11 to regulate the blue color. Therefore, be careful when working with PWM, timers and third-party libraries that may use them. It's strange that home page There was nothing said about this nuance on Github. If you wish, you can uncomment the line with timer 1 and comment out 2.

Connecting the elements on the breadboard looks like this:

After testing on the breadboard, the phases “Placing elements on the board” and “Working with a soldering iron” began. After the first testing of the finished board, a thought creeps into my head: something went wrong. And here begins the phase, familiar to many, “Painstaking work with the tester.” However, the problems (several adjacent contacts were accidentally soldered together) were quickly eliminated and here is the long-awaited mischievous light of the LEDs.

Then it was just a matter of the body. For this reason, plywood with holes for our sensors was cut. Back cover it was made specially removable so that you could enjoy the view from the inside and, if desired, finish or redo something. It also has 2 holes for reprogramming the board and power supply.

The body was glued with two-component epoxy glue. It is worth noting the peculiarity of this glue for those who have not encountered it before. This product comes in two separate containers, and when the contents are mixed, an instant chemical reaction occurs. After mixing, you have to act quickly, within 3-4 minutes. For further use, you need to mix a new portion. So if you are trying to repeat this, my advice to you is to mix in small portions and act very quickly, there will not be much time to think. Therefore, it is worth thinking in advance about how and where to glue the body. Moreover, this cannot be done in one sitting.

For mounting strips with LEDs in top cover a tube was inserted through which all the wires passed perfectly.

When the issue with the lampshade arose, I remembered how as a child I made crafts from simple thread, glue and a balloon, which served as the base. The principle for the lampshade is the same, but wrapping a polyhedron turned out to be more difficult than a ball. Due to the pressure exerted by the threads on the structure, it began to narrow upward and the threads began to fall off. Urgently, with my hands covered in glue, it was decided to strengthen the structure from above. And then the CD came to the rescue. The end result is this night light:

What would you like to say in the end?

What should I change in the project? To supply the TRIG signal to the distance sensors, one could use one Arduino output instead of three. I would also provide a hole for the IR sensor (which I forgot about), which, alas, is still hidden in the case from which it, naturally, cannot read signals from the remote control. However, who said that you can’t solder or drill anything?

I would like to note that this was an interesting semester, and a great opportunity to try to do something not on paper, thanks to which I can put another tick next to the “childhood dream” item. And if you think that trying something new is difficult, and you don’t know what to do first, don’t worry. Many people have a thought running through their heads: where to start and how can this even be done? There are many tasks in life from which you can get confused, but once you try, you will notice that with a twinkle in your eyes you can move mountains, even if you have to try a little for this.

For an additional task

    1 more LED

    1 more resistor with a nominal value of 220 Ohms

    2 more wires

Schematic diagram

Scheme on the breadboard

note

    In this experiment we install a photoresistor between the power supply and the analog input, i.e. to position R1 in the voltage divider circuit. We need this so that when the illumination decreases, we receive less voltage at the analog input.

    Try to place the components so that the LED does not illuminate the photoresistor.

Sketch

p050_night_light.ino #define LED_PIN 13 #define LDR_PIN A0 #define POT_PIN A1 void setup() ( pinMode(LED_PIN, OUTPUT) ; ) void loop() ( // read the light level. By the way, announce // you can assign a variable and a value to it at once int lightness = analogRead(LDR_PIN) ; // read the value from the potentiometer with which we regulate // threshold value between conditional darkness and light int threshold = analogRead(POT_PIN) ; // declare a boolean variable and assign a value to it // “Is it dark now.” Boolean variables, as opposed to // integers, can contain only one of two values: // true or false. Such values // also called boolean. boolean tooDark = (lightness< threshold) ; // use program branching: the processor will execute one of // two blocks of code depending on the execution of the condition. // If (English “if”) is too dark... if (tooDark) ( // ...turn on the lighting digitalWrite(LED_PIN, HIGH) ; ) else ( // ...otherwise the light is not needed - turn it off digitalWrite(LED_PIN, LOW) ; ) )

Explanations for the code

    We use a new type of variable - boolean, which stores only the values ​​true (true, 1) or false (false, 0). These values ​​are the result of evaluating Boolean expressions. In this example, the Boolean expression is lightness< threshold . На человеческом языке это звучит как: «освещенность ниже порогового уровня». Такое высказывание будет истинным, когда освещенность ниже порогового уровня. Микроконтроллер может сравнить значения переменных lightness и threshold , которые, в свою очередь, являются результатами измерений, и вычислить истинность логического выражения.

    We put this logical expression in brackets only for clarity. It's always better to write readable code. In other cases, parentheses can affect the order of operations, as in ordinary arithmetic.

    In our experiment, the boolean expression will be true when the lightness value is less than the threshold value because we used the operator< . Мы можем использовать операторы > , <= , >= , == , != , which mean “greater than,” “less than or equal to,” “greater than or equal to,” “equal to,” “not equal to,” respectively.

    Be especially careful with the logical operator == and do not confuse it with the assignment operator = . In the first case, we compare the values ​​of expressions and get a logical value (true or false), and in the second case, we assign the value of the right operand to the left operand. The compiler does not know our intentions and will not issue an error, but we can accidentally change the value of some variable and then spend a long time looking for an error.

    The conditional if statement is one of the key ones in most programming languages. With its help, we can perform not only a strictly defined sequence of actions, but also make decisions about which branch of the algorithm to follow, depending on certain conditions.

    The logical expression lightness< threshold есть значение: true или false . Мы вычислили его и поместили в булеву переменную tooDark («слишком темно»). Таким образом мы как бы говорим «если слишком темно, то включить светодиод»

    With the same success we could say “if the illumination is less than the threshold level, then turn on the LED,” i.e. pass the entire logical expression to if:

if (lightness< threshold) { // ... }

    Behind conditional operator if necessarily follows a block of code that is executed if the logical expression is true. Don't forget about both curly braces ()!

    If, if the expression is true, we only need to execute one instruction, it can be written immediately after if (...) without curly braces:

if (lightness< threshold) digitalWrite(LED_PIN, HIGH) ;

    The if statement can be extended with an else construct. The block of code, or the single statement following it, will only be executed if the Boolean expression in if evaluates to false. The rules regarding curly braces are the same. In our experiment, we wrote "if it's too dark, turn on the LED, otherwise turn off the LED."

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 in electronic circuit The parameters 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 option sensors on the market are models of mass production 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 contains all the necessary elements for easy connection 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 low speed reactions 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. Directly changing the resistance depending on the light falling on it allows you to simplify electrical diagram connections. 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 regarding the additional 10 K resistor. It has two functions in our circuit: limiting the current in the circuit and forming required voltage in a 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. Actually 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 fast switching the onset of light. In the case of 1K, the light sensor will more accurately detect high light levels.

If you are using ready module light sensor, then 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.

In this experiment, the LED should turn on when the light level drops below a threshold set by a potentiometer.

LIST OF PARTS FOR THE EXPERIMENT

- 1 Arduino Uno board;

- 1 solderless breadboard;

- 1 LED;

- 1 photoresistor;

- 1 resistor with a nominal value of 220 Ohms, 1 resistor with a nominal value of 10 kOhms;

- 1 variable resistor (potentiometer);

- 10 male-male wires.

DETAILS FOR ADDITIONAL TASK

1 more LED;

Another 1 resistor with a nominal value of 220 Ohms;

2 more wires.

CIRCUIT DIAGRAM

DIAGRAM ON BREADBOARD

SKETCH

download sketch for Arduino IDE
#define LED_PIN 13 #define LDR_PIN A0 #define POT_PIN A1 void setup() ( pinMode(LED_PIN, OUTPUT); ) void loop() ( // read the lightness level. By the way, // you can declare a variable and assign a value to it at once int lightness = analogRead(LDR_PIN); // read the value from the potentiometer, which we use to adjust // the threshold value between conditional darkness and light int threshold = analogRead(POT_PIN); // declare a logical variable and assign it the value // “is it dark now”. Boolean variables, unlike // integer variables, can contain only one of two values: // true or false. Such values ​​// are also called boolean. boolean tooDark = (lightness< threshold); // используем ветвление программы: процессор исполнит один из // двух блоков кода в зависимости от исполнения условия. // Если (англ. «if») слишком темно... if (tooDark) { // ...включаем освещение digitalWrite(LED_PIN, HIGH); } else { // ...иначе свет не нужен — выключаем его digitalWrite(LED_PIN, LOW); } }

EXPLANATIONS FOR THE CODE

  • We are using a new type of variables − boolean, which store only values true (true, 1) or false (false, 0). These values ​​are the result of evaluating Boolean expressions. In this example, the Boolean expression is lightness< threshold . In human language this sounds like: “illuminance below the threshold level.” Such a statement will be true when the illumination is below the threshold level. The microcontroller can compare the values ​​of variables lightness And threshold, which in turn are the measurement results, and calculate the truth of the logical expression.
  • We put this logical expression in brackets only for clarity. It's always better to write readable code. In other cases, parentheses can affect the order of operations, as in ordinary arithmetic.
  • In our experiment, a Boolean expression will be true when the value lightness less than value threshold because we used the operator < . We can use operators > , <= , >= , = = , != , which mean “greater than,” “less than or equal to,” “greater than or equal to,” “equal to,” “not equal to,” respectively.
  • Be especially careful with the logical operator = = and don't confuse it with the assignment operator = . In the first case, we compare the values ​​of expressions and get a logical value (true or false), and in the second case, we assign the value of the right operand to the left operand. The compiler does not know our intentions and will not issue an error, but we can accidentally change the value of some variable and then spend a long time looking for an error.
  • Conditional operator ifIf") is one of the key ones in most programming languages. With its help, we can perform not only a strictly defined sequence of actions, but also make decisions about which branch of the algorithm to follow, depending on certain conditions.
  • For a logical expression lightness< threshold there is a meaning: true or false. We calculated it and put it into a boolean variable tooDark(“too dark”) Thus, we seem to be saying “if it’s too dark, then turn on the LED”
  • With the same success we could say “if the illumination is less than the threshold level, then turn on the LED,” i.e. transfer to if all logical expression:
if (lightness< threshold) { // ... }
  • Behind the conditional statement if There must be a block of code that is executed if the logical expression is true. Don't forget about both curly braces {} !
  • If, if the expression is true, we only need to execute one instructions, it can be written immediately after if (…) without curly braces:
if (lightness< threshold) digitalWrite(LED_PIN, HIGH);
  • Operator if can be extended by design else("otherwise"). A block of code or a single statement following it will only be executed if the logical expression in if has the meaning false , « lie" The rules regarding curly braces are the same. In our experiment, we wrote "if it's too dark, turn on the LED, otherwise turn off the LED."

QUESTIONS TO TEST YOURSELF

  1. If we install a photoresistor between the analog input and ground, our device will work in reverse: the LED will turn on when the amount of light increases. Why?
  2. What result of the device's operation will we get if the light from the LED falls on the photoresistor?
  3. If we do install the photoresistor as stated in the previous question, how do we need to change the program so that the device works correctly?
  4. Let's say we have the code if (condition) (action;). In what cases will it be done? action ?
  5. At what values y expression x + y > 0 will be true if x > 0 ?
  6. Is it necessary to indicate which instructions to execute if the condition is in the statement if false?
  7. What is the difference between the operator = = from the operator = ?
  8. If we use the construction if (condition) action1; else action2;, could there be a situation where none of the actions are executed? Why?

TASKS FOR INDEPENDENT SOLUTION

  1. Rewrite the program without using the variable tooDark while maintaining the functionality of the device.
  2. Add another LED to the circuit. Complete the program so that when the illumination falls below the threshold value, one LED turns on, and when the illumination falls below half the threshold value, both LEDs turn on.
  3. Change the circuit and program so that the LEDs turn on according to the same principle, but glow the more intensely the less light falls on the photoresistor.




Top