카테고리 보관물: 하드웨어

RP2350의 HSTX와 PSRAM의 상성에 대한 실무 경험 정리 다시 한번 더 해봅니다

RP2040에서 HDMI 출력을 하는 것을 상태기계로 구현하는 것이 시도되었습니다. 칩설계자가 만든 PicoDVI에서 이런 작업을 했는데요. 두개의 코어를 95% 이상 부려내서 겨우 출력을 했는데, 이로부터 HDMI 출력을 안정적으로 MCU와 분리해서 처리해주는 체제가 필요하다고 요청이 되어 HSTX 핀을 RP2350에서는 기본 제공을 합니다.

이 HSTX 핀에다가 DVI/HDMI 브레이크아웃 보드를 연결하면 HDMI LCD 모니터에 출력이 되는데요.

640×480@60Hz는 프레임버퍼 크기가 600KB에 근접해서, RP2350의 SRAM이 520KB 정도라 안됩니다. 그래서 다들 발상하는게, PSRAM이 달린 RP2350 보드를 쓴다는 것이고 저도 해보았습니다.

그런데 RP2350에서 HDMI 출력을 하게 해주는 HSTX는 PSRAM의 블랭킹 구간의 매커니즘과 충돌합니다. AHB-Lite 버스 문제인지, LVGL UI가 복잡해지면 707KB를 처리해야 할때, 12KB 정도만 보내는게 하드웨어 제약에 의해 있는 현상이라, UI 표시가 안됩니다.

블랭킹 구간은 화면이 안그려지는 짧은 순간인데, Pimoroni Pico Plus 2의 경우 프레임당 1.43ms라, 640×480@60Hz 표시에 필요한 대역폭에 턱없이 모자릅니다.

PSRAM을 안쓰고 SRAM을 쓰면 HSTX와 경합이 크게 없는데요. 그러나 SRAM이 520KB밖에 안되서 640×480@60Hz보다 320×240@60Hz로 하고, RGB565로 표시시 320×240을 쏘아서 640×480으로 뻥튀기해서 표시하는 것이 최적입니다. 이경우

• HSTX와 PSRAM이 동시에 쓰면 대역폭 문제 발생
• SRAM으로 하면 해결되지만 520KB의 적은 용량이라 해상도 뻥튀기 필요
• FHD LCD 모니터의  CTA/CEA VESA 표준 준수 여부에 의해 해상도가 제한적이 됨

이 조건들로 인해 HSTX와 PSRAM을 동시에 쓰는게 이그러집니다.

PSRAM을 반드시 써야 한다면,

• HSTX를 안쓰는 인터페이스의 디스플레이
• 8080 파라렐 방식으로 된 디스플레이 중에 GRAM이 있으면 좋다

이 조건이어야 하네요.

전문 용어와 알파벳이 밀도높게 쓰였는데 이해에 어려움이 없으시죠?

이 문제는 PicoDVI와 Adafruit의 프로젝트 라이브러리 주석에도 나온 문제점이라고 인공지능이 찾아서 보고해주네요. RP2350이 HSTX를 제공해도 현실적 한계가 되는 부분입니다.

그래서 굳이 디스플레이 표시용으로 PSRAM을 쓰기보다, SRAM으로 된 보드를 구해서 쓰는게 좋을 수 있고,

• 320x240 RGB565로 표시후 가로 방향으로 소프트웨어적인 보간 실행 또는
• 640x480 RGB332로 표시

이 두가지가 최선 같습니다.

RP2350 후속칩이 나오면 어떻게 달라질지 기대가 되네요.

라즈베리파이 피코와 PCM5101A로 오디오 재생하기 프로젝트

라즈베리파이 피코는 Cortex-M0+ 듀얼코어를 장착한 MCU 개발보드로 264KB의 램을 제공합니다. 피코에 PCM5101A를 장착하면 PCM 신호를 보내 고음질의 음악을 연주할 수 있습니다. MP3는 따로 PCM으로 변환해야 하고, 인터페이스는 I2S여야 합니다.

라즈베리파이 피코는 I2S 핀을 따로 제공하지 않으므로 PIO 상태기계를 활용해서 I2S를 에뮬레이션해야 하구요. 마침 라즈베리파이 재단에서 제공하는 pico-extras 프로젝트 하위 프로젝트인 pico_audio_i2s를 활용하면 기정의된 PIO로 만들어진 C 라이브러리가 있어 편리하게 쓰는게 가능해집니다.

하드웨어 설비를 간편하게 하기 위한 최소 설비입니다:

라즈베리파이 피코 한대
Waveshare Pico-Audio rev.1
Wavashare expander quad
SPI microSD 카드 모듈
FAT32로 포맷된 microSD 카드
micro-USB 케이블 두개

이중에서 expander quad라고 된 제품은 일종의 확장보드 성격의 작은 보드로 4개의 모듈을 핀을 직접 연결하지 않고도 쓰게 되어 있는 쉴드입니다. 특별히 좋은 것은 3V3 핀을 4개로 나누어서 전원 공급이 되게 해주니 좋습니다.

일반 설비를 잘 하고나서 프로젝트를 만듭니다.

아래와 같은 명령어를 씁니다.

# cd ~
user# git clone https://github.com/raspberrypi/pico-sdk
user# cd pico-sdk
user/pico-sdk# git submodule update --init --recursive
user/pico-sdk# cd ~
user# git clone https://github.com/raspberrypi/pico-extras
user# cd pico-extras
user/pico-extras# git submodule update --init -recursive
user/pico-extras# cd ~
user# git clone https://github.com/raspberrypi/pico-playground
user# cd pico-playground
user/pico-playground# git submodule update --init --recursive
user/pico-playground# cd ~
user# git clone https://github.com/raspberrypi/pico-examples
user# cd pico-extras
user/pico-examples# git submodule update --init -recursive
user# mkdir pico-audio
user# cd pico-audio
user/pico-audio# git clone https://github.com/elehobica/pico_fatfs.git

이런 명령어로 피코 C SDK와 하위 예제 프로젝트를 받아오고 환경변수를 등록합니다. 그리고 프로젝트 디렉토리를 하나 만들어서 pico_fatfs를 받아오고 거기서 작업합니다.

제일 중요한 것이 pico_audio_i2s를 쓰는 방법입니다.

이 하위 프로젝트에는 PIOASM이 정의된 파일이 포함되어 있고, I2S를 작동시킬때 필요한 C 코드들이 쓸만하게 정의되어 있습니다. PIOASM은 아래와 같습니다.

.program audio_i2s
.side_set 2

                    ;        /--- LRCLK
                    ;        |/-- BCLK
bitloop1:           ;        ||
    out pins, 1       side 0b10
    jmp x-- bitloop1  side 0b11
    out pins, 1       side 0b00
    set x, 14         side 0b01

bitloop0:
    out pins, 1       side 0b00
    jmp x-- bitloop0  side 0b01
    out pins, 1       side 0b10
public entry_point:
    set x, 14         side 0b11

.program audio_i2s_swapped
.side_set 2

                    ;        /--- BCLK
                    ;        |/-- LRCLK
bitloop1:           ;        ||
    out pins, 1       side 0b01
    jmp x-- bitloop1  side 0b11
    out pins, 1       side 0b00
    set x, 14         side 0b10

bitloop0:                      
    out pins, 1       side 0b00
    jmp x-- bitloop0  side 0b10
    out pins, 1       side 0b01
public entry_point:            
    set x, 14         side 0b11

% c-sdk {

static inline void audio_i2s_program_init(PIO pio, uint sm, uint offset, uint data_pin, uint clock_pin_base) {
    pio_sm_config sm_config = audio_i2s_program_get_default_config(offset);

    sm_config_set_out_pins(&sm_config, data_pin, 1);
    sm_config_set_sideset_pins(&sm_config, clock_pin_base);
    sm_config_set_out_shift(&sm_config, false, true, 32);
    sm_config_set_fifo_join(&sm_config, PIO_FIFO_JOIN_TX);

    pio_sm_init(pio, sm, offset, &sm_config);

#if PICO_PIO_USE_GPIO_BASE
    uint64_t pin_mask = (1ull << data_pin) | (3ull << clock_pin_base);
    pio_sm_set_pindirs_with_mask64(pio, sm, pin_mask, pin_mask);
#else
    uint32_t pin_mask = (1u << data_pin) | (3u << clock_pin_base);
    pio_sm_set_pindirs_with_mask(pio, sm, pin_mask, pin_mask);
#endif
    pio_sm_set_pins(pio, sm, 0); // clear pins

    pio_sm_exec(pio, sm, pio_encode_jmp(offset + audio_i2s_offset_entry_point));
}

%}

보시듯이 I2S에 대응되는 통신을 위해 핀을 할당하고 신호 타이밍에 맞추어 데이터를 보내게 되어 있는 구조입니다. 특별히 어려울 코드는 없으며 각각 DIN과 BCK에 대응되는 data_pin과 clock_pin을 지정하면 되는데요. LRCK는 clock_pin 바로 다음 핀으로 자동으로 잡합니다. MCLK는 따로 핀이 바깥으로 빠져나온 모듈이면 GND에 꽂으면 되는데요. Pico-Audio rev.1은 MCLK가 따로 핀으로 없고, BCK로부터 나온 클럭을 내부 PLL로 가공해서 자동으로 신호 타이밍을 맞추어주니 큰 신경을 쓸 필요가 없어집니다.

Pico-Audio 위키페이지에 가보면 아래와 같은 핀을 쓰라고 되어 있습니다.

#define I2S_DATA_PIN 26
#define I2S_BCLK_PIN 27
#define I2S_LRCK_PIN 28

이는 C 코드에서 잘 지정해주면 expander quad에서 알아서 신호를 보내주니 잘 지정해두기만 하면 됩니다.

I2S 설비가 다 되었으면 이번에는 pico_audio_i2s의 사용법을 살펴보는 것이 할 일입니다. pico_audio_i2s는 아래 단계를 거쳐서 초기화하고 재생을 합니다.

• 3개의 PIO 중에 하나를 골라 설정
• DMA로 하나를 골라 설정
• I2S 구조체, 오디오 형식 구조체, 오디오 버퍼 구조체를 설정하고
• 프로듀서, 컨슈머 풀 가동
• microSD 카드에서 WAV 파일 읽어오기
• 읽어온 내용을 버퍼에 보내서 재생

이 과정을 거칩니다.

PIO 설정과 DMA 설정, 프로듀서, 컨슈머 풀 가동은 아래와 같은 형식으로 합니다.

#define SAMPLE_RATE 44100
#define BUFFER_SAMPLES 1024

#define I2S_DATA_PIN 26
#define I2S_BCLK_PIN 27
#define I2S_LRCK_PIN 28

int audio_sm = pio_claim_unused_sm(pio0, true); // 사용안하고 있는 상태기계 자동 선택
int audio_dma = dma_claim_unused_channel(true); // 사용안하고 있는 DMA 채널 자동 선택
pio_sm_unclaim(pio0, audio_sm); // 옵셔널: 위 코드가 작동안하면 즉시 해제 (경합이 일어날 수 있으니 위 두코드가 안될때만 가동)
dma_channel_unclaim(audio_dma); // 옵셔널: 위와 같음

