Chat

Welcome to Flux

Treat Flux like your intern. Tell it what you'd like to build and it'll get to work. You can also ask it questions, brainstorm ideas, and teach it your preferences. Learn More

Explain project
Write a project description
Find schematic issues
Create a test plan
Simulate a circuit
Prepare for Manufacturing
Component Selection Workflow
New Subsystem Wizard

create a high level mermaid block diagram of this project. Include key component...

@copilot create a high level mermaid block diagram of this project. Include key component's manufacturer part number in each block whenever possible.
2y
To create a high-level block diagram of your Arduino Uno R3 Shield Template project, we'll use the Mermaid syntax which is a simple, code-like way of describing and visualizing diagrams like block diagrams. Unfortunately, I can't directly render or display Mermaid diagrams here, but I can provide you the Mermaid code which you can use in a compatible Markdown viewer or Mermaid live editor.
This project involves various components like resistors (with specific resistances and packages), a motor driver (U2 - TB6612FNG), diodes, inductors, a connector (J2), and power supply nets (VIN, +3V3, +5V). Let's create a simplified block diagram focusing on the core components, especially those with part numbers available:
graph TD;

    ArduinoUnoR3(Arduino Uno R3 PINOUT)
    MotorDriver[TB6612FNGPololu]
    Diode[Diode node_1N4007WShandong Jingdao Microelectronics]
    Motor[M2]
    J2[Connector J2]
    VIN[VIN PowerNet]
    Power3V3[+3V3 PowerNet]
    Power5V[+5V PowerNet]

    ArduinoUnoR3 -- "Digital/Analog I/O" --> J2
    J2 -- "Control Signals" --> MotorDriver
    MotorDriver -- "VMOT" --> VIN
    MotorDriver -- "VCC" --> Power5V
    MotorDriver -- "Outputs" --> Motor
    Diode -.-> |"Protection"| Motor
    Power3V3 -- "Supply" --> J2
    Power5V -- "Supply" --> J2

    classDef component fill:#f9f,stroke:#333,stroke-width:2px;
    classDef power fill:#bbf,stroke:#333,stroke-width:2px;
    classDef motor fill:#fdb,stroke:#333,stroke-width:2px;
    classDef diode fill:#ddd,stroke:#333,stroke-width:2px;

    class MotorDriver,Diode component;
    class Motor motor;
    class VIN,Power3V3,Power5V power;
Key components and connections are represented here:
  • Arduino Uno R3 PINOUT: Acts as a base, connecting to other peripheral devices or components. It doesn't have a specific part number as it's a template.
  • TB6612FNG (Pololu): This is the motor driver integrated circuit used to control motors.
  • 1N4007W (Shandong Jingdao Microelectronics): A diode, possibly used for protection or rectification.
  • M2: Represents a motor connected to the motor driver. The specific part number isn't provided, so it's generically labeled "M2."
  • J2: This connector might be used for interfacing with other boards or components.
  • VIN, +3V3, +5V PowerNets: Represent power supply lines. Each line is labeled with its voltage level.
