Функция отображения байта вместо значения
Я не уверен, что понимаю все, что делаю, но вот моя проблема:
Я использую ESP-NOW между двумя ESP32s.
Вот код первого ESP:
#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_now.h>
const byte led_gpio = 32;
const int PushButton = 33;
// Set your new MAC Address
//uint8_t newMACAddress[] = {0x32, 0xAE, 0xA4, 0x07, 0x0D, 0x01};
uint8_t newMACAddress[] = {0x00, 0x00, 0x00, 0x00, 0x99, 0x01};
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0x00, 0x00, 0x00, 0x00, 0x99, 0x02};
// the setup function runs once when you press reset or power the board
// Variable to store if sending data was successful
String success;
// Define variables to store data readings to be sent
float LightColour;
bool Working;
// Define variables to store incoming readings
float incomingLightColour;
bool incomingWorking;
// Structure example to send data
// Must match the receiver structure
typedef struct struct_message {
float LC;
bool WOR;
} struct_message;
// Create a struct_message called InfoReadings to hold sensor readings
struct_message infoReadings;
// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
if (status == 0) {
success = "Delivery Success :)";
} else {
success = "Delivery Fail :(";
}
}
// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
Serial.print("Bytes received: ");
Serial.println(len);
incomingLightColour = incomingReadings.LC;
incomingWorking = incomingReadings.WOR;
}
void setup() {
Serial.begin(115200);
// initialize digital pin LED_BUILTIN as an output.
pinMode(led_gpio, OUTPUT);
pinMode(PushButton, INPUT);
WiFi.mode(WIFI_STA);
// 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 Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
esp_now_peer_info_t peerInfo;
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;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
Serial.print("[OLD] ESP32 Board MAC Address: ");
Serial.println(WiFi.macAddress());
esp_wifi_set_mac(ESP_IF_WIFI_STA, &newMACAddress[0]);
Serial.print("[NEW] ESP32 Board MAC Address: ");
Serial.println(WiFi.macAddress());
}
// the loop function runs over and over again forever
void loop() {
LightColour = 0;
Working = 0;
// Display Readings in Serial Monitor
Serial.println("INCOMING READINGS");
Serial.print("Light Colour: ");
Serial.print(incomingReadings.LC);
Serial.print("Working: ");
Serial.print(incomingReadings.WOR);
Serial.println();
int Push_button_state = digitalRead(PushButton);
if (Push_button_state == HIGH) {
digitalWrite(led_gpio, HIGH); // turn the LED on (HIGH is the voltage level)
LightColour = 100;
Working = 1;
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &infoReadings, sizeof(infoReadings));
if (result == ESP_OK) {
Serial.println("Sent with success");
} else {
Serial.println("Error sending the data");
}
} else {
digitalWrite(led_gpio, LOW); // turn the LED off by making the voltage LOW
} // wait for a second
}
А вот код второго ЭСП:
#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_now.h>
const byte led_gpio = 32;
const int PushButton = 33;
// Set your new MAC Address
//uint8_t newMACAddress[] = {0x32, 0xAE, 0xA4, 0x07, 0x0D, 0x01};
uint8_t newMACAddress[] = {0x00, 0x00, 0x00, 0x00, 0x99, 0x02};
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0x00, 0x00, 0x00, 0x00, 0x99, 0x01};
// the setup function runs once when you press reset or power the board
// Variable to store if sending data was successful
String success;
// Define variables to store data readings to be sent
float LightColour;
bool Working;
// Define variables to store incoming readings
float incomingLightColour;
bool incomingWorking;
//Structure example to send data
//Must match the receiver structure
typedef struct struct_message {
float LC;
bool WOR;
} struct_message;
// Create a struct_message called InfoReadings to hold sensor readings
struct_message infoReadings;
// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
if (status == 0) {
success = "Delivery Success :)";
} else {
success = "Delivery Fail :(";
}
}
// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
Serial.print("Bytes received: ");
Serial.println(len);
incomingLightColour = incomingReadings.LC;
incomingWorking = incomingReadings.WOR;
// Display Readings in Serial Monitor
Serial.println("INCOMING READINGS");
Serial.print("Light Colour: ");
Serial.print(incomingReadings.LC);
Serial.print("Working: ");
Serial.print(incomingReadings.WOR);
Serial.println();
}
void setup() {
Serial.begin(115200);
// initialize digital pin LED_BUILTIN as an output.
pinMode(led_gpio, OUTPUT);
pinMode(PushButton, INPUT);
WiFi.mode(WIFI_STA);
// 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 Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
esp_now_peer_info_t peerInfo;
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;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
Serial.print("[OLD] ESP32 Board MAC Address: ");
Serial.println(WiFi.macAddress());
esp_wifi_set_mac(ESP_IF_WIFI_STA, &newMACAddress[0]);
Serial.print("[NEW] ESP32 Board MAC Address: ");
Serial.println(WiFi.macAddress());
}
// the loop function runs over and over again forever
void loop() {
int Push_button_state = digitalRead(PushButton);
if (Push_button_state == HIGH) {
digitalWrite(led_gpio, HIGH); // turn the LED on (HIGH is the voltage level)
} else {
digitalWrite(led_gpio, LOW); // turn the LED off by making the voltage LOW
} // wait for a second
}
Моя цель довольно проста. Когда я нажимаю кнопку; Я хочу, чтобы информация была отправлена, что LightColour = 100
и Рабочий = 1
.
Это тестовая программа для того, чтобы понять, что происходит.
Но в последовательном мониторе приемного устройства вот что у меня есть:
Bytes received: 8
INCOMING READINGS
Light Colour: 0.00
Working: 0
Это означает, что следующая часть кода работает неправильно:
incomingLightColour = incomingReadings.LC;
incomingWorking = incomingReadings.WOR;
Но количество полученных байт, кажется, в порядке?
@vib, 👍0
Обсуждение1 ответ
▲ 0
это было глупо Я забыл добавить:
infoReadings.LC = LightColour;
infoReadings.WOR = Working;
Сейчас все работает
,
@vib
было бы лучше удалить этот вопрос, @Juraj
Смотрите также:
- esp32 Stack canary watchpoint срабатывает
- ESP32S v1.1 NodeMCU vs ESP32 DevKitV1
- esp32-cam публикует изображение в mqtt
- WindowsError(31, "Устройство, подключенное к системе, не функционирует") в arduino
- Как очистить кучу памяти в esp32
- ESP-NOW и Wi-Fi, и OTA одновременно на Отправителе и Получателе
- PN532 не обнаруживает RFID-карту при подключении к ESP32 в режиме I2C, но отлично работает с Arduino Uno
- AsyncWebServer дает сброс wdt
где вы устанавливаете значения для "infoReadings"?, @Juraj