SunFounder 3in1 Kit
Code
Note:
• You can open the file 1.4.pumping.ino under the path of 3in1-kit\learning_project\1.4.pumping.
• Or copy this code into Arduino IDE.
Add the tubing to the pump and place it in the basin. After the code is uploaded successfully, you can see that the water
in the basin is drained after a while. When doing this experiment, please keep the circuit away from water to avoid
short circuit!
4.2 2. Analog Write
6 of the Arduino’s 14 digital pins also have PWM out function. Therefore, in addition to writing digital signals to these
6 pins, you can also write analog signals (PWM wave signals) to them. This way you can make the LEDs show different
brightness or make the motor rotate at different speeds.
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Since it may be hard to
grasp the literal meaning, here is an example of controlling the intensity of an LED to help you better understand.
A digital signal consisting of high and low levels is called a pulse. The pulse width of these pins can be adjusted by
changing the ON/OFF speed. Simply put, when we turn the LED on, off, and on again for a short period of time (like
20ms, the visual dwell time of most people), We won’t see that it has gone out, but the brightness of the light will be
slightly weaker. During this period, the longer the LED is on, the brighter the LED will be. That is to say, within a
period, the wider the pulse, the greater the “electrical signal strength” output by the microcontroller.
This is the function needed to write the PWM wave.
• analogWrite(pin, value)
Writes an analog value (PWM wave) to a pin. Different output voltages (0-5V) can be sim-
ulated by generating a specified pulse signal. The pin will hold this signal until it is called
by a new read or write statement.
Syntax
analogWrite(pin, value)
Parameters
– pin: the Arduino pin to write to. Allowed data types: int.
– value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int.
Example of Analog Write
int pin = 9; //connect to pwm pin
void setup() {
pinMode(pin, OUTPUT); // sets the pin as output
}
void loop() {
for (int i = 0 ;i<255 ; i++){
analogWrite(pin, i); //analogWrite values from 0 to 255
delay(30);
(continues on next page)
96 Chapter 4. Basic Projects