esp32s3-ch390-udp-discovery-10.ino

Olimex UEXT-CH390: SPI to Ethernet 10/100 Mbps Module for Microcontrollers · File : esp32s3-ch390-udp-discovery-10.ino · Language : C/C++ (ESP-IDF) · Use case : Diffuser des paquets UDP pour la découverte du réseau local.

Periodically sends a UDP broadcast message via CH390 to announce device presence on the network.

Uses esp-netif and lwIP. Requires a CH390 driver implementation for ESP-IDF. Verify GPIO numbers based on your UEXT wiring on the ESP32-S3.

esp32s3-ch390-udp-discovery-10.ino

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "lwip/sockets.h"
#include "sdkconfig.h"

#include "driver/spi_master.h"
#include "ch390.h" // Bibliothèque supposée pour le CH390

static const char *TAG = "CH390_UDP";
#define UDP_PORT 12345
#define DISCOVERY_MESSAGE "UXTCH390_DEVICE_FOUND\n"

void udp_discovery_task(void *pvParameters) {
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock < 0) {
        ESP_LOGE(TAG, "Socket creation failed");
        vTaskDelete(NULL);
        return;
    }

    struct sockaddr_in dest_info;
    memset(&dest_info, 0, sizeof(dest_info));
    dest_info.sin_family = AF_INET;
    dest_info.sin_port = htons(UDP_PORT);
    dest_info.sin_addr.s_addr = inet_addr("255.255.255.255"); // Broadcast

    while (1) {
        int ret = sendto(sock, DISCOVERY_MESSAGE, strlen(DISCOVERY_MESSAGE), 0, 
                         (struct sockaddr*)&dest_info, sizeof(struct sockaddr_in));
        if (ret < 0) {
            ESP_LOGE(TAG, "Sendto failed with errno %d", errno);
        } else {
            ESP_LOGI(TAG, "Broadcast sent: %s", DISCOVERY_MESSAGE);
        }
        vTaskDelay(pdMS_TO_TICKS(5000)); // Envoyer toutes les 5 secondes
    }
}

void app_main(void) {
    ESP_LOGI(TAG, "Initializing SPI for CH390...");
    // Configuration SPI spécifique à l'ESP32-S3 et au module CH390
    // Exemple générique :
    spi_host_device_t spi_host = SPI2_HOST;
    spi_device_handle_t spi_handle;
    ch390_config_t ch390_cfg = {
        .cs_io = GPIO_NUM_10,
        .sck_io = GPIO_NUM_12,
        .mosi_io = GPIO_NUM_11,
        .miso_io = GPIO_NUM_13,
        .rst_io = GPIO_NUM_14,
        .max_freq_hz = 20000000,
    };
    
    esp_err_t ret = ch390_init(spi_host, &ch390_cfg, &spi_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "CH390 Init failed: %s", esp_err_to_name(ret));
        return;
    }

    esp_netif_t *eth_netif = esp_eth_new_netif(&eth); // Nécessite installation du pilote eth
    esp_netif_ip_info_t ip_info;
    esp_netif_get_ip_info(eth_netif, &ip_info);
    ESP_LOGI(TAG, "IP: " IPSTR, IP2STR(&ip_info.ip));

    xTaskCreate(udp_discovery_task, "udp_disc", 2048, NULL, 5, NULL);
}

← Back to the board