Open KidsBlock and connect the board to computer. Choose File –> Load from your computer.
Choose path D:\Code\2.Code_kidsIOT and open 4.5Gearshift mode.sb3.
Click to connect to port and then .
Code Blocks
Blocks |
Code block |
---|---|
Conceive:
Initialization
Set pin mode and initialize the serial port.
Main Code
Loop:
Press button 5 to adjust the speed to 40%.
Press button 4 to adjust the speed to 60%.
Press button 3 to adjust the speed to 80%.
Press button 2 to adjust the speed to 100%.
Press button 1 to stop the fan.
Build blocks:
The code structure is similar to that in chapter 3.8.
In addition, here we adopt a map block to configure the motor PWM.
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 know that the rotation speed is effected by PWM duty cycle.
The range of PWM is 0 ~ 255. When PWM=255, the speed is at maximum. In this experiment, we set the speed range from 0 to 100, and map the speed values to PWM by the map block.
Divide PWM equally into 100 parts, so each part is 2.55, which corresponds to 1 speed.
Maximum unit of PWM: 2.55
Maximum unit of speed: 1
The speed value multiplied by 2.55 equals the corresponding PWM value:
In a map block, five operators need to be set:
The first is the value being mapped, here it is the speed value.
The second and third are the range of the value being mapped, here is the speed range.
The forth and fifth are the range of the mapping value, here is the range of motor PWM.
returns the PWM value of speed of 40.
Put it into to set the mapped value to the duty cycle of the motor, so that the motor will rotate at the speed of 40%.
Similarly, we duplicate this block and set speed value(the first operator in map block) to 60, 80 and 100 to make the fan work at the speed of 60%, 80% and 100%.
This map block can directly set the range of mapped values and of mapping values, so we only need to modify the mapped values without calculating the corresponding mapping values one by one.