ESP32 Starter Kit
4. Test Code
Add libraries to Arduino IDE first.
/*
keyestudio ESP32 Inventor Learning Kit
Project 12 Servo
http://www.keyestudio.com
*/
int
servoPin
=
4;//servo PIN
void
setup() {
pinMode(servoPin,
}
void
loop() {
for(int
i
=
0
; i
servopulse(servoPin,
delay(10);//delay 10ms
}
for(int
i
=
180
; i
servopulse(servoPin,
delay(10);//delay 10ms
}
}
void servopulse(int
int
pulsewidth
=
map(myangle, 0, 180, 500, 2500);
for
(int
i
=
0; i
digitalWrite(pin,
delayMicroseconds(pulsewidth);//The number of microseconds of delayed pulse
value
digitalWrite(pin,
}
}
5. Test Result
After connecting the wiring and uploading code, the servo starts to rotate from 0° to 180° and then reverse.
6. Code Explanation
void servopulse(int pin, int myangle) : To integrate the code together for easy use and management, the first parameter
is the pin number, the second parameter is the Angle of the servo.
map(myangle, 0, 180, 500, 2500); This is a mapping variable range function used to map the range of myangle variable
from 0-180 to 500-2500, so that we can get a value of 2500 when the servo is set to 180°, 500-2500 is the time that the
servo high level is maintained.
86
OUTPUT);//servo pin is set to output
<=
180
; i++) {
i);//Set the servo to rotate from 0° to 180°
>=
0
; i--) {
i);//Set the servo to rotate from 180° to 0°
int
pin,
myangle) {
<
10; i++) {
//Output a few more pulses
HIGH);//Set the servo interface level to high
LOW);//Lower the level of servo interface
//Impulse function
//Map Angle to pulse width
width␣
Chapter 8. Arduino Tutorial
Need help?
Do you have a question about the ESP32 and is the answer not in the manual?
Questions and answers