// I2S 설비 정보
struct audio_i2s_config i2s_config = {
    .data_pin = I2S_DATA_PIN,
    .clock_pin_base = I2S_BCLK_PIN,
    .dma_channel = audio_dma,
    .pio_sm = audio_sm,
};

// 재생할 WAV 파일 사양과 일치하게 설정
struct audio_format audio_format = {
    .format = AUDIO_BUFFER_FORMAT_PCM_S16,
    .sample_freq = SAMPLE_RATE,
    .channel_count = 2,
};

// 16비트 signed WAV의 경우 sample_stride를 4 추천
struct audio_buffer_format producer_format = {
    .format = &audio_format,
    .sample_stride = 4
};

// 프로듀서, 컨슈머 풀 구성
struct audio_buffer_pool *producer_pool = audio_new_producer_pool(&producer_format, 3, BUFFER_SAMPLES);
if (!producer_pool) {
    printf("[Core 1] FATAL: Failed to create audio pool\n"); // 로그 추가
    panic("Failed to create audio pool");
}

// 설정한대로 pico_audio_i2s 시동 준비 완료
audio_i2s_setup(&audio_format, &i2s_config);
audio_i2s_connect(producer_pool);
audio_i2s_set_enabled(true);

이렇게 해두고 FatFS으로 파일을 읽어오는 코드와 연동합니다.

대략 좋은 위치에

#define SPI_PORT spi1
#define PIN_MISO 12   // GPIO12 = SPI1_RX  (SD카드 MISO → Pico 입력)
#define PIN_MOSI 11   // GPIO11 = SPI1_TX  (SD카드 MOSI ← Pico 출력)
#define PIN_SCK  10   // GPIO10 = SPI1_SCK
#define PIN_CS   13

#define WAV_FILENAME "bgm1.wav"
#define WAV_HEADER_SIZE 44

printf("[Core 0] Configuring SPI for SD Card...\n");
pico_fatfs_spi_config_t spi_config = {
    SPI_PORT, 400000, 15000000,
    PIN_MISO, PIN_CS, PIN_SCK, PIN_MOSI,
    true};  // MISO 내부 풀업 필수 (tf_card.c 주석: "pull up of MISO is MUST")
pico_fatfs_set_config(&spi_config);

FATFS fs;
printf("[Core 0] Attempting to mount SD Card...\n");
FRESULT mount_res = f_mount(&fs, "", 1);
if (mount_res != FR_OK)
{
    printf("[Core 0] FATAL: SD Card Mount Failed! FatFS Error Code: %d\n", mount_res);
    panic("SD Card Mount Failed\r\n");
}
printf("[Core 0] SUCCESS: SD Card Mounted.\n"); 

마운트가 잘 되어 있으면 아래와 같은 코드를 실행합니다.

while (true)
{
    FIL fil;
    printf("[Core 1] Attempting to open file: bgm1.wav\n"); // ⭐️ 로그 추가

    mutex_enter_blocking(&sd_card_mutex);
    FRESULT fr_open = f_open(&fil, "bgm1.wav", FA_READ);
    mutex_exit(&sd_card_mutex);

    if (fr_open != FR_OK) {
        printf("[Core 1] ERROR: Failed to open bgm1.wav! FatFS Error Code: %d\n", fr_open); // 실패 원인 파악
        sleep_ms(2000); // 실패 시 2초 대기 후 재시도
        continue;
    }
    printf("[Core 1] SUCCESS: File opened.\n"); // 로그 추가

    g_played_audio_bytes = 0;
    g_playback_finished = false;
    g_is_playing = true;
    g_file_change_request = false;

    struct audio_buffer *buffer = take_audio_buffer(producer_pool, true);
    if (buffer)
    {
        memset(buffer->buffer->bytes, 0, buffer->buffer->size);
        buffer->sample_count = buffer->max_sample_count;
        give_audio_buffer(producer_pool, buffer);
    }

    uint32_t loop_counter = 0; // 로그 출력 빈도 조절용 변수

    // 오디오 재생 무한 루프
    while (true)
    {
        buffer = take_audio_buffer(producer_pool, true);
        UINT bytes_read;

        mutex_enter_blocking(&sd_card_mutex);
        FRESULT fr = f_read(&fil, buffer->buffer->bytes, buffer->buffer->size, &bytes_read);
        mutex_exit(&sd_card_mutex);

        if (fr != FR_OK || bytes_read == 0)
        {
            printf("\n[Core 1] Playback finished or Read Error. FR: %d, Bytes read: %d\n", fr, bytes_read); // ⭐️ 로그 추가
            g_playback_finished = true;
            release_audio_buffer(producer_pool, buffer);
            printf("[Core 1] Closing file.\n");  
            f_close(&fil);
            break;
        }
        else
        {
            g_played_audio_bytes += bytes_read;
            buffer->sample_count = bytes_read / 4;
            give_audio_buffer(producer_pool, buffer);

            // 과도한 printf로 인한 끊김 방지: 버퍼 1000번 채울 때마다 한 번씩만 출력
            loop_counter++;
            if (loop_counter % 1000 == 0) {
                printf("[Core 1] Playing... (Played %d bytes)\n", g_played_audio_bytes);
            }
        }

        sleep_ms(1);
    }
}
audio_i2s_set_enabled(false);

요점은 f_open으로 WAV 파일을 열고, f_read로 WAV 파일을 포인터를 옮겨가면서 조금씩 읽어와서 take_audio_buffer와 give_audio_buffer로 pico_audio_i2s가 소비할 버퍼를 채운다는 것입니다. 재생할 버퍼가 다 소진되고 파일의 끝에 포인터가 가면 release_audio_buffer를 실행해서 버퍼를 비우고 파일을 닫습니다. 이 단계에서 안쪽 while 루프를 빠져나와 처음부터 같은 파일을 다시 연주합니다.

이를 응용하면 LVGL로 오디오 재생기 UI를 표시하고 각각의 UI 버튼을 누를때 적절한 기능을 실행되게 할수도 있습니다. 이 글에서는 일단 최소 코드만 보여봅니다.

STM32-H755ZI-Q 개발 보드에서 이더넷으로 DHCP 연결 수립후 IP 받아오는 설정

STM32-H755ZI-Q 개발 보드는 RJ45 커넥터와 LAN8742 PHY를 내장으로 지원합니다.

주요 사양은

• 데이터 레이트: 10/100Mbps
• 표준안: IEEE 802.3/802.3u (10BASE-T, 100BASE-TX)
• 인터페이스: RMII
• 전압: 1.6V ~ 3.3V (LVCMOS I/O) 1.2V 레귤레이터 통합
• 50MHz 클럭 소스

구요. 라우터가 왠만하면 요즘 나오는 제품은 지원을 합니다. (물론 10BASE-T와 100BASE-TX는 아주 오래전 규격인데, MP3나 WAV 스트리밍도 되는 사양일 것입니다.)

우선 연결도는 아래와 같구요

STM32 보드 === lwIP (DHCP client) === 라우터 (DHCP server)

우리가 해야 하는 것은 ETH를 켜는 것과, lwIP 옵션 지정입니다.

STM32CubeMX에서 하면 간편한데, 너무 길어지니 대략적인 요약문부터 올립니다.

(1) STM32CubeMX > Connectivity > ETH 켬
(2) STM32CubeMX > Middleware and Software Pack > LWIP 켬
(3) ethernetif.c 수정보완

이 세가지 큰 흐름을 기반으로 세부를 설정해주면 됩니다.

우선 STM32CubeMX 설정 화면은 생략하고 이로부터 생성된 소스코드를 어떻게 고쳐야 하는지 보이겠습니다.

Project Root > CM7 > LWIP > App > lwip.c :

/* USER CODE BEGIN Header */
/**
 ******************************************************************************
  * File Name          : LWIP.c
  * Description        : This file provides initialization code for LWIP
  *                      middleWare.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "lwip.h"
#include "lwip/init.h"
#include "lwip/netif.h"
#if defined ( __CC_ARM )  /* MDK ARM Compiler */
#include "lwip/sio.h"
#endif /* MDK ARM Compiler */
#include "ethernetif.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */
/* Private function prototypes -----------------------------------------------*/
static void ethernet_link_status_updated(struct netif *netif);
static void Ethernet_Link_Periodic_Handle(struct netif *netif);
/* ETH Variables initialization ----------------------------------------------*/
void Error_Handler(void);

/* DHCP Variables initialization ---------------------------------------------*/
uint32_t DHCPfineTimer = 0;
uint32_t DHCPcoarseTimer = 0;
/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
uint32_t EthernetLinkTimer;

/* Variables Initialization */
struct netif gnetif;
ip4_addr_t ipaddr;
ip4_addr_t netmask;
ip4_addr_t gw;

/* USER CODE BEGIN 2 */

/* USER CODE END 2 */

/**
  * LwIP initialization function
  */
void MX_LWIP_Init(void)
{
  /* Initialize the LwIP stack without RTOS */
  lwip_init();

  /* IP addresses initialization with DHCP (IPv4) */
  ipaddr.addr = 0;
  netmask.addr = 0;
  gw.addr = 0;

  /* add the network interface (IPv4/IPv6) without RTOS */
  netif_add(&gnetif, &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &ethernet_input);

  /* Registers the default network interface */
  netif_set_default(&gnetif);

  /* We must always bring the network interface up connection or not... */
  netif_set_up(&gnetif);

  /* Set the link callback function, this function is called on change of link status*/
  netif_set_link_callback(&gnetif, ethernet_link_status_updated);

  /* Start DHCP negotiation for a network interface (IPv4) */
  //dhcp_start(&gnetif);

/* USER CODE BEGIN 3 */

/* USER CODE END 3 */
}

#ifdef USE_OBSOLETE_USER_CODE_SECTION_4
/* Kept to help code migration. (See new 4_1, 4_2... sections) */
/* Avoid to use this user section which will become obsolete. */
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
#endif

/**
  * @brief  Ethernet Link periodic check
  * @param  netif
  * @retval None
  */
static void Ethernet_Link_Periodic_Handle(struct netif *netif)
{
/* USER CODE BEGIN 4_4_1 */
/* USER CODE END 4_4_1 */

  /* Ethernet Link every 100ms */
  if (HAL_GetTick() - EthernetLinkTimer >= 100)
  {
    EthernetLinkTimer = HAL_GetTick();
    ethernet_link_check_state(netif);
  }
/* USER CODE BEGIN 4_4 */
/* USER CODE END 4_4 */
}

/**
 * ----------------------------------------------------------------------
 * Function given to help user to continue LwIP Initialization
 * Up to user to complete or change this function ...
 * Up to user to call this function in main.c in while (1) of main(void)
 *-----------------------------------------------------------------------
 * Read a received packet from the Ethernet buffers
 * Send it to the lwIP stack for handling
 * Handle timeouts if LWIP_TIMERS is set and without RTOS
 * Handle the llink status if LWIP_NETIF_LINK_CALLBACK is set and without RTOS
 */
