First Network
Reading time required
5minutes
Quick read only takes 2 minutes
Code is no longer straightforward; it has learned to think
Do you remember the smart desk lamp we created last time? Today, I will upgrade it—allowing it to automatically turn off when the light is sufficient and turn on when the light is insufficient. Such intelligent behavior requires the program to possess ‘judgment.’
This leads us to today’s main topic: flow control. It enables the program to respond differently based on various conditions, making the code truly ‘alive.’
1
Conditional Judgment: The Crossroads of Programs
Imagine the scene of getting up in the morning. You walk to the window and check the weather outside:
if(it's raining) { take an umbrella;} else { no umbrella;}
This is the simplest form of conditional judgment. In C language, it is written almost identically:
if(condition) { // execute this code if the condition is true} else { // execute this code if the condition is false}
Back to our smart desk lamp. Suppose the light sensor returns a value less than 50 indicating insufficient light, we can write:
int light_value = read_light_sensor();
if(light_value < 50) { turn_on_LED();} else { turn_off_LED();}
The program encounters a ‘crossroads’ here, deciding which way to go based on the condition light_value < 50.
When I first learned programming, I always forgot to add curly braces after the condition, which led to many funny situations. Once, I wrote an automatic watering system that watered regardless of soil moisture because I forgot to add curly braces; only the first line of code was controlled by the condition!
Tip: Even if there is only one line of code, develop the good habit of adding curly braces.
2
Multiple Conditions: More Complex Choices
Choices in real life often exceed two. For example, deciding what to wear:
if(temperature > 30) { wear short sleeves;} else if(temperature > 20) { wear long sleeves;} else if(temperature > 10) { wear a jacket;} else { wear a down jacket;}
This if-else if-else structure allows the program to handle more complex decisions. In our lamp project, it can be designed as:
if(light_value < 30) { set_brightness_to_max();} else if(light_value < 50) { set_brightness_to_medium();} else if(light_value < 70) { set_brightness_to_min();} else { turn_off_LED();}
In this way, the lamp can provide different brightness levels based on light intensity, making it smarter.
3
Loop Structures: Masters of Repetition
If conditional judgment gives the program ‘judgment,’ then loops provide the program with ‘action’—the ability to execute repeatedly without fatigue.
Think of doing push-ups while exercising. You wouldn’t say, ‘do one, then do another, then do another…’; instead, you would say, ‘do 20 push-ups.’ In C language, this corresponds to the for loop:
for(int i = 0; i < 20; i++) { do_one_pushup;}
The three parts of the for loop are quite interesting:
int i = 0: starts counting from 0 (programmers like to start from 0)
i < 20: continue as long as the count is less than 20
i++: increment the count by 1 after each execution
In microcontroller programming, loops are everywhere. For example, to make an LED blink:
while(1) { light_up_LED(); delay(500); turn_off_LED(); delay(500);}
This while(1) indicates ‘forever loop’ because the condition 1 is always true. Microcontroller programs typically run this way, continuously executing after power is applied.
4
Two Types of Loops, Each with Its Strengths
The for loop and while loop are like different tools, used in different scenarios.
For loops are suitable for situations where the number of iterations is known, such as scanning a keyboard matrix:
for(int row = 0; row < 4; row++) { for(int col = 0; col < 4; col++) { check_key(row, col); }}
While loops are suitable for situations where the number of iterations is uncertain but the termination condition is known, such as waiting for a button press:
while(button_not_pressed) { // do nothing, just wait}
When I first used a while loop, I accidentally created an infinite loop, and the microcontroller became like it was under a spell, completely unresponsive. I had to power cycle it to restart, and at that moment, I truly understood the importance of ‘conditional control.’
5
Practical Thinking: Smart Fan System
Now, let’s design a more practical project: a smart fan control system.
Requirements:
When the temperature exceeds 30 degrees, rotate at high speed
When the temperature is between 25-30 degrees, rotate at medium speed
When the temperature is below 25 degrees, stop rotating
Check the temperature every 5 seconds
You can first try to draw a flowchart on paper and think about what knowledge we learned today will be needed.
// Hint: Here you need temperature reading function, conditional judgment, loop
// Try to write the code framework!
6
From Concept to Practice
Today we explored flow control in programs, allowing the code to make judgments based on conditions and to execute repeatedly without fatigue. This is like injecting a soul into the program, transforming it from a rigid sequence of instructions into an intelligent decision-maker.
However, code written on paper is ultimately just theory. Next time, we will do something particularly rewarding—’burning’ the code into a real microcontroller, making this small chip work according to our will.
Preview: In Day 10, I will teach you step by step how to use the STC-ISP download software, how to connect hardware, and how to troubleshoot when the program download fails. These are all practical experiences I have accumulated over the years!
Are you ready? See you next time!
Thought Question: Can you design a program that controls the volume of a music player based on environmental noise using the knowledge learned today? Feel free to share your thoughts in the comments!