-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathArduino_Reciever_Example
71 lines (56 loc) · 1.6 KB
/
Arduino_Reciever_Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <ESP32Servo.h> // Using Servo library to control servo
#include <esp_now.h>
#include <WiFi.h>
Servo servo; // Create a servo object to control a servo
const int buttonPin = 32; // Doesn't have to be this exact pin
const int motorPin = 13; // Doesn't have to be this exact pin
bool onState = false;
// Structure to receive data
typedef struct {
uint8_t command; // Change to uint8_t to match the sending data type
} ReceivedData;
ReceivedData myData;
// Callback function to handle received data
void OnDataRecv(const esp_now_recv_info *info, const uint8_t *incomingData, int len) {
memcpy(&myData, incomingData, sizeof(myData));
//Serial.print("Received command: ");
//Serial.println(myData.command); // This should now correctly print 1
if (myData.command == 1) {
onState = !onState; // Toggle the onState
}
}
void setup() {
// Initialize Serial for debugging
Serial.begin(115200);
// Set button pin as input
pinMode(buttonPin, INPUT_PULLDOWN);
// Attach servo
servo.attach(motorPin);
// Initialize WiFi in STA mode
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESP-NOW is successfully Init, we will register for recv CB to
// get recv packer info
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
// Check if button is pressed
if (digitalRead(buttonPin) == HIGH)
{
delay(200);
onState = !onState; // Toggle the state manually
}
if (onState)
{
servo.write(140);
}
else
{
servo.write(40);
}
//Serial.println(onState);
}