void MX_LWIP_Process(void)
{
/* USER CODE BEGIN 4_1 */
/* USER CODE END 4_1 */
  ethernetif_input(&gnetif);

/* USER CODE BEGIN 4_2 */
/* USER CODE END 4_2 */
  /* Handle timeouts */
  sys_check_timeouts();

  Ethernet_Link_Periodic_Handle(&gnetif);

/* USER CODE BEGIN 4_3 */
/* USER CODE END 4_3 */
}

/**
  * @brief  Notify the User about the network interface config status
  * @param  netif: the network interface
  * @retval None
  */
static void ethernet_link_status_updated(struct netif *netif)
{
  if (netif_is_up(netif))
  {
/* USER CODE BEGIN 5 */
/* USER CODE END 5 */
  }
  else /* netif is down */
  {
/* USER CODE BEGIN 6 */
/* USER CODE END 6 */
  }
}

#if defined ( __CC_ARM )  /* MDK ARM Compiler */
/**
 * Opens a serial device for communication.
 *
 * @param devnum device number
 * @return handle to serial device if successful, NULL otherwise
 */
sio_fd_t sio_open(u8_t devnum)
{
  sio_fd_t sd;

/* USER CODE BEGIN 7 */
  sd = 0; // dummy code
/* USER CODE END 7 */

  return sd;
}

/**
 * Sends a single character to the serial device.
 *
 * @param c character to send
 * @param fd serial device handle
 *
 * @note This function will block until the character can be sent.
 */
void sio_send(u8_t c, sio_fd_t fd)
{
/* USER CODE BEGIN 8 */
/* USER CODE END 8 */
}

/**
 * Reads from the serial device.
 *
 * @param fd serial device handle
 * @param data pointer to data buffer for receiving
 * @param len maximum length (in bytes) of data to receive
 * @return number of bytes actually received - may be 0 if aborted by sio_read_abort
 *
 * @note This function will block until data can be received. The blocking
 * can be cancelled by calling sio_read_abort().
 */
u32_t sio_read(sio_fd_t fd, u8_t *data, u32_t len)
{
  u32_t recved_bytes;

/* USER CODE BEGIN 9 */
  recved_bytes = 0; // dummy code
/* USER CODE END 9 */
  return recved_bytes;
}

/**
 * Tries to read from the serial device. Same as sio_read but returns
 * immediately if no data is available and never blocks.
 *
 * @param fd serial device handle
 * @param data pointer to data buffer for receiving
 * @param len maximum length (in bytes) of data to receive
 * @return number of bytes actually received
 */
u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len)
{
  u32_t recved_bytes;

/* USER CODE BEGIN 10 */
  recved_bytes = 0; // dummy code
/* USER CODE END 10 */
  return recved_bytes;
}
#endif /* MDK ARM Compiler */

Project Root > CM7 > LWIP > Target > ethernetif.c :

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * File Name          : ethernetif.c
  * Description        : This file provides code for the configuration
  *                      of the ethernetif.c MiddleWare.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "lwip/opt.h"
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/timeouts.h"
#include "netif/ethernet.h"
#include "netif/etharp.h"
#include "lwip/ethip6.h"
#include "ethernetif.h"
#include "lan8742.h"
#include <string.h>

/* Within 'USER CODE' section, code will be kept by default at each generation */
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* Private define ------------------------------------------------------------*/

/* Network interface name */
#define IFNAME0 's'
#define IFNAME1 't'

/* ETH Setting  */
#define ETH_DMA_TRANSMIT_TIMEOUT               ( 20U )
#define ETH_TX_BUFFER_MAX             ((ETH_TX_DESC_CNT) * 2U)
/* ETH_RX_BUFFER_SIZE parameter is defined in lwipopts.h */

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

/* Private variables ---------------------------------------------------------*/
/*
@Note: This interface is implemented to operate in zero-copy mode only:
        - Rx Buffers will be allocated from LwIP stack Rx memory pool,
          then passed to ETH HAL driver.
        - Tx Buffers will be allocated from LwIP stack memory heap,
          then passed to ETH HAL driver.

@Notes:
  1.a. ETH DMA Rx descriptors must be contiguous, the default count is 4,
       to customize it please redefine ETH_RX_DESC_CNT in ETH GUI (Rx Descriptor Length)
       so that updated value will be generated in stm32xxxx_hal_conf.h
  1.b. ETH DMA Tx descriptors must be contiguous, the default count is 4,
       to customize it please redefine ETH_TX_DESC_CNT in ETH GUI (Tx Descriptor Length)
       so that updated value will be generated in stm32xxxx_hal_conf.h

  2.a. Rx Buffers number must be between ETH_RX_DESC_CNT and 2*ETH_RX_DESC_CNT
  2.b. Rx Buffers must have the same size: ETH_RX_BUFFER_SIZE, this value must
       passed to ETH DMA in the init field (heth.Init.RxBuffLen)
  2.c  The RX Ruffers addresses and sizes must be properly defined to be aligned
       to L1-CACHE line size (32 bytes).
*/

/* Data Type Definitions */
typedef enum
{
  RX_ALLOC_OK       = 0x00,
  RX_ALLOC_ERROR    = 0x01
} RxAllocStatusTypeDef;

typedef struct
{
  struct pbuf_custom pbuf_custom;
  uint8_t buff[(ETH_RX_BUFFER_SIZE + 31) & ~31] __ALIGNED(32);
} RxBuff_t;

/* Memory Pool Declaration */
#define ETH_RX_BUFFER_CNT             12U
__attribute__((section(".Rx_PoolSection"))) LWIP_MEMPOOL_DECLARE(RX_POOL, ETH_RX_BUFFER_CNT, sizeof(RxBuff_t), "Zero-copy RX PBUF pool");

/* Variable Definitions */
static uint8_t RxAllocStatus;
#if defined ( __ICCARM__ ) /*!< IAR Compiler */

#pragma location=0x30000000
ETH_DMADescTypeDef  DMARxDscrTab[ETH_RX_DESC_CNT]; /* Ethernet Rx DMA Descriptors */
#pragma location=0x30000080
ETH_DMADescTypeDef  DMATxDscrTab[ETH_TX_DESC_CNT]; /* Ethernet Tx DMA Descriptors */

#elif defined ( __CC_ARM )  /* MDK ARM Compiler */

__attribute__((at(0x30000000))) ETH_DMADescTypeDef  DMARxDscrTab[ETH_RX_DESC_CNT]; /* Ethernet Rx DMA Descriptors */
__attribute__((at(0x30000080))) ETH_DMADescTypeDef  DMATxDscrTab[ETH_TX_DESC_CNT]; /* Ethernet Tx DMA Descriptors */

#elif defined ( __GNUC__ ) /* GNU Compiler */

ETH_DMADescTypeDef DMARxDscrTab[ETH_RX_DESC_CNT] __attribute__((section(".RxDecripSection"))); /* Ethernet Rx DMA Descriptors */
ETH_DMADescTypeDef DMATxDscrTab[ETH_TX_DESC_CNT] __attribute__((section(".TxDecripSection")));   /* Ethernet Tx DMA Descriptors */

#endif

#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma location = 0x30000100
extern u8_t memp_memory_RX_POOL_base[];

#elif defined ( __CC_ARM ) /* MDK ARM Compiler */
__attribute__((section(".Rx_PoolSection"))) extern u8_t memp_memory_RX_POOL_base[];

#elif defined ( __GNUC__ ) /* GNU */
__attribute__((section(".Rx_PoolSection"))) extern u8_t memp_memory_RX_POOL_base[];
#endif

/* USER CODE BEGIN 2 */

/* USER CODE END 2 */

/* Global Ethernet handle */
ETH_HandleTypeDef heth;

ETH_TxPacketConfig TxConfig;

/* Private function prototypes -----------------------------------------------*/
int32_t ETH_PHY_IO_Init(void);
int32_t ETH_PHY_IO_DeInit (void);
int32_t ETH_PHY_IO_ReadReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t *pRegVal);
int32_t ETH_PHY_IO_WriteReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t RegVal);
int32_t ETH_PHY_IO_GetTick(void);

lan8742_Object_t LAN8742;
lan8742_IOCtx_t  LAN8742_IOCtx = {ETH_PHY_IO_Init,
                                  ETH_PHY_IO_DeInit,
                                  ETH_PHY_IO_WriteReg,
                                  ETH_PHY_IO_ReadReg,
                                  ETH_PHY_IO_GetTick};

/* USER CODE BEGIN 3 */

/* USER CODE END 3 */

/* Private functions ---------------------------------------------------------*/
void pbuf_free_custom(struct pbuf *p);

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/*******************************************************************************
                       LL Driver Interface ( LwIP stack --> ETH)
*******************************************************************************/
/**
 * @brief In this function, the hardware should be initialized.
 * Called from ethernetif_init().
 *
 * @param netif the already initialized lwip network interface structure
 * for this ethernetif
 */