This diagram is highly simplified and focuses only on the main components and their connections. Each block in the diagram represents a key component or group of components within your project. Additional components like resistors, inductors, and others are not shown for simplicity but could be included for a more detailed diagram.
2y
void loop() { // Leer el estado de los botones botonPin1State = digitalRead(boton1Pin); botonPin2State = digitalRead(boton2Pin);
// Debounce para boton1 if (botonPin1State == LOW && !sistemaEncendido) { delay(50); // Esperar para evitar rebotes if (digitalRead(boton1Pin) == LOW) { // Verificar nuevamente digitalWrite(led1Pin, HIGH); digitalWrite(led2Pin, LOW); sistemaEncendido = true; } }
// Debounce para boton2 if (botonPin2State == LOW && sistemaEncendido) { delay(50); if (digitalRead(boton2Pin) == LOW) { digitalWrite(led1Pin, LOW); digitalWrite(led2Pin, HIGH); apagarServos(); sistemaEncendido = false; } }
// Resto de la lógica permanece igual... }
1y
El codigo esta bien?
1y
This Arduino code is designed to manage button presses with a debounce delay to prevent unintended double presses. It controls two LEDs based on the states of the buttons. Here's a summary of what the code does:
Functionality
  1. Button State Reading:
    • Reads the state of two buttons connected to digital pins boton1Pin and boton2Pin.
  2. Debounce Logic:
    • Implements a debounce mechanism to ensure button presses are valid, essentially filtering out noise from the physical bouncing of the button contacts.
  3. LED Control:
    • Button 1 Logic:
      • When the button connected to boton1Pin is pressed and the system is not already "on" (sistemaEncendido is false):
        • Waits 50 milliseconds for debounce delay.
        • Confirms the button state is still pressed.
        • Turns led1Pin on and led2Pin off.
        • Sets sistemaEncendido to true.
    • Button 2 Logic:
      • When the button connected to boton2Pin is pressed and the system is "on":
        • Waits 50 milliseconds for debounce delay.
        • Confirms the button state is still pressed.
        • Turns led1Pin off and led2Pin on.
        • Calls apagarServos() to presumably turn off or reset something connected to servos (although the function itself is not shown).
        • Sets sistemaEncendido to false.
  4. Comments:
    • Placeholder comment indicating where additional logic can be added.
This code assumes the existence of the following:
  • Button and LED Pins: boton1Pin, boton2Pin, led1Pin, led2Pin.
  • Global Variables for Button States and System State: botonPin1State, botonPin2State, sistemaEncendido.
If you want to implement or build on this logic, it might be useful to know more about the specific requirements or the rest of the program, such as the intended functionality of apagarServos() or any additional hardware interfaces. Let me know if you have specific questions or need further assistance with it!
1y
El código parece estar bien estructurado para realizar la función básica que describes: controlar dos LEDs con dos botones y gestionar el estado encendido/apagado del sistema con un debounce para evitar rebotes en los botones. Sin embargo, hay algunos puntos que podrías revisar o mejorar:
  1. Debounce: Estás implementando un debounce básico con un simple delay(50). Esto funciona, pero puede causar que el microcontrolador quede inactivo durante esos milisegundos y podría ser menos eficiente si hay otras tareas que ejecutar. Una alternativa podría ser implementar una lógica de debounce que no use delay, como un contador o un temporizador.
  2. Comentarios: Asegúrate de que los comentarios del código expliquen claramente las partes más complejas o específicas. Aunque este fragmento es relativamente sencillo, un comentario detallado sobre el propósito de apagarServos() sería útil.
  3. Funciones como apagarServos(): Esta función se menciona pero no se ve en el código proporcionado. Asegúrate de que esté bien definida en tu código completo. Esto podría significar incluir acciones específicas para apagar los servos, posiblemente relacionados con los controladores de motores, como el TB6612FNG en tu proyecto.
  4. Variables y Configuración: Asegúrate de que las variables como boton1Pin, boton2Pin, led1Pin, led2Pin, y sistemaEncendido estén correctamente definidas en la configuración inicial del programa (setup()), incluyendo la configuración de pines como entradas o salidas usando pinMode().
Si quieres que revise algún otro aspecto del código o necesitas más ayuda, dímelo.
1y
// Definir miniservos Servo servo1; Servo servo2; Servo servo3; Servo servo4;
// Pines de los miniservos int servoPin1 = 3; int servoPin2 = 5; int servoPin3 = 6; int servoPin4 = 11;
// Pines para los pulsadores y LEDs int boton1Pin = 7; // Pin del botón de encendido int boton2Pin = 8; // Pin del botón de apagado int led1Pin = 12; // LED que indica encendido int led2Pin = 13; // LED que indica apagado
// Pines del sensor ultrasonico const int trigPin = 9; const int echoPin = 10; long duracion; int distancia;
// Variables para almacenar el estado de los botones int botonPin1State = 0; int botonPin2State = 0; bool sistemaEncendido = false; // Estado del sistema
void setup() { // Inicializar pines de servos servo1.attach(servoPin1); servo2.attach(servoPin2); servo3.attach(servoPin3); servo4.attach(servoPin4);
// Inicializar pines de pulsadores, LEDs y sensor ultrasonico pinMode(boton1Pin, INPUT_PULLUP); pinMode(boton2Pin, INPUT_PULLUP); pinMode(led1Pin, OUTPUT); pinMode(led2Pin, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);
// Apagar LEDs al inicio digitalWrite(led1Pin, LOW); digitalWrite(led2Pin, LOW); }
void loop() { // Leer el estado de los botones botonPin1State = digitalRead(boton1Pin); botonPin2State = digitalRead(boton2Pin);
// Si el botón de inicio es presionado if (botonPin1State == LOW && !sistemaEncendido) { // Cambiado a LOW debido a INPUT_PULLUP digitalWrite(led1Pin, HIGH); // Encender LED de encendido digitalWrite(led2Pin, LOW); // Apagar LED de apagado sistemaEncendido = true; // Cambiar el estado del sistema }
// Si el botón de paro es presionado if (botonPin2State == LOW && sistemaEncendido) { // Cambiado a LOW debido a INPUT_PULLUP digitalWrite(led1Pin, LOW); // Apagar LED de encendido digitalWrite(led2Pin, HIGH); // Encender LED de apagado apagarServos(); sistemaEncendido = false; // Cambiar el estado del sistema }
// Control del sistema si está encendido if (sistemaEncendido) { // Medir la distancia usando el sensor ultrasónico digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
// Leer el tiempo de duración del eco
duracion = pulseIn(echoPin, HIGH);

// Calcular la distancia en centímetros
distancia = duracion * 0.034 / 2;

// Controlar servos según la distancia
if (distancia <= 10) {
  servo1.write(50); // Mover servo 1
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
} else if (distancia <= 20) {
  servo1.write(0);
  servo2.write(80); // Mover servo 2
  servo3.write(0);
  servo4.write(0);
} else if (distancia <= 30) {
  servo1.write(0);
  servo2.write(0);
  servo3.write(100); // Mover servo 3
  servo4.write(0);
} else if (distancia <= 40) {
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(150); // Mover servo 4
} else {
  apagarServos(); // Apagar todos los servos si la distancia es mayor a 40
}
} }
// Función para apagar todos los servos void apagarServos() { servo1.write(90); // Usar un valor más neutro servo2.write(90); servo3.write(90); servo4.write(90); }
1y
Esta bien el codigo
1y
The Arduino sketch you've provided is a complete and functional program for controlling four servos based on the input from an ultrasonic distance sensor, along with buttons for turning the system on and off, and LEDs for status indication. Here's a breakdown of the key components and functionality:
Initialization
  • Servo Objects: Four servos are defined using the Servo library.
  • Pin Assignments: Pins are assigned for servos, buttons, and LEDs.
  • Ultrasonic Sensor Pins: trigPin and echoPin are used for measuring distance.
  • Status Variables: Variables to track button states and the system's operational status.
Setup Function
  • Attach Servos: Attaches each servo to its respective pin.
  • Configuring Pins:
    • Buttons are set as inputs with internal pull-up resistors.
    • LEDs are set as outputs.
    • Ultrasonic sensor pins configured appropriately.
  • Initial LED State: Both LEDs are turned off initially.
Loop Function
  • Button Handling:
    • Debounce logic for button presses is managed by checking if they are low.
    • Toggles system state based on button input.
  • Distance Measurement:
    • Uses ultrasonic sensor to measure distance by sending a pulse and recording the duration of the echo.
    • Converts the echo duration into a distance in centimeters.
  • Servo Control:
    • Actuates servos based on the measured distance:
      • Different target positions for servos are set depending on proximity thresholds $10 , \text{cm}$, $20 , \text{cm}$, $30 , \text{cm}$, $40 , \text{cm}$.
    • If the distance exceeds $40 , \text{cm}$, all servos are set back to a neutral position.
apagarServos Function
  • Resets all servos to a neutral position $90^\circ$, which is commonly used to stop servos or set them to a default state.
Improvements and Considerations
  • Debounce Timing: You might consider adding software debounce more explicitly, with a non-blocking approach.
  • Neutral Servo Position: Ensure that the position set in apagarServos is appropriate for your application. You might need to adjust the "neutral" position depending on the mechanical setup.
  • Code Organization: It's well organized, but adding comments or segmenting functionality into more modular functions could enhance readability and maintainability.
If you have any specific questions or need further explanations about a part of this code, feel free to ask!
1y
Based on the code you've provided, it appears to be structured correctly for the planned functionality. Let's review the main aspects to ensure it's working as expected:
Key Components of the Code
  1. Libraries and Initialization:
    • Includes the Servo library to control servo motors.
    • Defines servo objects and assigns them to pins.
  2. Pin Assignments:
    • Defines pins for servos, buttons, LEDs, and an ultrasonic sensor.
    • Configures pins using pinMode in the setup function:
      • Buttons are configured as INPUT_PULLUP, which means they are active low (they read LOW when pressed).
      • LEDs and the ultrasonic sensor's trigPin are configured as OUTPUT.
      • The ultrasonic sensor's echoPin is configured as INPUT.
  3. Main Loop Logic:
    • Button Press Handling:
      • Checks button states with digitalRead. For debounce, it assumes proper mechanical button design with no additional code for bounce.
      • Turns on/off LEDs and changes system state based on button presses.
    • Ultrasonic Sensor Reading:
      • Uses pulseIn to measure echo time and calculate distance.
    • Servo Control:
      • Depending on the measured distance, moves servos to specific positions.
      • If the distance is greater than 40 cm, it calls apagarServos().
  4. Debounce:
    • The code uses input pull-up resistors for buttons, this simplifies the wiring and ensures a stable state. However, there is no debounce logic except relying on delay() calls. Consider improving this with non-blocking methods if necessary.
  5. Function apagarServos:
    • Sets all servos to a neutral position (90 degrees), which effectively "turns off" their motion.
Suggestions for Improvement
  • Debounce Logic: Consider implementing a non-blocking debounce method to improve button reliability, especially if further functionality might be added.
  • Distance Thresholds: Ensure the distance thresholds and servo positions fit the application's physical setup.
  • Comments: While there are some comments, additional comments could further clarify specific logic, especially around sensor handling and servo positioning.
  • Component Feedback: Based on the physical setup, observe the actual behavior of servos and ensure their response to distance changes is as expected.
Overall, your code logically fits the desired behavior you described. Let me know if you need further customization or if you experience any specific issues in practice!
1y
// Definir miniservos Servo servo1; Servo servo2; Servo servo3; Servo servo4;
// Pines de los miniservos int servoPin1 = 3; int servoPin2 = 5; int servoPin3 = 6; int servoPin4 = 11;
// Pines para los pulsadores y LEDs int boton1Pin = 7; // Pin del botón de encendido int boton2Pin = 8; // Pin del botón de apagado int led1Pin = 12; // LED que indica encendido int led2Pin = 13; // LED que indica apagado
// Pines del sensor ultrasonico const int trigPin = 9; const int echoPin = 10; long duracion; int distancia;
// Variables para almacenar el estado de los botones int botonPin1State = 0; int botonPin2State = 0; bool sistemaEncendido = false; // Estado del sistema
void setup() { // Inicializar pines de servos servo1.attach(servoPin1); servo2.attach(servoPin2); servo3.attach(servoPin3); servo4.attach(servoPin4);
// Inicializar pines de pulsadores, LEDs y sensor ultrasonico pinMode(boton1Pin, INPUT_PULLUP); pinMode(boton2Pin, INPUT_PULLUP); pinMode(led1Pin, OUTPUT); pinMode(led2Pin, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);
// Apagar LEDs al inicio digitalWrite(led1Pin, LOW); digitalWrite(led2Pin, LOW); }
void loop() { // Leer el estado de los botones botonPin1State = digitalRead(boton1Pin); botonPin2State = digitalRead(boton2Pin);
// Si el botón de inicio es presionado if (botonPin1State == LOW && !sistemaEncendido) { // Cambiado a LOW debido a INPUT_PULLUP digitalWrite(led1Pin, HIGH); // Encender LED de encendido digitalWrite(led2Pin, LOW); // Apagar LED de apagado sistemaEncendido = true; // Cambiar el estado del sistema }
// Si el botón de paro es presionado if (botonPin2State == LOW && sistemaEncendido) { // Cambiado a LOW debido a INPUT_PULLUP digitalWrite(led1Pin, LOW); // Apagar LED de encendido digitalWrite(led2Pin, HIGH); // Encender LED de apagado apagarServos(); sistemaEncendido = false; // Cambiar el estado del sistema }
// Control del sistema si está encendido if (sistemaEncendido) { // Medir la distancia usando el sensor ultrasónico digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
// Leer el tiempo de duración del eco
duracion = pulseIn(echoPin, HIGH);

// Calcular la distancia en centímetros
distancia = duracion * 0.034 / 2;

// Controlar servos según la distancia
if (distancia <= 10) {
  servo1.write(50); // Mover servo 1
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
} else if (distancia <= 20) {
  servo1.write(0);
  servo2.write(80); // Mover servo 2
  servo3.write(0);
  servo4.write(0);
} else if (distancia <= 30) {
  servo1.write(0);
  servo2.write(0);
  servo3.write(100); // Mover servo 3
  servo4.write(0);
} else if (distancia <= 40) {
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(150); // Mover servo 4
} else {
  apagarServos(); // Apagar todos los servos si la distancia es mayor a 40
}
} }
// Función para apagar todos los servos void apagarServos() { servo1.write(90); // Usar un valor más neutro servo2.write(90); servo3.write(90); servo4.write(90); }
1y
podrias revisar el codigo
1y
Your code is well-structured and appears correct for the functionality you've described. It uses an ultrasonic sensor to monitor distance and control four servos based on predefined distance thresholds. It also includes basic control for turning the system on and off with buttons and provides feedback via LEDs.
Key Components and Logic
  1. Libraries and Servo Initialization:
    • Uses the Servo library for controlling the servos.
    • Initializes four servo objects.
  2. Pin Definitions:
    • Assigns pins for servos, LEDs, buttons, and an ultrasonic sensor.
    • Utilizes internal pull-up resistors for button inputs.
  3. Setup Function:
    • Attaches servos to their respective pins.
    • Configures buttons, LEDs, and ultrasonic sensor pins with pinMode().
    • Ensures LEDs are off at startup.
  4. Loop Functionality:
    • Button Handling:
      • Reads the state of buttons. If pressed (LOW due to pull-up configuration), it toggles the system state.
    • LED Indicators:
      • Turns on/off LEDs to indicate system state.
    • Distance Measurement:
      • Sends a pulse and measures the echo return time to calculate distance.
    • Servo Control:
      • Actuates servos based on the measured distance with specific thresholds.
    • ApagarServos Function:
      • Resets all servos to a neutral position (90°) for a safe stop.
Suggestions for Improvement
  • Debouncing: While buttons are checked for state changes, you could implement a software debouncing mechanism to ensure more reliable button presses.
  • Timing: Make sure the 10 µs trigger pulse is consistent with your sensor's requirements. In most cases, it's fine, but it's always good to refer to the sensor's datasheet.
  • Maximum Range for Servos: Ensure servo limits (0-180°) align with their actual range to prevent mechanical issues.
  • Distance Calculation: The speed of sound is considered with $0.034 \text{ cm/µs}$. If the environment temperature varies significantly, a correction factor might be applied for precise measurements.
  • Additional Functions: If the application expands, consider modularizing the code further by splitting into more functions for readability and maintenance.
Overall, your code should accomplish the intended task effectively. Feel free to ask if you have more questions or need further guidance!
1y
Sure! Let's review the code to ensure it achieves the desired functionality and follows best practices. Here's an overview of what the code does, along with some observations and suggestions:
Overview
  1. Setup Phase:
    • Servo Initialization: Four servo motors are attached to specific pins and initialized.
    • Pin Configuration:
      • Buttons are set up with internal pull-up resistors, making them active low.
      • LEDs are configured as outputs for status indication.
      • Ultrasonic sensor pins are appropriately configured.
    • Initial LED State: Both LEDs are turned off, indicating the system starts in an off state.
  2. Loop Phase:
    • Button Handling:
      • Checks the button states and changes the system's state based on which button is pressed.
    • Ultrasonic Distance Measurement:
      • Sends a pulse to the ultrasonic sensor and measures the echo time to determine the distance.
      • The distance is calculated and used to control the servo motors.
    • Servo Control:
      • Moves servos based on the measured distance thresholds.
  3. Stop Servos Function:
    • Resets all servos to a neutral position when turning off.
Suggestions for Improvement
  • Debounce the Buttons:
    • Implement a debounce algorithm to prevent false triggers due to button bounce. This can be done with software debounce without blocking delays or adjusting hardware.
  • Code Maintenance:
    • Comments are appropriate; ensure they match the code logic. Consider adding comments for future reference, especially around the servo movements and distance control logic.
  • Efficiency:
    • Ensure that delayMicroseconds provides sufficient time for sensor stabilization. The current setup seems sufficient, but testing might prove whether adjustments are needed.
  • Functionality Verification:
    • Check that the neutral position (90 degrees) aligns with the mechanical setup and that it effectively "stops" or resets the servos to a desired position.
  • Edge Cases:
    • Consider cases where sensor readings might be out of expected range or when no object is detected (e.g., handling duracion returning 0).
This sketch seems logically consistent with basic expectations of the hardware it controls, assuming correct hardware connections. If you have specific issues or further features to add, please let me know!
1y
Codigo con sugerencias
1y
Certainly! Below is your revised code with suggestions incorporated to enhance reliability and maintainability, particularly focusing on debouncing the input from the buttons without using delays.
Revised Code with Suggestions

Cpp


#include 

// Definir miniservos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

// Pines de los miniservos
int servoPin1 = 3;
int servoPin2 = 5;
int servoPin3 = 6;
int servoPin4 = 11; 

// Pines para los pulsadores y LEDs
int boton1Pin = 7; // Pin del botón de encendido
int boton2Pin = 8; // Pin del botón de apagado
int led1Pin = 12;  // LED que indica encendido
int led2Pin = 13;  // LED que indica apagado

// Pines del sensor ultrasonico
const int trigPin = 9; 
const int echoPin = 10;
long duracion;
int distancia;

// Variables para almacenar el estado de los botones
int botonPin1State = HIGH;
int botonPin1LastState = HIGH;
int botonPin2State = HIGH;
int botonPin2LastState = HIGH;
unsigned long lastDebounceTime1 = 0;
unsigned long lastDebounceTime2 = 0;
unsigned long debounceDelay = 50; // milliseconds

bool sistemaEncendido = false; // Estado del sistema

void setup() {
  // Inicializar pines de servos
  servo1.attach(servoPin1);
  servo2.attach(servoPin2);
  servo3.attach(servoPin3);
  servo4.attach(servoPin4);

  // Inicializar pines de pulsadores, LEDs y sensor ultrasonico
  pinMode(boton1Pin, INPUT_PULLUP);
  pinMode(boton2Pin, INPUT_PULLUP);
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Apagar LEDs al inicio
  digitalWrite(led1Pin, LOW);
  digitalWrite(led2Pin, LOW);
}

void loop() {
  // Leer el estado de los botones
  int reading1 = digitalRead(boton1Pin);
  int reading2 = digitalRead(boton2Pin);

  // Debouce para botón 1
  if (reading1 != botonPin1LastState) {
    lastDebounceTime1 = millis();
  }
  
  if ((millis() - lastDebounceTime1) > debounceDelay) {
    if (reading1 != botonPin1State) {
      botonPin1State = reading1;
      if (botonPin1State == LOW && !sistemaEncendido) {
        digitalWrite(led1Pin, HIGH);  // Encender LED de encendido
        digitalWrite(led2Pin, LOW);   // Apagar LED de apagado
        sistemaEncendido = true;      // Cambiar el estado del sistema
      }
    }
  }
  botonPin1LastState = reading1;

  // Debouce para botón 2
  if (reading2 != botonPin2LastState) {
    lastDebounceTime2 = millis();
  }

  if ((millis() - lastDebounceTime2) > debounceDelay) {
    if (reading2 != botonPin2State) {
      botonPin2State = reading2;
      if (botonPin2State == LOW && sistemaEncendido) {
        digitalWrite(led1Pin, LOW);   // Apagar LED de encendido
        digitalWrite(led2Pin, HIGH);  // Encender LED de apagado
        apagarServos();
        sistemaEncendido = false;     // Cambiar el estado del sistema
      }
    }
  }
  botonPin2LastState = reading2;

  // Control del sistema si está encendido
  if (sistemaEncendido) {
    // Medir la distancia usando el sensor ultrasónico
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Leer el tiempo de duración del eco
    duracion = pulseIn(echoPin, HIGH);

    // Calcular la distancia en centímetros
    distancia = duracion * 0.034 / 2;

    // Controlar servos según la distancia
    if (distancia <= 10) {
      servo1.write(50); // Mover servo 1
      servo2.write(0);
      servo3.write(0);
      servo4.write(0);
    } else if (distancia <= 20) {
      servo1.write(0);
      servo2.write(80); // Mover servo 2
      servo3.write(0);
      servo4.write(0);
    } else if (distancia <= 30) {
      servo1.write(0);
      servo2.write(0);
      servo3.write(100); // Mover servo 3
      servo4.write(0);
    } else if (distancia <= 40) {
      servo1.write(0);
      servo2.write(0);
      servo3.write(0);
      servo4.write(150); // Mover servo 4
    } else {
      apagarServos(); // Apagar todos los servos si la distancia es mayor a 40
    }
  }
}

// Función para apagar todos los servos
void apagarServos() {
  servo1.write(90); // Usar un valor más neutro
  servo2.write(90);
  servo3.write(90);
  servo4.write(90);
}
Key Enhancements
  • Debouncing: Implemented a software debounce mechanism using the millis() function to ensure that button presses are accounted for only once over a specified debounce period.
  • State Management: Used separate variables to track the last and current state of each button, which helps in identifying state changes as well as managing debouncing effectively.
  • Commentary: Comments are adjusted for clarity and understanding of the logic and flow.
These changes help to ensure responsiveness and reliability of the button inputs. If you need further modifications, feel free to ask!
1y
Someone is typing...
5
R1
R6
Resistance
330 Ω
R3
J2
R2
R5
Resistance
330 Ω
R4
Resistance
330 Ω
RESET
VIN
+3V3
+5V
J1


  • Ground
    A common return path for electric current. Commonly known as ground.
  • Net Portal
    Wirelessly connects nets on schematic. Used to organize schematics and separate functional blocks. To wirelessly connect net portals, give them same designator. #portal
  • Power Net Portal
    Wirelessly connects power nets on schematic. Identical to the net portal, but with a power symbol. Used to organize schematics and separate functional blocks. To wirelessly connect power net portals, give them the same designator. #portal #power
  • Generic Resistor
    A generic fixed resistor ideal for rapid circuit topology development. Its footprint automatically adapts based on the selected package case code—supporting 0402, 0603, 0805, 1203, and many other standard SMD packages, as well as axial horizontal and vertical configurations. Save precious design time by seamlessly add more information to this part (value, footprint, etc.) as it becomes available. Standard resistor values: 1.0 ohm, 10 ohm, 100 ohm, 1.0k ohm, 10k ohm, 100k ohm, 1.0M ohm 1.1 ohm, 11 ohm, 110 ohm, 1.1k ohm, 11k ohm, 110k ohm, 1.1M ohm 1.2 ohm, 12 ohm, 120 ohm, 1.2k ohm, 12k ohm, 120k ohm, 1.2M ohm 1.3 ohm, 13 ohm, 130 ohm, 1.3k ohm, 13k ohm, 130k ohm, 1.3M ohm 1.5 ohm, 15 ohm, 150 ohm, 1.5k ohm, 15k ohm, 150k ohm, 1.5M ohm 1.6 ohm, 16 ohm, 160 ohm, 1.6k ohm, 16k ohm, 160k ohm, 1.6M ohm 1.8 ohm, 18 ohm, 180 ohm, 1.8K ohm, 18k ohm, 180k ohm, 1.8M ohm 2.0 ohm, 20 ohm, 200 ohm, 2.0k ohm, 20k ohm, 200k ohm, 2.0M ohm 2.2 ohm, 22 ohm, 220 ohm, 2.2k ohm, 22k ohm, 220k ohm, 2.2M ohm 2.4 ohm, 24 ohm, 240 ohm, 2.4k ohm, 24k ohm, 240k ohm, 2.4M ohm 2.7 ohm, 27 ohm, 270 ohm, 2.7k ohm, 27k ohm, 270k ohm, 2.7M ohm 3.0 ohm, 30 ohm, 300 ohm, 3.0K ohm, 30K ohm, 300K ohm, 3.0M ohm 3.3 ohm, 33 ohm, 330 ohm, 3.3k ohm, 33k ohm, 330k ohm, 3.3M ohm 3.6 ohm, 36 ohm, 360 ohm, 3.6k ohm, 36k ohm, 360k ohm, 3.6M ohm 3.9 ohm, 39 ohm, 390 ohm, 3.9k ohm, 39k ohm, 390k ohm, 3.9M ohm 4.3 ohm, 43 ohm, 430 ohm, 4.3k ohm, 43K ohm, 430K ohm, 4.3M ohm 4.7 ohm, 47 ohm, 470 ohm, 4.7k ohm, 47k ohm, 470k ohm, 4.7M ohm 5.1 ohm, 51 ohm, 510 ohm, 5.1k ohm, 51k ohm, 510k ohm, 5.1M ohm 5.6 ohm, 56 ohm, 560 ohm, 5.6k ohm, 56k ohm, 560k ohm, 5.6M ohm 6.2 ohm, 62 ohm, 620 ohm, 6.2k ohm, 62K ohm, 620K ohm, 6.2M ohm 6.8 ohm, 68 ohm, 680 ohm, 6.8k ohm, 68k ohm, 680k ohm, 6.8M ohm 7.5 ohm, 75 ohm, 750 ohm, 7.5k ohm, 75k ohm, 750k ohm, 7.5M ohm 8.2 ohm, 82 ohm, 820 ohm, 8.2k ohm, 82k ohm, 820k ohm, 8.2M ohm 9.1 ohm, 91 ohm, 910 ohm, 9.1k ohm, 91k ohm, 910k ohm, 9.1M ohm #generics #CommonPartsLibrary
  • Generic Capacitor
    A generic fixed capacitor ideal for rapid circuit topology development. You can choose between polarized and non-polarized types, its symbol and the footprint will automatically adapt based on your selection. Supported options include standard SMD sizes for ceramic capacitors (e.g., 0402, 0603, 0805), SMD sizes for aluminum electrolytic capacitors, and through-hole footprints for polarized capacitors. Save precious design time by seamlessly add more information to this part (value, footprint, etc.) as it becomes available. Standard capacitor values: 1.0pF, 10pF, 100pF, 1000pF, 0.01uF, 0.1uF, 1.0uF, 10uF, 100uF, 1000uF, 10000uF 1.1pF, 11pF, 110pF, 1100pF 1.2pF, 12pF, 120pF, 1200pF 1.3pF, 13pF, 130pF, 1300pF 1.5pF, 15pF, 150pF, 1500pF, 0.015uF, 0.15uF, 1.5uF, 15uF, 150uF, 1500uF 1.6pF, 16pF, 160pF, 1600pF 1.8pF, 18pF, 180pF, 1800pF 2.0pF, 20pF, 200pF, 2000pF 2.2pF, 22pF, 220pF, 2200pF, 0.022uF, 0.22uF, 2.2uF, 22uF, 220uF, 2200uF 2.4pF, 24pF, 240pF, 2400pF 2.7pF, 27pF, 270pF, 2700pF 3.0pF, 30pF, 300pF, 3000pF 3.3pF, 33pF, 330pF, 3300pF, 0.033uF, 0.33uF, 3.3uF, 33uF, 330uF, 3300uF 3.6pF, 36pF, 360pF, 3600pF 3.9pF, 39pF, 390pF, 3900pF 4.3pF, 43pF, 430pF, 4300pF 4.7pF, 47pF, 470pF, 4700pF, 0.047uF, 0.47uF, 4.7uF, 47uF, 470uF, 4700uF 5.1pF, 51pF, 510pF, 5100pF 5.6pF, 56pF, 560pF, 5600pF 6.2pF, 62pF, 620pF, 6200pF 6.8pF, 68pF, 680pF, 6800pF, 0.068uF, 0.68uF, 6.8uF, 68uF, 680uF, 6800uF 7.5pF, 75pF, 750pF, 7500pF 8.2pF, 82pF, 820pF, 8200pF 9.1pF, 91pF, 910pF, 9100pF #generics #CommonPartsLibrary
  • Generic Inductor
    A generic fixed inductor suitable for rapid circuit topology development. The footprint automatically adapts based on the selected package, supporting standard SMD sizes (e.g., 0402, 0603, 0805) as well as well-known inductor packages such as SDR1806, PA4320, SRN6028, and SRR1260. Standard inductor values: 1.0 nH, 10 nH, 100 nH, 1.0 µH, 10 µH, 100 µH, 1.0 mH 1.2 nH, 12 nH, 120 nH, 1.2 µH, 12 µH, 120 µH, 1.2 mH 1.5 nH, 15 nH, 150 nH, 1.5 µH, 15 µH, 150 µH, 1.5 mH 1.8 nH, 18 nH, 180 nH, 1.8 µH, 18 µH, 180 µH, 1.8 mH 2.2 nH, 22 nH, 220 nH, 2.2 µH, 22 µH, 220 µH, 2.2 mH 2.7 nH, 27 nH, 270 nH, 2.7 µH, 27 µH, 270 µH, 2.7 mH 3.3 nH, 33 nH, 330 nH, 3.3 µH, 33 µH, 330 µH, 3.3 mH 3.9 nH, 39 nH, 390 nH, 3.9 µH, 39 µH, 390 µH, 3.9 mH 4.7 nH, 47 nH, 470 nH, 4.7 µH, 47 µH, 470 µH, 4.7 mH 5.6 nH, 56 nH, 560 nH, 5.6 µH, 56 µH, 560 µH, 5.6 mH 6.8 nH, 68 nH, 680 nH, 6.8 µH, 68 µH, 680 µH, 6.8 mH 8.2 nH, 82 nH, 820 nH, 8.2 µH, 82 µH, 820 µH, 8.2 mH #generics #CommonPartsLibrary
  • Terminal
    Terminal
    An electrical connector acting as reusable interface to a conductor and creating a point where external circuits can be connected.
  • RMCF0805JT47K0
    47 kOhms ±5% 0.125W, 1/8W Chip Resistor 0805 (2012 Metric) Automotive AEC-Q200 Thick Film #forLedBlink
  • 875105359001
    10uF Capacitor Aluminum Polymer 20% 16V SMD 5x5.3mm #forLedBlink #commonpartslibrary #capacitor #aluminumpolymer #radialcan
  • CTL1206FYW1T
    Yellow 595nm LED Indication - Discrete 1.7V 1206 (3216 Metric) #forLedBlink

Arduino Uno R3 Shield Template

Arduino Uno R3 Shield Template thumbnail
Template for Arduino Uno R3 Shield. Include an official pinout so you will always know Arduino names, the alternative roles of pins, which one is SDA, or SCL, etc. On PCB you can find the 3D model of the Arduino Uno R3 itself along with the board outline on the silkscreen. #Arduino #Uno #Shield #Template #project-template #project

Properties

Properties describe core aspects of the project.

Pricing & Availability

Distributor

Qty 1

Digi-Key

$0.02–$0.10

LCSC

$0.00–$0.01

Controls