EasyManua.ls Logo

Keyestudio ESP32 - 4. Test Code; 5. Test Result; 6. Code Explanation

Keyestudio ESP32
344 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
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, OUTPUT);//servo pin is set to output
}
void loop() {
for(int i = 0 ; i <= 180 ; i++) {
servopulse(servoPin, i);//Set the servo to rotate from 0° to 180°
delay(10);//delay 10ms
}
for(int i = 180 ; i >= 0 ; i--) {
servopulse(servoPin, i);//Set the servo to rotate from 180° to 0°
delay(10);//delay 10ms
}
}
void servopulse(int pin, int myangle) { //Impulse function
int pulsewidth = map(myangle, 0, 180, 500, 2500); //Map Angle to pulse width
for (int i = 0; i < 10; i++) { //Output a few more pulses
digitalWrite(pin, HIGH);//Set the servo interface level to high
delayMicroseconds(pulsewidth);//The number of microseconds of delayed pulse width
˓value
digitalWrite(pin, LOW);//Lower the level of servo interface
}
}
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 Chapter 8. Arduino Tutorial

Table of Contents