static void low_level_init(struct netif *netif)
{
  HAL_StatusTypeDef hal_eth_init_status = HAL_OK;

  /* [중요 수정 1] MAC 주소 변수를 static으로 선언하여 메모리에서 사라지지 않게 함 */
  static uint8_t MACAddr[6];

  /* [중요 수정 2] 하드웨어 초기화 전에 반드시 메모리 풀(RX_POOL)을 먼저 초기화해야 합니다. */
  /* 이 줄이 HAL_ETH_Init보다 밑에 있으면 수신 기능이 고장 납니다. */
  LWIP_MEMPOOL_INIT(RX_POOL);

  /* 디스크립터 메모리 초기화 (안전장치) */
  memset(DMARxDscrTab, 0, sizeof(ETH_DMADescTypeDef) * ETH_RX_DESC_CNT);
  memset(DMATxDscrTab, 0, sizeof(ETH_DMADescTypeDef) * ETH_TX_DESC_CNT);

  heth.Instance = ETH;
  MACAddr[0] = 0x00;
  MACAddr[1] = 0x80;
  MACAddr[2] = 0xE1;
  MACAddr[3] = 0x00;
  MACAddr[4] = 0x00;
  MACAddr[5] = 0x00;
  heth.Init.MACAddr = &MACAddr[0];
  heth.Init.MediaInterface = HAL_ETH_RMII_MODE;
  heth.Init.TxDesc = DMATxDscrTab;
  heth.Init.RxDesc = DMARxDscrTab;

  /* [중요 수정 3] 버퍼 크기를 1536 대신 실제 정의된 매크로로 맞춤 */
  heth.Init.RxBuffLen = ETH_RX_BUFFER_SIZE;

  /* USER CODE BEGIN MACADDRESS */
  HAL_Delay(100);
  /* USER CODE END MACADDRESS */

  hal_eth_init_status = HAL_ETH_Init(&heth);

  /* [중요 수정 4] 하드웨어 체크섬 끄기 (소프트웨어 체크섬 사용) */
  memset(&TxConfig, 0 , sizeof(ETH_TxPacketConfig));
  TxConfig.Attributes = ETH_TX_PACKETS_FEATURES_CRCPAD;
  TxConfig.ChecksumCtrl = ETH_CHECKSUM_DISABLE; // LwIP가 계산하도록 설정
  TxConfig.CRCPadCtrl = ETH_CRC_PAD_INSERT;

  /* End ETH HAL Init */

  /* LWIP_MEMPOOL_INIT(RX_POOL); <--- 원래 여기 있던 코드를 위로 올렸습니다. */

#if LWIP_ARP || LWIP_ETHERNET
  /* set MAC hardware address length */
  netif->hwaddr_len = ETH_HWADDR_LEN;

  /* set MAC hardware address */
  netif->hwaddr[0] =  heth.Init.MACAddr[0];
  netif->hwaddr[1] =  heth.Init.MACAddr[1];
  netif->hwaddr[2] =  heth.Init.MACAddr[2];
  netif->hwaddr[3] =  heth.Init.MACAddr[3];
  netif->hwaddr[4] =  heth.Init.MACAddr[4];
  netif->hwaddr[5] =  heth.Init.MACAddr[5];

  /* maximum transfer unit */
  netif->mtu = ETH_MAX_PAYLOAD;

  /* Accept broadcast address and ARP traffic */
#if LWIP_ARP
    netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
#else
    netif->flags |= NETIF_FLAG_BROADCAST;
#endif /* LWIP_ARP */

/* USER CODE BEGIN PHY_PRE_CONFIG */
/* USER CODE END PHY_PRE_CONFIG */

  /* Set PHY IO functions */
  LAN8742_RegisterBusIO(&LAN8742, &LAN8742_IOCtx);

  /* Initialize the LAN8742 ETH PHY */
  if(LAN8742_Init(&LAN8742) != LAN8742_STATUS_OK)
  {
    netif_set_link_down(netif);
    netif_set_down(netif);
    return;
  }

  if (hal_eth_init_status == HAL_OK)
  {
    /* Get link state */
    ethernet_link_check_state(netif);
  }
  else
  {
    Error_Handler();
  }
#endif /* LWIP_ARP || LWIP_ETHERNET */
}

/**
 * @brief This function should do the actual transmission of the packet. The packet is
 * contained in the pbuf that is passed to the function. This pbuf
 * might be chained.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
 * @return ERR_OK if the packet could be sent
 *         an err_t value if the packet couldn't be sent
 *
 * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
 *       strange results. You might consider waiting for space in the DMA queue
 *       to become available since the stack doesn't retry to send a packet
 *       dropped because of memory failure (except for the TCP timers).
 */

/* ethernetif.c 파일 내부 */

static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
  uint32_t i = 0U;
  struct pbuf *q = NULL;
  err_t errval = ERR_OK;
  ETH_BufferTypeDef Txbuffer[ETH_TX_DESC_CNT] = {0};

  memset(Txbuffer, 0 , ETH_TX_DESC_CNT*sizeof(ETH_BufferTypeDef));

  for(q = p; q != NULL; q = q->next)
  {
    if(i >= ETH_TX_DESC_CNT)
      return ERR_IF;

    Txbuffer[i].buffer = q->payload;
    Txbuffer[i].len = q->len;

    /* ========================================================== */
    /* [핵심 수정] TX 패킷을 DMA가 가져가기 전에 캐시를 RAM으로 밀어넣습니다. */
    /* 이 코드가 없으면 공유기는 깨진 패킷을 받고 무시합니다. */
    /* ========================================================== */
    SCB_CleanDCache_by_Addr((uint32_t *)q->payload, q->len);
    /* ========================================================== */

    if(i>0)
    {
      Txbuffer[i-1].next = &Txbuffer[i];
    }

    if(q->next == NULL)
    {
      Txbuffer[i].next = NULL;
    }

    i++;
  }

  TxConfig.Length = p->tot_len;
  TxConfig.TxBuffer = Txbuffer;
  TxConfig.pData = p;

  /* 디버깅용 로그 */
  // printf("TX Packet: len=%d\r\n", p->tot_len);

  HAL_ETH_Transmit(&heth, &TxConfig, ETH_DMA_TRANSMIT_TIMEOUT);

  return errval;
}

/**
 * @brief Should allocate a pbuf and transfer the bytes of the incoming
 * packet from the interface into the pbuf.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return a pbuf filled with the received packet (including MAC header)
 *         NULL on memory error
   */
static struct pbuf * low_level_input(struct netif *netif)
{
  struct pbuf *p = NULL;

  if(RxAllocStatus == RX_ALLOC_OK)
  {
    HAL_ETH_ReadData(&heth, (void **)&p);
  }

  return p;
}

/**
 * @brief This function should be called when a packet is ready to be read
 * from the interface. It uses the function low_level_input() that
 * should handle the actual reception of bytes from the network
 * interface. Then the type of the received packet is determined and
 * the appropriate input function is called.
 *
 * @param netif the lwip network interface structure for this ethernetif
 */
void ethernetif_input(struct netif *netif)
{
  struct pbuf *p = NULL;

  do
  {
    p = low_level_input( netif );
    if (p != NULL)
    {
      if (netif->input( p, netif) != ERR_OK )
      {
        pbuf_free(p);
      }
    }
  } while(p!=NULL);
}

#if !LWIP_ARP
/**
 * This function has to be completed by user in case of ARP OFF.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return ERR_OK if ...
 */
static err_t low_level_output_arp_off(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
{
  err_t errval;
  errval = ERR_OK;

/* USER CODE BEGIN 5 */

/* USER CODE END 5 */

  return errval;

}
#endif /* LWIP_ARP */

/**
 * @brief Should be called at the beginning of the program to set up the
 * network interface. It calls the function low_level_init() to do the
 * actual setup of the hardware.
 *
 * This function should be passed as a parameter to netif_add().
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return ERR_OK if the loopif is initialized
 *         ERR_MEM if private data couldn't be allocated
 *         any other err_t on error
 */
err_t ethernetif_init(struct netif *netif)
{
  LWIP_ASSERT("netif != NULL", (netif != NULL));

#if LWIP_NETIF_HOSTNAME
  /* Initialize interface hostname */
  netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */

  /*
   * Initialize the snmp variables and counters inside the struct netif.
   * The last argument should be replaced with your link speed, in units
   * of bits per second.
   */
  // MIB2_INIT_NETIF(netif, snmp_ifType_ethernet_csmacd, LINK_SPEED_OF_YOUR_NETIF_IN_BPS);

  netif->name[0] = IFNAME0;
  netif->name[1] = IFNAME1;
  /* We directly use etharp_output() here to save a function call.
   * You can instead declare your own function an call etharp_output()
   * from it if you have to do some checks before sending (e.g. if link
   * is available...) */

#if LWIP_IPV4
#if LWIP_ARP || LWIP_ETHERNET
#if LWIP_ARP
  netif->output = etharp_output;
#else
  /* The user should write its own code in low_level_output_arp_off function */
  netif->output = low_level_output_arp_off;
#endif /* LWIP_ARP */
#endif /* LWIP_ARP || LWIP_ETHERNET */
#endif /* LWIP_IPV4 */

#if LWIP_IPV6
  netif->output_ip6 = ethip6_output;
#endif /* LWIP_IPV6 */

  netif->linkoutput = low_level_output;

  /* initialize the hardware */
  low_level_init(netif);

  return ERR_OK;
}

/**
  * @brief  Custom Rx pbuf free callback
  * @param  pbuf: pbuf to be freed
  * @retval None
  */
void pbuf_free_custom(struct pbuf *p)
{
  struct pbuf_custom* custom_pbuf = (struct pbuf_custom*)p;
  LWIP_MEMPOOL_FREE(RX_POOL, custom_pbuf);

  /* If the Rx Buffer Pool was exhausted, signal the ethernetif_input task to
   * call HAL_ETH_GetRxDataBuffer to rebuild the Rx descriptors. */

  if (RxAllocStatus == RX_ALLOC_ERROR)
  {
    RxAllocStatus = RX_ALLOC_OK;
  }
}

/* USER CODE BEGIN 6 */

/**
* @brief  Returns the current time in milliseconds
*         when LWIP_TIMERS == 1 and NO_SYS == 1
* @param  None
* @retval Current Time value
*/
u32_t sys_now(void)
{
  return HAL_GetTick();
}

/* USER CODE END 6 */

/**
  * @brief  Initializes the ETH MSP.
  * @param  ethHandle: ETH handle
  * @retval None
  */

void HAL_ETH_MspInit(ETH_HandleTypeDef* ethHandle)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(ethHandle->Instance==ETH)
  {
  /* USER CODE BEGIN ETH_MspInit 0 */

  /* USER CODE END ETH_MspInit 0 */
    /* Enable Peripheral clock */
    __HAL_RCC_ETH1MAC_CLK_ENABLE();
    __HAL_RCC_ETH1TX_CLK_ENABLE();
    __HAL_RCC_ETH1RX_CLK_ENABLE();

    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOG_CLK_ENABLE();
    /**ETH GPIO Configuration
    PC1     ------> ETH_MDC
    PA1     ------> ETH_REF_CLK
    PA2     ------> ETH_MDIO
    PA7     ------> ETH_CRS_DV
    PC4     ------> ETH_RXD0
    PC5     ------> ETH_RXD1
    PB13     ------> ETH_TXD1
    PG11     ------> ETH_TX_EN
    PG13     ------> ETH_TXD0
    */
    GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_13;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_13;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);

    /* Peripheral interrupt init */
    HAL_NVIC_SetPriority(ETH_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(ETH_IRQn);
  /* USER CODE BEGIN ETH_MspInit 1 */

  /* USER CODE END ETH_MspInit 1 */
  }
}

void HAL_ETH_MspDeInit(ETH_HandleTypeDef* ethHandle)
{
  if(ethHandle->Instance==ETH)
  {
  /* USER CODE BEGIN ETH_MspDeInit 0 */

  /* USER CODE END ETH_MspDeInit 0 */
    /* Disable Peripheral clock */
    __HAL_RCC_ETH1MAC_CLK_DISABLE();
    __HAL_RCC_ETH1TX_CLK_DISABLE();
    __HAL_RCC_ETH1RX_CLK_DISABLE();

    /**ETH GPIO Configuration
    PC1     ------> ETH_MDC
    PA1     ------> ETH_REF_CLK
    PA2     ------> ETH_MDIO
    PA7     ------> ETH_CRS_DV
    PC4     ------> ETH_RXD0
    PC5     ------> ETH_RXD1
    PB13     ------> ETH_TXD1
    PG11     ------> ETH_TX_EN
    PG13     ------> ETH_TXD0
    */
    HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5);

    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_7);

    HAL_GPIO_DeInit(GPIOB, GPIO_PIN_13);

    HAL_GPIO_DeInit(GPIOG, GPIO_PIN_11|GPIO_PIN_13);

    /* Peripheral interrupt Deinit*/
    HAL_NVIC_DisableIRQ(ETH_IRQn);

  /* USER CODE BEGIN ETH_MspDeInit 1 */

  /* USER CODE END ETH_MspDeInit 1 */
  }
}

