#include <ESP32Servo.h>
#include <esp_now.h>
#define START_BUTTON_PIN 2
#define STOP_BUTTON_PIN 3
#define LIMIT_SWITCH_PIN 4
#define MOTOR_PIN 5
Servo motor;
int cycleCount = 0;
bool motorDirection = true; // true for one direction, false for the opposite
void setup() {
pinMode(START_BUTTON_PIN, INPUT);
pinMode(STOP_BUTTON_PIN, INPUT);
pinMode(LIMIT_SWITCH_PIN, INPUT);
motor.attach(MOTOR_PIN);
Serial.begin(9600);
// Setup ESP-NOW
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
}
void loop() {
if (digitalRead(START_BUTTON_PIN) == HIGH || cycleCount < 5) {
if (digitalRead(LIMIT_SWITCH_PIN) == LOW) {
motorDirection = !motorDirection;
cycleCount++;
sendSignal();
}
rotateMotor(motorDirection);
} else if (digitalRead(STOP_BUTTON_PIN) == HIGH) {
motor.detach();
sendSignal();
}
}
void rotateMotor(bool direction) {
// Rotate the motor based on the direction
// This will need to be adjusted based on your specific motor and driver
if (direction) {
motor.write(180);
} else {
motor.write(0);
}
}
void sendSignal() {
// Send a signal to the other ESP32 device
// This will need to be adjusted based on your specific ESP32 devices and ESP-NOW setup
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
// Send message
uint8_t msg = '1';
esp_err_t result = esp_now_send(broadcastAddress, &msg, sizeof(msg));
if (result == ESP_OK) {
Serial.println("Sent with success");
} else {
Serial.println("Error sending the data");
}
}