add espnow

This commit is contained in:
interfisch 2024-10-27 18:18:42 +01:00
commit af0fc0e114
17 changed files with 430 additions and 12 deletions

5
controller/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

10
controller/.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

View file

@ -18,11 +18,12 @@ monitor_speed = 115200
build_flags =
-D ID=0 ;0=black box first print, 1=black print new design, 2=white cardboard
-D ID=1 ;0=black box first print, 1=black print new design, 2=white cardboard
-D PIN_LEFT=D5
-D PIN_RIGHT=D6
-D PIN_UP=D2 ;SDA
-D PIN_DOWN=D1 ;SCL
-D PIN_A=D4 ;D3 GPIO 0, wakes esp from deepsleep when pulled down
-D PIN_B=D3 ;D3 GPIO 0, prevents boot when pulled down
'-D RECEIVERMAC={0x24, 0x58, 0x7C, 0xCE, 0xFA, 0xDC}'
-D CHANNEL=1 ;only channel 1 works

View file

@ -1,10 +1,27 @@
#include <Arduino.h>
#define ESPNOW
//#define UDP
#ifdef UDP
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#endif
#ifdef ESPNOW
#include <ESP8266WiFi.h>
#include <espnow.h>
#endif
// REPLACE WITH YOUR RECEIVER MAC Address
uint8_t broadcastAddress[] = RECEIVERMAC;
#ifdef UDP
const char* ssid = "network";
const char* password = "password";
WiFiUDP Udp;
unsigned int localUdpPort = 4210; // local port to listen on
char incomingPacket[255]; // buffer for incoming packets
@ -12,6 +29,22 @@ char incomingPacket[255]; // buffer for incoming packets
unsigned int remoteUDPPort = 5005;
IPAddress remoteIP = IPAddress(192,168,1,221);
#endif
#ifdef ESPNOW
// callback when data is sent
void OnDataSent(uint8_t *mac_addr, uint8_t sendStatus) {
Serial.print("Last Packet Send Status: ");
if (sendStatus == 0){
Serial.println("Delivery success");
}
else{
Serial.println("Delivery fail");
}
}
#endif
bool flag_init_send;
@ -34,14 +67,6 @@ enum Input {
KEY_B=5
};
uint8_t input_pins[] = {PIN_LEFT,PIN_RIGHT,PIN_UP,PIN_DOWN,PIN_A,PIN_B};
bool sent_states[INPUT_SIZE];
bool input_states[INPUT_SIZE];
unsigned long last_send_state[INPUT_SIZE];
#define DEBOUNCE_TIME 50
typedef struct struct_message {
uint8_t id;
@ -49,8 +74,16 @@ typedef struct struct_message {
Input input;
} struct_message;
struct_message myData;
uint8_t input_pins[] = {PIN_LEFT,PIN_RIGHT,PIN_UP,PIN_DOWN,PIN_A,PIN_B};
bool sent_states[INPUT_SIZE];
bool input_states[INPUT_SIZE];
unsigned long last_send_state[INPUT_SIZE];
#define DEBOUNCE_TIME 50
bool flag_send=false;
@ -69,6 +102,37 @@ void setup()
myData.action=HELLO;
myData.input=KEY_LEFT; //does not matter
#ifdef ESPNOW
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
Serial.print("WiFi-Channel Default: ");
Serial.println(WiFi.channel());
wifi_promiscuous_enable(true);
wifi_set_channel(CHANNEL);
wifi_promiscuous_enable(false);
Serial.print("WiFi Channel Update : ");
Serial.println(WiFi.channel());
// Init ESP-NOW
if (esp_now_init() != 0) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_register_send_cb(OnDataSent);
// Register peer
esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0);
#endif
#ifdef UDP
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
@ -77,10 +141,12 @@ void setup()
Serial.print(".");
}
Serial.println(" connected");
flag_init_send=true;
Udp.begin(localUdpPort);
Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
#endif
flag_init_send=true;
}
@ -88,6 +154,7 @@ void loop()
{
unsigned long loopmillis=millis();
#ifdef UDP
int packetSize = Udp.parsePacket();
if (packetSize)
{
@ -101,6 +168,7 @@ void loop()
Serial.printf("UDP packet contents: %s\n", incomingPacket);
}
#endif
for (uint8_t i=0;i<INPUT_SIZE;i++)
{
@ -141,6 +209,7 @@ void loop()
if (flag_send) {
flag_send=false;
#ifdef UDP
Udp.beginPacket(remoteIP, remoteUDPPort);
char packet[3];
@ -159,5 +228,17 @@ void loop()
Udp.write(packet,sizeof(packet));
Udp.endPacket();
#endif
#ifdef ESPNOW
if (myData.action==PRESS){
sent_states[myData.input]=true;
}else if (myData.action==RELEASE){
sent_states[myData.input]=false;
}
esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
Serial.printf("sending");
#endif
}
}

5
receiver/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

10
receiver/.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

39
receiver/include/README Normal file
View file

@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

46
receiver/lib/README Normal file
View file

@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

29
receiver/platformio.ini Normal file
View file

@ -0,0 +1,29 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32]
platform = platformio/espressif32@^6.7
board = esp32-s3-devkitm-1
;Devboard is ESP32-S3-DevKitC-1 (N16R8). board=esp32-s3-devkitm-1 works fine
framework = arduino
monitor_port= /dev/ttyACM0
monitor_speed = 115200
upload_speed = 921600
lib_deps =
adafruit/Adafruit NeoPixel@^1.12.3
build_flags =
-D PIXELPIN=4
-D NUMPIXELS=600
-D CHANNEL=1