/*******************************************************************************
                       PHI IO Functions
*******************************************************************************/
/**
  * @brief  Initializes the MDIO interface GPIO and clocks.
  * @param  None
  * @retval 0 if OK, -1 if ERROR
  */
int32_t ETH_PHY_IO_Init(void)
{
  /* We assume that MDIO GPIO configuration is already done
     in the ETH_MspInit() else it should be done here
  */

  /* Configure the MDIO Clock */
  HAL_ETH_SetMDIOClockRange(&heth);

  return 0;
}

/**
  * @brief  De-Initializes the MDIO interface .
  * @param  None
  * @retval 0 if OK, -1 if ERROR
  */
int32_t ETH_PHY_IO_DeInit (void)
{
  return 0;
}

/**
  * @brief  Read a PHY register through the MDIO interface.
  * @param  DevAddr: PHY port address
  * @param  RegAddr: PHY register address
  * @param  pRegVal: pointer to hold the register value
  * @retval 0 if OK -1 if Error
  */
int32_t ETH_PHY_IO_ReadReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t *pRegVal)
{
  if(HAL_ETH_ReadPHYRegister(&heth, DevAddr, RegAddr, pRegVal) != HAL_OK)
  {
    return -1;
  }

  return 0;
}

/**
  * @brief  Write a value to a PHY register through the MDIO interface.
  * @param  DevAddr: PHY port address
  * @param  RegAddr: PHY register address
  * @param  RegVal: Value to be written
  * @retval 0 if OK -1 if Error
  */
int32_t ETH_PHY_IO_WriteReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t RegVal)
{
  if(HAL_ETH_WritePHYRegister(&heth, DevAddr, RegAddr, RegVal) != HAL_OK)
  {
    return -1;
  }

  return 0;
}

/**
  * @brief  Get the time in millisecons used for internal PHY driver process.
  * @retval Time value
  */
int32_t ETH_PHY_IO_GetTick(void)
{
  return HAL_GetTick();
}

/**
  * @brief  Check the ETH link state then update ETH driver and netif link accordingly.
  * @retval None
  */
void ethernet_link_check_state(struct netif *netif)
{
  ETH_MACConfigTypeDef MACConf = {0};
  int32_t PHYLinkState = 0;
  uint32_t linkchanged = 0U, speed = 0U, duplex = 0U;

  PHYLinkState = LAN8742_GetLinkState(&LAN8742);

  if(netif_is_link_up(netif) && (PHYLinkState <= LAN8742_STATUS_LINK_DOWN))
  {
    HAL_ETH_Stop_IT(&heth);
    netif_set_down(netif);
    netif_set_link_down(netif);
  }
  else if(!netif_is_link_up(netif) && (PHYLinkState > LAN8742_STATUS_LINK_DOWN))
  {
    switch (PHYLinkState)
    {
    case LAN8742_STATUS_100MBITS_FULLDUPLEX:
      duplex = ETH_FULLDUPLEX_MODE;
      speed = ETH_SPEED_100M;
      linkchanged = 1;
      break;
    case LAN8742_STATUS_100MBITS_HALFDUPLEX:
      duplex = ETH_HALFDUPLEX_MODE;
      speed = ETH_SPEED_100M;
      linkchanged = 1;
      break;
    case LAN8742_STATUS_10MBITS_FULLDUPLEX:
      duplex = ETH_FULLDUPLEX_MODE;
      speed = ETH_SPEED_10M;
      linkchanged = 1;
      break;
    case LAN8742_STATUS_10MBITS_HALFDUPLEX:
      duplex = ETH_HALFDUPLEX_MODE;
      speed = ETH_SPEED_10M;
      linkchanged = 1;
      break;
    default:
      break;
    }

    if(linkchanged)
    {
      /* Get MAC Config MAC */
      HAL_ETH_GetMACConfig(&heth, &MACConf);
      MACConf.DuplexMode = duplex;
      MACConf.Speed = speed;
      HAL_ETH_SetMACConfig(&heth, &MACConf);
      HAL_ETH_Start_IT(&heth);
      netif_set_up(netif);
      netif_set_link_up(netif);
    }
  }

}

void HAL_ETH_RxAllocateCallback(uint8_t **buff)
{
/* USER CODE BEGIN HAL ETH RxAllocateCallback */
  struct pbuf_custom *p = LWIP_MEMPOOL_ALLOC(RX_POOL);
  if (p)
  {
    /* Get the buff from the struct pbuf address. */
    *buff = (uint8_t *)p + offsetof(RxBuff_t, buff);
    p->custom_free_function = pbuf_free_custom;
    /* Initialize the struct pbuf.
    * This must be performed whenever a buffer's allocated because it may be
    * changed by lwIP or the app, e.g., pbuf_free decrements ref. */
    pbuf_alloced_custom(PBUF_RAW, 0, PBUF_REF, p, *buff, ETH_RX_BUFFER_SIZE);
  }
  else
  {
    RxAllocStatus = RX_ALLOC_ERROR;
    *buff = NULL;
  }
/* USER CODE END HAL ETH RxAllocateCallback */
}

void HAL_ETH_RxLinkCallback(void **pStart, void **pEnd, uint8_t *buff, uint16_t Length)
{
/* USER CODE BEGIN HAL ETH RxLinkCallback */

  struct pbuf **ppStart = (struct pbuf **)pStart;
  struct pbuf **ppEnd = (struct pbuf **)pEnd;
  struct pbuf *p = NULL;

  /* Get the struct pbuf from the buff address. */
  p = (struct pbuf *)(buff - offsetof(RxBuff_t, buff));
  p->next = NULL;
  p->tot_len = 0;
  p->len = Length;

  /* Chain the buffer. */
  if (!*ppStart)
  {
    /* The first buffer of the packet. */
    *ppStart = p;
  }
  else
  {
    /* Chain the buffer to the end of the packet. */
    (*ppEnd)->next = p;
  }
  *ppEnd  = p;

  /* Update the total length of all the buffers of the chain. Each pbuf in the chain should have its tot_len
   * set to its own length, plus the length of all the following pbufs in the chain. */
  for (p = *ppStart; p != NULL; p = p->next)
  {
    p->tot_len += Length;
  }

  /* Invalidate data cache because Rx DMA's writing to physical memory makes it stale. */
  SCB_InvalidateDCache_by_Addr((uint32_t *)buff, Length);

/* USER CODE END HAL ETH RxLinkCallback */
}

void HAL_ETH_TxFreeCallback(uint32_t * buff)
{
/* USER CODE BEGIN HAL ETH TxFreeCallback */

  pbuf_free((struct pbuf *)buff);

/* USER CODE END HAL ETH TxFreeCallback */
}

/* USER CODE BEGIN 8 */

/* USER CODE END 8 */

Project Root > CM7 > LWIP > Target > lwipopts.h :


/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * File Name          : Target/lwipopts.h
  * Description        : This file overrides LwIP stack default configuration
  *                      done in opt.h file.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Define to prevent recursive inclusion --------------------------------------*/
#ifndef __LWIPOPTS__H__
#define __LWIPOPTS__H__

#include "main.h"

/*-----------------------------------------------------------------------------*/
/* Current version of LwIP supported by CubeMx: 2.1.2 -*/
/*-----------------------------------------------------------------------------*/

/* Within 'USER CODE' section, code will be kept by default at each generation */
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

