Activity: Mastering the "While" Loop
Today, we are learning how to use the while loop. Instead of counting steps automatically like in a for loop, the robot now acts as if it is constantly asking: "Have I reached my destination yet? If the answer is NO, I will take one more step."
Please answer the following 4 questions in your notebook:
Understand the Logic: Why do we need the variable anguloActualBase in this code? What would happen if we didn't have it?
Predict Errors: Look at the code. What would happen to the robot if we forgot to write the line anguloActualBase = anguloActualBase + 1; inside the loop? Would it move? Why?
Run the Simulation: Go to Wokwi, copy and paste the while code, build your circuit, and see how the robot moves.
Reflect: Based on your test, explain in your own words why this loop is called "while" (mientras). How does the robot "decide" when to stop moving?
WOKWI CODE
/*
TITULO: codigo de bucle while cobot (Adaptado para Wokwi)
OBJETIVO: Usar servos conectados directamente al Arduino
*/
#include <Servo.h>
// Definimos los objetos para cada motor
Servo servoBase;
Servo servoHombro;
Servo servoCodo;
// Definimos los pines donde conectaremos los servos en Wokwi (Deben ser pines PWM: ~)
const int PIN_BASE = 9;
const int PIN_HOMBRO = 10;
const int PIN_CODO = 11;
// Variable de memoria
int anguloActualBase = 90;
void setup() {
Serial.begin(115200);
// Conectamos los servos a los pines
servoBase.attach(PIN_BASE);
servoHombro.attach(PIN_HOMBRO);
servoCodo.attach(PIN_CODO);
Serial.println(">>> INICIANDO PRUEBA WHILE SIN PCA9685 <<<");
// Posición inicial
servoBase.write(90);
servoHombro.write(90);
servoCodo.write(90);
delay(1000);
}
void loop() {
// --- EJEMPLO 1: MOVER BASE A LA DERECHA (Hasta 180) ---
Serial.println("--> Yendo hacia 180 grados...");
while (anguloActualBase < 180) {
anguloActualBase = anguloActualBase + 1;
servoBase.write(anguloActualBase);
delay(20);
}
delay(1000);
// --- EJEMPLO 2: MOVER BASE A LA IZQUIERDA (Hasta 0) ---
Serial.println("<-- Regresando a 0 grados...");
while (anguloActualBase > 0) {
anguloActualBase = anguloActualBase - 1;
servoBase.write(anguloActualBase);
delay(20);
}
delay(1000);
}
| Componente | Pin del Servomotor | Conexión en Arduino |
| Servo Base | Señal (Naranja/Amarillo) | Pin Digital 9 |
| Servo Hombro | Señal (Naranja/Amarillo) | Pin Digital 10 |
| Servo Codo | Señal (Naranja/Amarillo) | Pin Digital 11 |
| Todos los Servos | VCC (Rojo) | 5V |
| Todos los Servos | GND (Marrón/Negro) | GND |
___________________________________________________________________
ARDUINO CODE
/*
TITULO: codigo de bucle while cobot
GRADO: Septimo
OBJETIVO:
Entender el bucle 'while' (mientras).
El robot se moverá suavemente preguntando todo el tiempo:
"¿Ya llegué? No. Entonces doy un paso más."
*/
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver tarjeta = Adafruit_PWMServoDriver();
// --- 1. CONFIGURACIÓN ---
const int BASE = 0;
const int HOMBRO = 4;
const int CODO = 8;
const int PULSO_MIN = 150;
const int PULSO_MAX = 600;
// VARIABLES DE MEMORIA (Importante para el While)
// Necesitamos recordar en qué ángulo está cada motor
int anguloActualBase = 90;
void setup() {
Serial.begin(115200);
tarjeta.begin();
tarjeta.setPWMFreq(50);
Serial.println(">>> INICIANDO PRUEBA WHILE <<<");
// Posición inicial
tarjeta.setPWM(BASE, 0, gradosAPulsos(90));
tarjeta.setPWM(HOMBRO, 0, gradosAPulsos(90));
tarjeta.setPWM(CODO, 0, gradosAPulsos(90));
delay(1000);
}
void loop() {
// --- EJEMPLO 1: MOVER BASE A LA DERECHA (Subir hasta 180) ---
Serial.println("--> Yendo hacia 180 grados...");
// TRADUCCIÓN DEL WHILE:
// "Mientras (while) el angulo actual sea MENOR (<) que 180..."
// "...voy a sumar 1 al ángulo y moverme."
while (anguloActualBase < 180) {
anguloActualBase = anguloActualBase + 1; // 1. Aumentamos el contador
// 2. Movemos el motor a la nueva posición
tarjeta.setPWM(BASE, 0, gradosAPulsos(anguloActualBase));
// 3. Esperamos un poquito (Suavidad)
delay(20);
}
delay(1000); // Descanso al llegar
// --- EJEMPLO 2: MOVER BASE A LA IZQUIERDA (Bajar hasta 0) ---
Serial.println("<-- Regresando a 0 grados...");
// TRADUCCIÓN DEL WHILE:
// "Mientras (while) el angulo actual sea MAYOR (>) que 0..."
// "...voy a restar 1 al ángulo y moverme."
while (anguloActualBase > 0) {
anguloActualBase = anguloActualBase - 1; // 1. Restamos el contador
tarjeta.setPWM(BASE, 0, gradosAPulsos(anguloActualBase));
delay(20);
}
delay(1000); // Descanso antes de repetir
}
// --- FUNCIÓN DE TRADUCCIÓN (No tocar) ---
int gradosAPulsos(int grados) {
return map(grados, 0, 180, PULSO_MIN, PULSO_MAX);
}
| Componente | Pin/Cable del Componente | Pin en la ESP32 |
| PCA9685 | VCC | 3.3V |
| PCA9685 | GND | GND |
| PCA9685 | SDA | GPIO 21 |
| PCA9685 | SCL | GPIO 22 |
| Servos | Cable Positivo (+) | Fuente Externa 5V-6V (+) |
| Servos | Cable Negativo (-) | Fuente Externa / GND común |
| Servos | Cable Señal (Naranja) | Pines 0, 4, 8 de la tarjeta |
No hay comentarios:
Publicar un comentario