Code: Select all
/////////////ESPNOW
#include <esp_now.h>
#include <WiFi.h>
uint8_t broadcastAddress1[] = {0x94, 0xB9, 0x7E, 0xD4, 0x50, 0xAC};//address of sender
typedef struct Send_Data_Format { //format of the information to be sent
int x;
int y;
} Send_Data_Format;
Send_Data_Format example;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { //callback when data is sent
//char macStr[18];//Serial.print("Packet to: ");snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);Serial.print(macStr);Serial.print(" send status:\t");Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
esp_now_peer_info_t peerInfo; //needed here instead of in setup due to bug
/////////////ESPNOW
///setup pin inputs for joystick and setup variables.
const int SW_pin = 32;
const int X_pin = 25;
const int Y_pin = 33;
volatile int Xmap = 0;
volatile int Ymap = 0;
void setup() {
//joystick pins
pinMode(SW_pin, INPUT);
pinMode(X_pin, INPUT);
pinMode(Y_pin, INPUT);
digitalWrite(SW_pin, HIGH);
Serial.begin(115200);//serial connection
/////////////ESPNOW setup stage
//COMMENTING OUT THIS PART MAKES THE X AXIS READ OKAY AGAIN?!
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
//Serial.println("Error initialising ESPNOW");
return;
}
esp_now_register_send_cb(OnDataSent);
peerInfo.channel = 0;
peerInfo.encrypt = false;
memcpy(peerInfo.peer_addr, broadcastAddress1, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
//Serial.println("Failed to add peer");
return;
}
//delay(1000);
/////// END
/////////////ESPNOW setup stage
}
int newdata = 0;
int lastY = 0;
void loop() {
joystickoutput();
if (lastY!=Ymap){
/////////////ESPNOW loop stage
example.x = Xmap;
example.y = Ymap;
esp_err_t result = esp_now_send(0, (uint8_t *) &example, sizeof(Send_Data_Format));
/////////////ESPNOW loop stage
}
lastY=Ymap;
delay(10);
}
void joystickoutput() {
if (analogRead(X_pin) <= 1790) {
Xmap = map(analogRead(X_pin), 0, 1790, -100, 0);
}
if (analogRead(X_pin) >= 1800) {
Xmap = map(analogRead(X_pin), 1800, 4095, 0, 100);
}
if (analogRead(Y_pin) <= 1825) {
Ymap = map(analogRead(Y_pin), 0, 1825, -100, 0);
}
if (analogRead(Y_pin) >= 1835) {
Ymap = map(analogRead(Y_pin), 1835, 4095, 0, 100);
}
Serial.print("Switch: ");
Serial.print(digitalRead(SW_pin));
Serial.print("\n");
Serial.print("X-Axis: ");
Serial.print(Xmap);
Serial.print("\n");
Serial.print("Y-Axis: ");
Serial.print(Ymap);
Serial.print("\n");
}