Files
Drone-FabAcademy-2025/src/controller/drone controller/src/main.cpp

113 lines
2.6 KiB
C++

#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
// declarations
int normalizePot(int pin, int minValue);
int mapPot(int normalizedValue);
int analogReadMultiPlexer(int addressA, int addressB, int addressC, int addressD, int pin);
void espNow();
const int MAXPWMVALUE = 1000;
const int MINPWMVALUE = 2000;
const uint8_t broadcastAddress[] = {0x8C, 0xBF, 0xEA, 0xCC, 0x8E, 0x5C};
// Define the struct that will be sent
typedef struct struct_message
{
int PWMCH1;
int PWMCH2;
int PWMCH3;
int PWMCH4;
} struct_message;
struct_message myData; // declare the struct as myData
esp_now_peer_info_t peerInfo; // create a class object of the ESPNow class
void setup()
{
espNow();
Serial.begin(9600);
pinMode(D3, OUTPUT);
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
pinMode(D8, OUTPUT);
pinMode(D9, OUTPUT);
pinMode(D0, INPUT);
}
void loop()
{
Serial.print("X:" + String(myData.PWMCH2));
Serial.println(" Y:" + String(myData.PWMCH1));
// Set values to send
myData.PWMCH1 = mapPot(analogReadMultiPlexer(0, 0, 0, 0, A0));
myData.PWMCH2 = mapPot(analogReadMultiPlexer(1, 0, 0, 0, A0)); // test values
myData.PWMCH3 = 1000;
myData.PWMCH4 = 1000;
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&myData, sizeof(myData));
if (result == ESP_OK)
{
// Serial.println("Sent with success");
}
else
{
// Serial.println("Error sending the data");
}
delay(10); //delay to avoid hammering the radio and to save power/heat
}
int mapPot(int normalizedValue)
{
return map(normalizedValue, 400, 2500, MINPWMVALUE, MAXPWMVALUE); // map the normalized value to the PWM range
}
int normalizePot(int pin, int minValue) // normalize the pot value to a range of 80 to 4095 instead of 0 to 4095 because the potmeter is at lower values not accurate
{
int pot = analogRead(pin);
if (pot <= minValue)
{
return 80;
}
else
{
return pot;
}
}
int analogReadMultiPlexer(int addressA, int addressB, int addressC, int addressD, int pin)
{
digitalWrite(D3, LOW);
digitalWrite(D6, addressA);
digitalWrite(D7, addressB);
digitalWrite(D9, addressC);
digitalWrite(D8, addressD);
return analogRead(pin);
}
void espNow(){ // Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK)
{
Serial.println("Error initializing ESP-NOW");
return;
}
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK)
{
Serial.println("Failed to add peer");
return;
}}