#ifdef __cplusplus
 extern "C" {
#endif

/* STM32CubeMX Specific Parameters (not defined in opt.h) ---------------------*/
/* Parameters set in STM32CubeMX LwIP Configuration GUI -*/
/*----- WITH_RTOS disabled (Since FREERTOS is not set) -----*/
#define WITH_RTOS 0
/*----- CHECKSUM_BY_HARDWARE enabled -----*/
#define CHECKSUM_BY_HARDWARE 0
/*-----------------------------------------------------------------------------*/

#define MEM_SIZE 16384
#define MEMP_NUM_PBUF 16
#define MEMP_NUM_UDP_PCB 4
/* LwIP Stack Parameters (modified compared to initialization value in opt.h) -*/
/* Parameters set in STM32CubeMX LwIP Configuration GUI -*/
/*----- Value in opt.h for LWIP_DHCP: 0 -----*/
#define LWIP_DHCP 1
/*----- Default value in ETH configuration GUI in CubeMx: 1524 -----*/
#define ETH_RX_BUFFER_SIZE 1536
/*----- Value in opt.h for NO_SYS: 0 -----*/
#define NO_SYS 1
/*----- Value in opt.h for SYS_LIGHTWEIGHT_PROT: 1 -----*/
#define SYS_LIGHTWEIGHT_PROT 0
/*----- Value in opt.h for MEM_ALIGNMENT: 1 -----*/
#define MEM_ALIGNMENT 4
/*----- Default Value for H7 devices: 0x30004000 -----*/
#define LWIP_RAM_HEAP_POINTER 0x30020000
/*----- Value in opt.h for MEMP_NUM_SYS_TIMEOUT: (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + (PPP_SUPPORT*6*MEMP_NUM_PPP_PCB) + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0)) -*/
#define MEMP_NUM_SYS_TIMEOUT 5
/*----- Value supported for H7 devices: 1 -----*/
#define LWIP_SUPPORT_CUSTOM_PBUF 1
/*----- Value in opt.h for LWIP_ETHERNET: LWIP_ARP || PPPOE_SUPPORT -*/
#define LWIP_ETHERNET 1
/*----- Value in opt.h for LWIP_DNS_SECURE: (LWIP_DNS_SECURE_RAND_XID | LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT) -*/
#define LWIP_DNS_SECURE 7
/*----- Value in opt.h for TCP_SND_QUEUELEN: (4*TCP_SND_BUF + (TCP_MSS - 1))/TCP_MSS -----*/
#define TCP_SND_QUEUELEN 9
/*----- Value in opt.h for TCP_SNDLOWAT: LWIP_MIN(LWIP_MAX(((TCP_SND_BUF)/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF) - 1) -*/
#define TCP_SNDLOWAT 1071
/*----- Value in opt.h for TCP_SNDQUEUELOWAT: LWIP_MAX(TCP_SND_QUEUELEN)/2, 5) -*/
#define TCP_SNDQUEUELOWAT 5
/*----- Value in opt.h for TCP_WND_UPDATE_THRESHOLD: LWIP_MIN(TCP_WND/4, TCP_MSS*4) -----*/
#define TCP_WND_UPDATE_THRESHOLD 536
/*----- Value in opt.h for LWIP_NETIF_LINK_CALLBACK: 0 -----*/
#define LWIP_NETIF_LINK_CALLBACK 1
/*----- Value in opt.h for LWIP_NETCONN: 1 -----*/
#define LWIP_NETCONN 0
/*----- Value in opt.h for LWIP_SOCKET: 1 -----*/
#define LWIP_SOCKET 0
/*----- Value in opt.h for RECV_BUFSIZE_DEFAULT: INT_MAX -----*/
#define RECV_BUFSIZE_DEFAULT 2000000000
/*----- Value in opt.h for LWIP_STATS: 1 -----*/
#define LWIP_STATS 0
/*----- Value in opt.h for CHECKSUM_GEN_IP: 1 -----*/
#define CHECKSUM_GEN_IP 1
/*----- Value in opt.h for CHECKSUM_GEN_UDP: 1 -----*/
#define CHECKSUM_GEN_UDP 1
/*----- Value in opt.h for CHECKSUM_GEN_TCP: 1 -----*/
#define CHECKSUM_GEN_TCP 1
/*----- Value in opt.h for CHECKSUM_GEN_ICMP6: 1 -----*/
#define CHECKSUM_GEN_ICMP6 1
/*----- Value in opt.h for CHECKSUM_CHECK_IP: 1 -----*/
#define CHECKSUM_CHECK_IP 1
/*----- Value in opt.h for CHECKSUM_CHECK_UDP: 1 -----*/
#define CHECKSUM_CHECK_UDP 1
/*----- Value in opt.h for CHECKSUM_CHECK_TCP: 1 -----*/
#define CHECKSUM_CHECK_TCP 1
/*----- Value in opt.h for CHECKSUM_CHECK_ICMP6: 1 -----*/
#define CHECKSUM_CHECK_ICMP6 1
/*-----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

#ifdef __cplusplus
}
#endif
#endif /*__LWIPOPTS__H__ */

중요한 설정은

• LWIP_MEMPOOL_INIT(RX_POOL); 의 호출 위치 변경
• 하드웨어 체크섬 해제후 소프트웨어적으로 바꿈

이구요.

이후에

• 링커스크립트로 D2 도메인을 등록
• ethernetif.c에서 RX, TX 수신버퍼가 된대로 등록한 도메인에 할당

을 할 것입니다. ethernetif.c는 위와 같이 하면 되고 STM32H755ZITX_FLASH.ld에 아래처럼 교체합니다.

/*
******************************************************************************
**
**  File        : LinkerScript.ld
**
**  Author      : STM32CubeIDE
**
**  Abstract    : Linker script for STM32H7 series
**                      1024Kbytes FLASH
**                      800Kbytes RAM
**
**                Set heap size, stack size and stack location according
**                to application requirements.
**
**                Set memory bank area and size if external memory is used.
**
**  Target      : STMicroelectronics STM32
**
**  Distribution: The file is distributed as is without any warranty
**                of any kind.
**
*****************************************************************************
** @attention
**
** Copyright (c) 2025 STMicroelectronics.
** All rights reserved.
**
** This software is licensed under terms that can be found in the LICENSE file
** in the root directory of this software component.
** If no LICENSE file comes with this software, it is provided AS-IS.
**
*****************************************************************************
*/

/* Entry Point */
ENTRY(Reset_Handler)

/* Highest address of the user mode stack */
_estack = ORIGIN(RAM_D1) + LENGTH(RAM_D1); /* end of "RAM_D1" Ram type memory */

_Min_Heap_Size = 0x4000; /* required amount of heap  */
_Min_Stack_Size = 0x4000; /* required amount of stack */

/* Memories definition */
MEMORY
{
RAM_D1 (xrw)      : ORIGIN = 0x24000000, LENGTH =  512K
FLASH   (rx)      : ORIGIN = 0x08000000, LENGTH = 1024K    /* Memory is divided. Actual start is 0x08000000 and actual length is 2048K */
DTCMRAM (xrw)     : ORIGIN = 0x20000000, LENGTH = 128K
SRAM1_AND_2 (xrw) : ORIGIN = 0x30000000, LENGTH = 256K
SRAM3 (xrw)       : ORIGIN = 0x30040000, LENGTH = 32K
RAM_D3 (xrw)      : ORIGIN = 0x38000000, LENGTH = 64K
ITCMRAM (xrw)     : ORIGIN = 0x00000000, LENGTH = 64K
}

/* Sections */
SECTIONS
{
/* The startup code into "FLASH" Rom type memory */
.isr_vector :
{
. = ALIGN(4);
KEEP(*(.isr_vector)) /* Startup code */
. = ALIGN(4);
} >FLASH

/* The program code and other data into "FLASH" Rom type memory */
.text :
{
. = ALIGN(4);
*(.text)           /* .text sections (code) */
*(.text*)          /* .text* sections (code) */
*(.glue_7)         /* glue arm to thumb code */
*(.glue_7t)        /* glue thumb to arm code */
*(.eh_frame)

KEEP (*(.init))
KEEP (*(.fini))

. = ALIGN(4);
_etext = .;        /* define a global symbols at end of code */
} >FLASH

/* Constant data into "FLASH" Rom type memory */
.rodata :
{
. = ALIGN(4);
*(.rodata)         /* .rodata sections (constants, strings, etc.) */
*(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
. = ALIGN(4);
} >FLASH

.ARM.extab (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
{
. = ALIGN(4);
*(.ARM.extab* .gnu.linkonce.armextab.*)
. = ALIGN(4);
} >FLASH
.ARM (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
{
. = ALIGN(4);
__exidx_start = .;
*(.ARM.exidx*)
__exidx_end = .;
. = ALIGN(4);
} >FLASH

.preinit_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
{
. = ALIGN(4);
PROVIDE_HIDDEN (__preinit_array_start = .);
KEEP (*(.preinit_array*))
PROVIDE_HIDDEN (__preinit_array_end = .);
. = ALIGN(4);
} >FLASH

.init_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
{
. = ALIGN(4);
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array*))
PROVIDE_HIDDEN (__init_array_end = .);
. = ALIGN(4);
} >FLASH

.fini_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
{
. = ALIGN(4);
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP (*(SORT(.fini_array.*)))
KEEP (*(.fini_array*))
PROVIDE_HIDDEN (__fini_array_end = .);
. = ALIGN(4);
} >FLASH

/* Used by the startup to initialize data */
_sidata = LOADADDR(.data);

/* Initialized data sections into "RAM" Ram type memory */
.data :
{
. = ALIGN(4);
_sdata = .;        /* create a global symbol at data start */
*(.data)           /* .data sections */
*(.data*)          /* .data* sections */
*(.RamFunc)        /* .RamFunc sections */
*(.RamFunc*)       /* .RamFunc* sections */

. = ALIGN(4);
_edata = .;        /* define a global symbol at data end */
} >RAM_D1 AT> FLASH

/* Uninitialized data section into "RAM" Ram type memory */
. = ALIGN(4);
.bss :
{
/* This is used by the startup in order to initialize the .bss section */
_sbss = .;         /* define a global symbol at bss start */
__bss_start__ = _sbss;
*(.bss)
*(.bss*)
*(COMMON)

. = ALIGN(4);
_ebss = .;         /* define a global symbol at bss end */
__bss_end__ = _ebss;
} >RAM_D1

/* User_heap_stack section, used to check that there is enough "RAM" Ram  type memory left */
._user_heap_stack :
{
. = ALIGN(8);
PROVIDE ( end = . );
PROVIDE ( _end = . );
. = . + _Min_Heap_Size;
. = . + _Min_Stack_Size;
. = ALIGN(8);
} >RAM_D1

.lwip_sec : 
{
. = ALIGN(32);
*(.RxDecripSection)
. = ALIGN(32);
*(.TxDecripSection)
. = ALIGN(32);
*(.Rx_PoolSection)
} >SRAM1_AND_2
/* Remove information from the compiler libraries */
/DISCARD/ :
{
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}

.ARM.attributes 0 : { *(.ARM.attributes) }
}

이렇게 하면 위에 ethernetif.c의 초반부에 선언된 RX, TX 변수가 SRAM1_AND_2에 배정되어 이더넷 장치가 참조가 가능하게 됩니다.

#define ETH_RX_BUFFER_CNT             12U
__attribute__((section(".Rx_PoolSection"))) LWIP_MEMPOOL_DECLARE(RX_POOL, ETH_RX_BUFFER_CNT, sizeof(RxBuff_t), "Zero-copy RX PBUF pool");

이 부분과

#elif defined ( __GNUC__ ) /* GNU Compiler */

ETH_DMADescTypeDef DMARxDscrTab[ETH_RX_DESC_CNT] __attribute__((section(".RxDecripSection"))); /* Ethernet Rx DMA Descriptors */
ETH_DMADescTypeDef DMATxDscrTab[ETH_TX_DESC_CNT] __attribute__((section(".TxDecripSection")));   /* Ethernet Tx DMA Descriptors */

#endif

#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma location = 0x30000100
extern u8_t memp_memory_RX_POOL_base[];

#elif defined ( __CC_ARM ) /* MDK ARM Compiler */
__attribute__((section(".Rx_PoolSection"))) extern u8_t memp_memory_RX_POOL_base[];

#elif defined ( __GNUC__ ) /* GNU */
__attribute__((section(".Rx_PoolSection"))) extern u8_t memp_memory_RX_POOL_base[];
#endif

이부분이 확실하게 각각의 구간에 선언되게 해놔야 합니다.

이렇게 해두고나서 main.c에

#include "main.h"
#include "lwip.h"
#include "usart.h"
#include "gpio.h"

#include "lwip.h"
#include "lwip/dhcp.h"
#include "lwip/netif.h"
#include <stdio.h>
#include <string.h>


extern struct netif gnetif;
char ip_string[16] = {0};
uint8_t dhcp_state = 0;
uint8_t link_state = 0;

void Display_IP_Address(void)
{
  uint32_t ip_addr = gnetif.ip_addr.addr;

  /* Convert IP to string */
  sprintf(ip_string, "%d.%d.%d.%d",
          (int)(ip_addr & 0xFF),
          (int)((ip_addr >> 8) & 0xFF),
          (int)((ip_addr >> 16) & 0xFF),
          (int)((ip_addr >> 24) & 0xFF));

  /* Print to UART */
  printf("IP Address: %s\r\n", ip_string);
  printf("Netmask: %d.%d.%d.%d\r\n",
         (int)(gnetif.netmask.addr & 0xFF),
         (int)((gnetif.netmask.addr >> 8) & 0xFF),
         (int)((gnetif.netmask.addr >> 16) & 0xFF),
         (int)((gnetif.netmask.addr >> 24) & 0xFF));
  printf("Gateway: %d.%d.%d.%d\r\n",
         (int)(gnetif.gw.addr & 0xFF),
         (int)((gnetif.gw.addr >> 8) & 0xFF),
         (int)((gnetif.gw.addr >> 16) & 0xFF),
         (int)((gnetif.gw.addr >> 24) & 0xFF));
}

void network_run() {

  HAL_Delay(5000);
  printf("\r\n\r\n");
  printf("=== Ethernet Test ===\r\n");

  /* * 참고: 케이블이 이미 꽂혀있는 상태로 부팅되면
   * 루프 진입 직후 netif_is_link_up이 true가 되어
   * 즉시 DHCP가 시작됩니다.
   */

  while (1) {
    /* LwIP 주기적 처리 (패킷 수신, 타이머 처리 등) */
    MX_LWIP_Process();

    /* 1. 링크 상태 모니터링 및 DHCP 제어 */
    if (netif_is_link_up(&gnetif) && link_state == 0)
    {
      /* 링크가 방금 연결됨 (0 -> 1) */
      link_state = 1;
      printf("Ethernet Link UP - Starting DHCP...\r\n");

      /* 여기서 DHCP 시작! */
      dhcp_start(&gnetif);
    }
    else if (!netif_is_link_up(&gnetif) && link_state == 1)
    {
      /* 링크가 끊어짐 (1 -> 0) */
      link_state = 0;
      dhcp_state = 0; // IP 출력 플래그 초기화
      printf("Ethernet Link DOWN - Stopping DHCP.\r\n");

      /* DHCP 중지 (선택 사항이지만 권장) */
      dhcp_stop(&gnetif);

      /* IP 주소를 0.0.0.0으로 리셋 (재연결 시 갱신 확인용) */
      ip_addr_set_zero(&gnetif.ip_addr);
      ip_addr_set_zero(&gnetif.netmask);
      ip_addr_set_zero(&gnetif.gw);
    }

    /* 2. IP 할당 완료 체크 */
    /* dhcp_state 변수는 'IP가 출력되었는지'를 확인하는 용도로 사용 */
    if (gnetif.ip_addr.addr != 0 && dhcp_state == 0)
    {
      dhcp_state = 1; // 한 번만 출력하기 위한 플래그
      printf("DHCP Bound Success!\r\n");
      Display_IP_Address();
    }

    /* 너무 긴 지연은 LwIP 처리를 늦출 수 있으므로 줄이거나 제거하는 것이 좋습니다 */
    /* HAL_Delay(100); -> 10ms 정도로 줄이거나 제거 권장 */
    HAL_Delay(10);
  }
}

처럼 선언한 함수를 main()에서 장치 초기화 다음 라인에

network_run();

처럼 호출합니다.

위파일대로 되어 있다면 잘 작동할 것입니다.

이더넷 케이블을 꼽고 (CAT5 추천) 있으면 Link Up 이 되었다고 나오고, 이내 DHCP Bound Success!가 뜨고 DHCP로 IP를 받아옵니다. 케이블을 떼어내면 Link DOWN!이 뜨고 다시 연결하면 DHCP Bound Success! 가 뜹니다. 이것이 순식간에 일어납니다.

물론 50MHz의 빠른 속도가 필요하니 설정이 필요한데요. ETH 핀들의 Maximum 속도를 Very High로 두는 것입니다. 대체로 위 코드에 포함되어있습니다.

혹시 오타가 있다면 말씀해주세요. 프록시 환경이라 오타가 늦게 발견되기도 합니다. 일단 올려둡니다.

[RPI-PICO] MinGW UCRT가 무엇인가? (이번에는 검색자료를 보고 응용해서 해설해봅니다)

msys64를 설치해서 pacman 명령어로 mingw를 설치할때, 여러 버전이 나옵니다.

pacman -Ss mingw-w64

이렇게 입력하면 mingw-w64 라고 이름에 붙어있는 프로그램들이나 라이브러리가 검색되는데요.

mingw-w64도 종류가 여럿이라 무엇을 설치하면 좋을지 확신이 안될때가 있습니다.

보통 문서들을 보면 mingw-w64-ucrt-x86_64-* 를 추천하는데요. mingw의 윈도우 64비트 버전, UCRT인 gcc와 같은 프로그램과 라이브러리를 의미합니다.

여기서 UCRT 부분이 위에 명령어로 입력한 목록에 뜨는데요. 다른 mingw-w64와 다른 점이 유의되죠.

UCRT는 Universal C Runtime의 줄임말로 C 표준을 지키고, MSVCRT (Microsoft Visual C++ Runtime)을 향상시킨 런타임에 의한다는 것을 의미합니다. Visual Studio 2015 또는 이후 버전에서 UCRT가 기본값이죠.

라즈베리파이 피코 C SDK와의 상성은 이런 용도가 주로 쓰입니다.

picotool의 소스코드를 윈도우 64비트에서 돌아가게 할때 컴파일 과정에서 쓰임
pioasm도 흡사한 용도
주의: uf2를 빌드하는 ARM GNU Toolchain에 포함된 컴파일러와 별도로 설치해야 함

이렇게 구별됩니다.

[RPI-PICO] 라즈베리파이 피코 2W에서 cmake 실행시 picotool 관련하여 cli.h에 cstdint를 추가해야 한다고 나올때

msys64로 mingw-w64-ucrt-x86_64-gcc 와 부속파일을 대충 설치하고 피코 2W 프로젝트를 빌드하면 아래와 같이 오류가 나타날 수 있습니다.

cmake -B build -S . -G Ninja -DPICO_PLATFORM=rp2350 -DPICO_BOARD=pico2_w 
cd build 
ninja 

아래와 같은 오류가 발생하고 컴파일 타임에 멈춥니다.

oldies-idols-stream/build/_deps/picotool-src/cli.h:22:1: note: 'int64_t' is defined in header '<cstdint>'; this is probably fixable by adding '#include <cstdint>' 
   21 | #include <limits> 
  +++ |+#include <cstdint> 
   22 |

이 경우 수동으로 늘 추가해야 하는데, 살펴보면 picotool 문제가 이전에 발생합니다.

이를 해결 하려면

https://forums.raspberrypi.com/viewtopic.php?t=384966

에서 해설하는 것을 참고로 해서 조치를 취해야 하는데요.

pacman --needed -S $MINGW_PACKAGE_PREFIX-{toolchain,cmake,libusb,arm-none-eabi-toolchain,make} git make
pacman -S mingw-w64-ucrt-x86_64-picotool

cli.h 오류는 위와 같은 명령어로 의존성을 해결하니 넘어갑니다 ^^

위와 같이 명령을 입력해서 하시구요 (msys64 필요)

환경변수로

picotool_DIR 을 C:\msys64\ucrt64\bin 으로 설정하고

vscode를 재시작해서 터미널을 닫고 다시 열어서 빌드를 하면 cli.h 관련 오류가 사라집니다.

전제 조건:
ARM GNU toolchain 설치와 설정이 잘 되어 있음 (환경변수와 vscode 확장 등등)
mingw-w64-ucrt-x86_64-* 설치와 설정이 잘 되어 있음 (위와 같이 하고 환경변수, vscode 설정 등등 리마인드 필요)
vscode 에서 라즈베리파이 피코 확장기능이 잘 설치되어 작동함
Vscode에서 CTRL+SHIFT+P 눌러서 CMake:scan for kits와 CMake:select a kit 실행

이정도 살펴보시면 됩니다.

시스템 오류시에 참고할만한 정보

시스템 오류는 개별적으로 보면 여러 이유가 있고, 패턴이 비슷해도 원인을 정확하게 특정하기가 애매한 주제 같기도 합니다. 우선 시스템에 남아있는 로그나 메모리 상태를 보기도 하는데, 오류가 해킹에 의한 것이라면 더욱 더 그러하네요. 이번에 불거진 SKT 해킹 사태도 늦게 대응이 되는 이유입니다.

이 경우 정말로 고약하게 고장이 나면 PC 메인보드도 날아가고 여러모로 충격이 큰데요.

이런 경우에 유발자가 누구인지 정확하게 아는게 추천됩니다.

그래서 그런지, 요즘은 부팅이 될때 제어권이 운영체제로 넘어가더라도, 하드웨어 제작사 (특히 메인보드) 의 로고를 보여주는 작동이 되는군요.

이 경우 특수한 경우 하드웨어, 소프트웨어 업체에서 해코지를 한 경우가 있겠으나 정말로 확신이 없다면 오히려 특정하는게 위해가 될 수 있습니다. 업체들이 도움을 주는 방향으로 고객도 대처하면 좋을때가 있네요. 이 이유는 해커들이 원인을 속이기 위해 큰 업체들과 분쟁을 일으키려는 조치를 해킹에 반영해서입니다.

수리기능사분들도 이를 아시기에 포괄적인 해법으로 추천하는데, 포괄적임이 해킹과 맞물리면 정말로 포괄적이 아니게 되어, 이후에 사기를 친 것으로 판단하기도 하고 가능성은 여럿입니다.

포괄적인 것의 예는 메인보드를 바꾸어야 할때, 오래된 기종이라 다른 부품도 바꾸어야 한다면, PC를 새로 맞추라고 하는데요. 이게 이후에 사용자가 알게 된게, UEFI 칩을 프로그래밍하면 된다는 정보를 입수할때 있을 수 있는 일이네요.

메인보드로 인한 오작동은 UEFI 매커니즘에 의해서이고, 이를 신품으로 바꾸면 일단 조치가 됩니다. (EFI파티션도 잘 조정해야함) 그래서 제일 간편하게 메인보드 교체를 하는 것인데, 이게 이후에 오해가 되네요.

제가 드는 한 유머는 이렇습니다.

버퍼링 안되게 해주세요..!!! (일반인)
음… 버퍼링이 되어야 하는데… (기술자)

이 경우 상식처럼 된 것이 서로를 적대시하게 하기도 해서 주의가 요청됩니다.

요즘 세태처럼 IT업계에서의 처리도 비지니스의 엄한 측면과 맞물려 정식화되거나, 고객들도 강하게 나오는 윤리관이 대세가 되면 해커가 한게 잘못인데, 업체와 고객 사이가 나빠지는 이유가 되는군요.

여기에 업체들이 참고하는 비지니스 논리도 그렇고, 고객들의 결정도 그렇고 정말로 상상을 넘어서는 이유들이 해킹이나 보안 관련해서 있습니다.

그러니 정말로 정확하게 검토하지 않으면 누군가라도 해가 되고 끝나는게 해킹 같애요.

리눅스도 사실 오작동 유발하는 오픈소스 이면때문에 기술자들이 애를 먹는데요. 이 경우에는 기술자들도 포괄적인 판단이 최선이고, 실력이 있으신 분들도 직접 살펴보지 않으면 안되고, 살펴보는 것도 기업 차원에서 오랫동안 연구해야 하는 전수되는 기능도 있고, 안티바이러스 업체분처럼 돕는 것이 생활이신 분들과도 소통하다보면 정보가 누락되기도 하는 등의 전개가 되는게 이 해킹 처리라, 정말로 얄궂은 것이네요.

일단 문제가 발생했고 일반적인 패턴에 근거한다면 고객지원 센터나 수리점에 맞기는게 제일 최선입니다.


어떤 경우, 메인보드 고장이 일어난 경우 이런 경우도 있습니다.

부품의 커넥터 접촉면 이상처럼 보이는 경우, 부품을 뺐다 끼면 되는 고장과 유사한 경우, 세번까지 시도하면 고쳐질 수 있습니다. 이는 보통 두번까지만 실험해보는 일반적인 실천때문인데요. 이 경우 전산학에 소질이 있지만 하드웨어에는 경험이 덜한 분들이 두번까지만 실험해보고 수리점에 가져가면, 세번째로 실험하는 것이라 고쳐질때, 같은 방법을 적용했는데도 두번째까지는 안통한 사용자들은 답답함도 느끼죠. (특히 실력이 의심되기도…) 이런 일이 겹치면 조심하는 태도가 무뎌지네요. 이런 심리적인 것도 해킹 대처에 있음을 알면 해킹 받는 상황에 대한 양해가 잘 이루어질 것입니다.

때로는 이 조치를 알아서, 세번째까지 확인하면 이상작동이 다시 돌아오게 설정도 되네요. 그러니 그냥 수리점에 맡기시는게 최선입니다. (이 경우 수리점에 맡겼다 = 실력없음처럼도 되어 문제네요)

[RPI-PICO] Level shifter

Level shifter는 전자회로에서 나가고 오는 전압 레벨을 핀마다 조정하는 장치를 뜻합니다. 연결된 회로마다 작동하는 전압이 다르다면 level shifter 설비를 해서 조정하게 됩니다. 제일 흔한 로직 레벨은 1.8V, 3.3V, 5V이구요. 보통 회로가 3.3V로 작동한다고 하면 서로 다른 전압을 3.3V로 조정한다는 의미가 됩니다. 다른 전압 입력이나 출력을 한다면요.

단방향과 양방향 level shifter가 존재하구요. 양방향은 또 여러 유형으로 나뉘는데 외부 신호를 감지하는 등의 작동으로 입력과 출력을 결정하는 차이가 있습니다.

SPI로 통신하는 microSD 카드 모듈 중에서는 level shifter 기능을 내장한 기종이 있네요.

level shifter 기능이 있는 모듈

제가 참고한 FatFS 응용 프로젝트의 이슈 게시판을 보면 위와 같은 모듈을 쓸때 3.3V 인가시 mount error 3이 발생하고, 5V인가시 mount error 1이 발생합니다. 프로젝트 저자에 의하면 level shifter가 라즈베리파이 피코에 내장되어 있는데 microSD 카드 모듈에 또 level shifter가 있어서 서로 겹쳐서 작동해서 발생하는 에러로, 아래와 같이 단순한 (?) 회로로 된 모듈로 바꾸라고 조언하네요.

level shifter 기능이 없는 모듈

실재로 바꿔보니 잘 작동합니다.

참고로 라즈베리파이 피코의 다른 GPIO의 전압은 3.3V로 조정하는게 좋은데, 나가는 전압이 5V인 핀도 있기는 합니다. 이 5V로 나가는 핀에 level shifter가 있는 모듈을 연결하면 마이크로파이썬으로 작업시 작동하는데, 3.3V로는 안됩니다. 그리고 피코 C SDK와 FatFS를 응용한 프로젝트로 하면 level shifter가 있는 모듈은 둘다 안되고 level shifter가 없는 모듈로 3.3V 연결시 되네요.

한가지 이상한 것은 라즈베리파이 피코는 3.3V로 GPIO가 운용된다고 하는게 정설이고, VSYS는 5V 입력핀이라고 하는데 제 경우 VSYS에 모듈 연결시 (level shifter있는 것으로) 작동합니다. (마이크로파이썬) VSYS가 5V를 출력하는 기능이 있을 것이라고 대략 추정되기도 하네요. 5V를 출력해서 모듈에 전원공급한다?

메모리 상태 문제인지 아니면 기존의 해설이 잘못된 건지 구별은 안했습니다. 안전을 위해 3.3V로 GPIO를 늘 운용하게 하려고 구축된 표현에서 VSYS의 기능이 입력핀이라고 회자되게 된건가 하는 생각도 드는데 여튼 위와 같이 작동합니다. 확실하게 구별은 안해봤네요. VBUS의 경우 USB도 작동하게 할때 전원을 피코에 입력하는 핀임은 확실하구요. VSYS는 핀에 연결된 장치에 5V 전원 연결을 하는 용도 같은데, 많은 자료에서 ‘input voltage’와 같이 강조점을 두어 표현하네요. 마이크로파이썬으로 운용시 VSYS에 모듈을 연결하고 5V 인가해서 작동하는 모듈이 위와 같이 있는데, 이게 혹시 제 호스트 PC나 피코 메모리 상태가 달라져서인지 아니면 VSYS가 모듈에 전원공급도 하는 기능인지는 자료가 안찾아집니다.

확실한 것은

  • 라즈베리파이 피코는 내부적으로 level shifting을 하기에 모듈에 level shifter가 있는 경우 작동을 안할 수 있다
  • 이를 고려해서 모듈을 구해서 써야 하는 경우가 있다
  • 피코 C SDK, FatFS와 같은 라이브러리를 쓰는 경우 위 두가지 사항을 잘 지켜야 한다

이 세가지네요.

The Raspberry Pi Pico’s VSYS output, when connected to a module, provides the primary power source to the module, typically 5V (or 0V if not powered). This VSYS power is then used to power the module’s onboard SMPS (Switch Mode Power Supply), which generates the 3.3V needed for the RP2040 microcontroller and its GPIO pins.

Elaboration:

VSYS as the main power input:

The VSYS pin on the Pico is the primary input for power, typically from a USB connection or a battery.

Voltage range:

VSYS can accept a voltage range of 1.8V to 5.5V.

Onboard SMPS:

The Pico’s onboard SMPS converts the VSYS voltage (typically 5V) into the 3.3V required by the RP2040.

Module power:

The 3.3V generated by the SMPS can then be used to power external modules or circuits connected to the Pico, provided the load doesn’t exceed the maximum output current (recommended to be under 300mA).

Alternative power sources:

Besides USB, the Pico can also be powered by batteries, such as a 9V battery or 3 AA batteries.

Power consumption:

The Pico’s power consumption varies depending on the program being run and the connected modules. A simple blink program may consume around 18mA, while more complex tasks like video playback can draw up to 95mA, according to the documentation.

이런 설명이 있네요.

VSYS도 모듈에 전원 공급을 한다는 해설인데 VSYS가 input voltage와 output voltage 기능이 다 있는 것인지 추론이 되는데 자료가 확실한게 잘 안찾아지네요. 설비를 해보면 작동합니다. level shifter가 있어도 5V로 인가하면 마이크로파이썬으로 되네요.

지금 추론은

  • VSYS가 입력, 출력 다 지원한다
  • 메모리 상태나 컴파일시 변조가 있어 헷갈린다
  • 실험을 해봐도 헷갈린다

이 상태인데 VSYS에 대한 의문이 풀리면 더 확신을 가지고 글을 쓰는게 될 것 같네요.


level shifter와 모듈에 대한 정보는 https://github.com/elehobica/pico_fatfs/issues/7 에서 참고하시길요.

[RPI-PICO] 라즈베리파이 피코 1 (RP2040) 부트롬 재컴파일해서 심기

가끔 라즈베리파이 피코가 오작동하는 것이 느껴질 때가 있습니다. 오작동이 아니더라도 튜닝을 의도한다든가 하는 위자드리급 고수시라면 한번쯤 해볼만한 작업입니다.

우선 RP2040용으로 나온 부트롬은 아래 명령어로 받아올 수 있습니다.

]# cd ~
]# mkdir devel
]# cd devel
]# git clone https://github.com/raspberrypi/pico-bootrom-rp2040

