#define ETH_PHY_ADDR 0
#define ETH_PHY_RST_GPIO GPIO_NUM_17
#define ETH_PHY_POWER_GPIO GPIO_NUM_2
#define ETH_PHY_MDIO_GPIO GPIO_NUM_18
#define ETH_PHY_MDC_GPIO GPIO_NUM_23
esp_err_t Ethernet::init() {
esp_err_t err;
// Turn on LAN8720
gpio_set_direction(ETH_PHY_POWER_GPIO, GPIO_MODE_OUTPUT);
gpio_set_level(ETH_PHY_POWER_GPIO, 1);
// Initialize the EMAC
eth_esp32_emac_config_t config = ETH_ESP32_EMAC_DEFAULT_CONFIG();
config.smi_mdc_gpio_num = ETH_PHY_MDC_GPIO;
config.smi_mdio_gpio_num = ETH_PHY_MDIO_GPIO;
config.clock_config = {
.rmii = {.clock_mode = EMAC_CLK_EXT_IN, .clock_gpio = EMAC_CLK_IN_GPIO}};
// Initialize the MAC and PHY
eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
phy_config.phy_addr = ETH_PHY_ADDR;
phy_config.reset_gpio_num = ETH_PHY_RST_GPIO;
mac = esp_eth_mac_new_esp32(&config, &mac_config);
phy = esp_eth_phy_new_lan87xx(&phy_config);
// Install the driver
esp_eth_handle_t eth_handle = NULL;
esp_eth_config_t eth_conf = ETH_DEFAULT_CONFIG(mac, phy);
err = esp_eth_driver_install(ð_conf, ð_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Ethernet driver installation failure: %s",
esp_err_to_name(err));
return err;
}
// Initialize TCP/IP network interface
err = esp_netif_init();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Network Interface initialization failure: %s",
esp_err_to_name(err));
return err;
}
err = esp_event_loop_create_default();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Event loop creation failure: %s", esp_err_to_name(err));
return err;
}
esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_ETH();
esp_netif_t* eth_netif = esp_netif_new(&netif_config);
err = esp_netif_attach(eth_netif, esp_eth_new_netif_glue(eth_handle));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Network Interface attachment failure: %s",
esp_err_to_name(err));
return err;
}
// Register event handlers
err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &on_eth_event,
NULL);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Ethernet event handler registration failure: %s",
esp_err_to_name(err));
return err;
}
err = esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &on_got_ip,
NULL);
if (err != ESP_OK) {
ESP_LOGE(TAG, "IP event handler registration failure: %s",
esp_err_to_name(err));
return err;
}
// Start the Ethernet driver
err = esp_eth_start(eth_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Ethernet start failure: %s", esp_err_to_name(err));
return err;
}
return ESP_OK;
}