69
receiver/src/espnow.cpp Normal file
View file

@ -0,0 +1,69 @@
#include "espnow.h"
//Mac Adress Receiver: 24:58:7c:ce:fa:dc
// Create a struct_message
struct_message espnowdata;
void readMacAddress(){
uint8_t baseMac[6];
esp_err_t ret = esp_wifi_get_mac(WIFI_IF_STA, baseMac);
if (ret == ESP_OK) {
Serial.printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
baseMac[0], baseMac[1], baseMac[2],
baseMac[3], baseMac[4], baseMac[5]);
} else {
Serial.println("Failed to read MAC address");
}
}
void initESPNOW() {
WiFi.mode(WIFI_STA);
Serial.print("WiFi-Channel Default: ");
Serial.println(WiFi.channel());
esp_wifi_set_promiscuous(true);
esp_wifi_set_channel(CHANNEL, WIFI_SECOND_CHAN_NONE);
esp_wifi_set_promiscuous(false);
Serial.print("WiFi-Channel Update : ");
Serial.println(WiFi.channel());
//WiFi.begin();
Serial.print("[DEFAULT] ESP32 Board MAC Address: ");
readMacAddress();
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info
esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv));
}
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&espnowdata, incomingData, sizeof(espnowdata));
Serial.print("Bytes received: ");
Serial.println(len);
statuspixel.setPixelColor(0, statuspixel.Color((millis()%3==0)*255,(millis()%3==1)*255,(millis()%3==2)*255)); //change status led when packet arrives
statuspixel.show();
processCommand(espnowdata);
Serial.println();
}

53
receiver/src/espnow.h Normal file
View file

@ -0,0 +1,53 @@
#ifndef espnow_h
#define espnow_h
#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_now.h>
#include <Adafruit_NeoPixel.h>
extern Adafruit_NeoPixel statuspixel;
// Must match the receiver structure
enum Action {
HELLO=0,
PRESS=1,
RELEASE=2,
DOWN=3,
UP=4
};
#define INPUT_SIZE 6
enum Input {
KEY_LEFT=0,
KEY_RIGHT=1,
KEY_UP=2,
KEY_DOWN=3,
KEY_A=4,
KEY_B=5
};
typedef struct struct_message {
uint8_t id;
Action action;
Input input;
} struct_message;
extern void processCommand(struct_message espnowdata);
void readMacAddress();
void initESPNOW();
// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len);
#endif

70
receiver/src/main.cpp Normal file
View file

@ -0,0 +1,70 @@
#include <Arduino.h>
#include "espnow.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#ifdef PIN_NEOPIXEL
Adafruit_NeoPixel statuspixel(1, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800);
#endif
void setup() {
Serial.begin(115200);
initESPNOW();
#if defined(NEOPIXEL_POWER)
// If this board has a power control pin, we must set it to output and high
// in order to enable the NeoPixels. We put this in an #if defined so it can
// be reused for other boards without compilation errors
pinMode(NEOPIXEL_POWER, OUTPUT);
digitalWrite(NEOPIXEL_POWER, HIGH);
#endif
#ifdef PIN_NEOPIXEL
statuspixel.begin();
statuspixel.setBrightness(100); // not so bright
statuspixel.clear();
//Flash colors for debug
statuspixel.setPixelColor(0, statuspixel.Color(255, 0,0));
statuspixel.show();
delay(250);
statuspixel.setPixelColor(0, statuspixel.Color(0, 255,0));
statuspixel.show();
delay(250);
statuspixel.setPixelColor(0, statuspixel.Color(0, 0,255));
statuspixel.show();
delay(250);
statuspixel.clear();
statuspixel.show();
#endif
Serial.println("Started");
}
void loop() {
unsigned long loopmillis=millis();
}
void processCommand(struct_message espnowdata) { //espnow data from remote
Serial.println(millis());
Serial.print("ID="); Serial.println(espnowdata.id);
Serial.print("Action="); Serial.println(espnowdata.action);
Serial.print("Input="); Serial.println(espnowdata.input);
Serial.println();
}