해당 사이트에 가보면 해설이 나오는데, 컴파일하는 컴파일러의 버전이 딱 맞아야 합니다. 이후 버전으로 하면 pico-bootrom-rp2040/bootrom/bootrom.ld 의 ROM이 16K로 되어 있는 량을 늘려야 해서, RP2040의 표준에 안맞게 됩니다. 16K를 늘리면 이후 버전 컴파일러로도 컴파일이 되지만, 그대로 두면 오류나고 멈추네요.

그리고 특기할만한 사실은 리눅스에서 작업하지 않으면 generated.h나 git_info.h 등의 헤더가 만들어지지 않습니다. 이는 pico-bootrom-rp2040에 루트에 포함된 CMakeLists.txt에서도 단서가 발견되는데요.

# todo is there a better way - this breaks on windows I presume
set_property(TARGET generate PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/generator/generate)
add_dependencies(generate generator)

set(GIT_INFO_H ${CMAKE_CURRENT_BINARY_DIR}/git_info.h)
set(GENERATED_H ${CMAKE_CURRENT_BINARY_DIR}/generated.h)

라고 되어 있는 부분에서 주석에 나온대로네요.

요약하자면

  • 리눅스에서 컴파일해야 한다
  • gcc-arm-none-eabi-9-2020-q2-update 버전을 써야 한다

