openwch / ch32v003

CH32V003 is an ultra-cheap RISC-V MCU with 2KB SRAM, 16KB flash, and up to 18 GPIOs that sells for under $0.10
373 stars 56 forks source link

Peripheral Example: I2C Slave (Interrupts) #46

Open darkomenz opened 1 month ago

darkomenz commented 1 month ago

Can someone post a example of how to use the I2C Peripheral as a I2C Slave driven by Interrupts instead of polling?

darkomenz commented 1 month ago

Looking over the existing samples I was able to come up with this code however it does not appear to be working properly.

`

include

void IIC_Init(u32 frequency, u16 address) { GPIO_InitTypeDef GPIO_InitStructure = {0}; I2C_InitTypeDef I2C_InitStructure = {0}; NVIC_InitTypeDef NVIC_InitStruct = {0};

// Step 1: Enable clocks for AFIO, GPIOC and I2C1
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOC, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);

// Step 2: Initialize GPIO for I2C1
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_30MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);

// Step 3: Initialize I2C1 peripheral
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_OwnAddress1 = address;
I2C_InitStructure.I2C_ClockSpeed = frequency;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_Init(I2C1, &I2C_InitStructure);

// Step 4: NVIC configuration for I2C interrupts
NVIC_InitStruct.NVIC_IRQChannel = I2C1_EV_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);

// Step 5: Configure I2C interrupts
I2C_ITConfig(I2C1, I2C_IT_EVT, ENABLE);
NVIC_EnableIRQ(I2C1_EV_IRQn);

// Step 6: Enable I2C peripheral
I2C_Cmd(I2C1, ENABLE);

}

void I2C1_IRQHandler(void) attribute((interrupt("WCH-Interrupt-fast"))); void I2C1_IRQHandler(void) { printf("I2C1_IRQHandler\r\n"); }

// Interrupt Service Routine for I2C1 Event void I2C1_EV_IRQHandler(void) attribute((interrupt("WCH-Interrupt-fast"))); void I2C1_EV_IRQHandler(void) { printf("I2C1_EV_IRQHandler\r\n"); } // Interrupt Service Routine for I2C1 Error void I2C1_ER_IRQHandler(void) attribute((interrupt("WCH-Interrupt-fast"))); void I2C1_ER_IRQHandler(void) { printf("I2C1_ER_IRQHandler\r\n"); }

int main(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); SystemCoreClockUpdate(); Delay_Init();

#if (SDI_PRINT == SDI_PR_OPEN)
    SDI_Printf_Enable();
#else
    USART_Printf_Init(115200);
#endif
printf("SystemClk: %ldhz\r\n", SystemCoreClock);

IIC_Init(100000, 0x02);
printf("I2C: Enabled!\r\n");

while (true)
{
    __WFI();  // Wait for Interrupt (low power mode)
}

} `