Open KidsBlock and connect to the board, click File –> Load from your computer.
Choose D:\Code\2.Code_kidsIOT to open 4.3Brightness_adjustment.sb3
Click to connect to port and then click .
Code Blocks
Blocks |
Code block |
---|---|
Conceive:
Initialization
Set the pin of the white LED and the potentiometer module, initialize the serial monitor.
Main Code
Loop: Read the value output by the potentiometer, and set the value as the duty cycle of the LED module to control its brightness.
Build blocks:
①
② Put into “forever” and set pin to IO3.
③ Add a (map block).
Q : The brightness value of LED is 0 ~ 255, while the output analog value of potentiometer is 0 ~ 4095. So how to control the brightness via the potentiometer?
A : We use map block to map the output range to the brightness range.
Q : What is MAP?
A : In mathematics, MAP is the term for a relationship between two sets of elements that “correspond” to each other.
Set: a whole consisting of one or more defined elements.
There is a correspondence between Set A and B. For every Element a in Set A, there is always a unique element b corresponding to it in Set B, which is called map A to B.
The concept of mapping is not only used in mathematics, but in computer science. In a computer program, mapping is a way to map each element in one set to a unique element in another.
We assume that the output analog values of the potentiometer is A, and the brightness range is B. We map values in A to B, so the output value will correspond to a unique brightness value. This kind of one-to-one mapping enables the potentiometer to directly adjust the brightness.
Five values need to be set in this map block:
(1): the value to be mapped;
(2 & 3): the range of the value to be mapped;
(4 & 5): the range after mapping.
Set the mapped value as the analog value read by IO34: Drag to the first box and set pin to IO34.
Set the range of the value to be mapped: here is the output range of the potentiometer(0 ~ 4095), so we set the second and third value to 0 and 4095 respectively.
Set the range after mapping: here is the brightness value range of LED(0 ~ 255), so we set the forth and fifth value to 0 and 255 respectively.
④ Put the map block into the PWM output as the duty cycle of the white LED module, so that we can control the brightness via the potentiometer.