입니다.

위에 예시한 명령어 이후에 입력할 워크플로우는 아래와 같습니다.

]# sudo apt install libusb-1.0-0-dev
]# cd ~/devel
]# git clone https://github.com/raspberrypi/picotool
]# cd picotool
]# cmake -B build -S .
]# cd build
]# make
]# make install

웹브라우저로 https://developer.arm.com/downloads/-/gnu-rm/9-2020-q2-update 이동
gcc-arm-none-eabi-9-2020-q2-update-x86_64-linux.tar.bz2 를 다운로드 받음 (호스트 PC가 리눅스이고 64비트 CPU인 경우)
다운받은 파일을 압축풀음

]# cp 압축푼 디렉토리 ~/devel/

이렇게 하면 ~/devel/압축푼 디렉토리 가 gcc-arm-none-eabi-9-2020-q2-update 디렉토리가 됩니다. 기존의 버전이 높은 arm gcc와 충돌이 없게 홈디렉토리에 압축을 풀었습니다. 압축푼대로 그냥 쓰면 됩니다.

다음으로 아래 명령어를 이어갑니다.

]# cd ~/devel/pico-bootrom-rp2040
]# vi CMakeLists.txt
# pico_sdk_init() 바로 아래에 아래 두라인을 추가 후 저장하고 나옴
set(CMAKE_C_COMPILER /home/bluenote/devel/압축푼디렉토리/bin/arm-none-eabi-gcc)
set(CMAKE_CXX_COMPILER /home/bluenote/devel/압축푼디렉토리/bin/arm-none-eabi-c++)
]# cmake -B build -S .
]# cd build
]# make

이렇게 하면 기본값으로 부트롬이 빌드되어 bootrom.bin 이 생성됩니다. 이 생성된 bin 파일을 라즈베리파이 피코에 심으세요.

BOOTSEL 모드로 라즈베리파이 피코를 연결
]# cd ~/devel/pico-bootrom-rp2040/build
]# picotool save bootrom.bin -t bin

이렇게 하면 빌드된 부트롬이 심어집니다. 정말로 심어진지는 미확인인데, 일단은 picotool로 save 명령을 실행하면 100% 꽉차고 오류없이 완료되네요.