### Initialize and Use USART Source: https://context7.com/openwch/ch32v307/llms.txt Shows how to initialize the debug USART and perform manual configuration for custom serial communication. Includes examples for sending and receiving data bytes. ```c #include "debug.h" // Initialize system and debug USART at 115200 baud NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); SystemCoreClockUpdate(); Delay_Init(); USART_Printf_Init(115200); // Print system information printf("SystemClk:%d\r\n", SystemCoreClock); printf("ChipID:%08x\r\n", DBGMCU_GetCHIPID()); // Manual USART configuration example USART_InitTypeDef USART_InitStructure = {0}; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_Init(USART1, &USART_InitStructure); USART_Cmd(USART1, ENABLE); // Send single byte USART_SendData(USART1, 0x55); while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); // Receive single byte while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); uint16_t received = USART_ReceiveData(USART1); ``` -------------------------------- ### Initialize ADC with DMA in C Source: https://context7.com/openwch/ch32v307/llms.txt Configures ADC1 for continuous conversion on PA1 and sets up DMA1 Channel 1 for data transfer. Requires calibration sequence before starting conversion. ```c #include "debug.h" u16 TxBuf[1024]; s16 Calibrattion_Val = 0; void ADC_Function_Init(void) { ADC_InitTypeDef ADC_InitStructure = {0}; GPIO_InitTypeDef GPIO_InitStructure = {0}; // Enable clocks RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); RCC_ADCCLKConfig(RCC_PCLK2_Div8); // ADC clock = PCLK2/8 // Configure PA1 as analog input GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; GPIO_Init(GPIOA, &GPIO_InitStructure); // Configure ADC ADC_DeInit(ADC1); ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; ADC_InitStructure.ADC_ScanConvMode = DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = 1; ADC_Init(ADC1, &ADC_InitStructure); ADC_DMACmd(ADC1, ENABLE); ADC_Cmd(ADC1, ENABLE); // Calibration sequence ADC_BufferCmd(ADC1, DISABLE); ADC_ResetCalibration(ADC1); while(ADC_GetResetCalibrationStatus(ADC1)); ADC_StartCalibration(ADC1); while(ADC_GetCalibrationStatus(ADC1)); Calibrattion_Val = Get_CalibrationValue(ADC1); } // DMA configuration for ADC void DMA_Tx_Init(DMA_Channel_TypeDef* DMA_CHx, u32 ppadr, u32 memadr, u16 bufsize) { DMA_InitTypeDef DMA_InitStructure = {0}; RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); DMA_DeInit(DMA_CHx); DMA_InitStructure.DMA_PeripheralBaseAddr = ppadr; DMA_InitStructure.DMA_MemoryBaseAddr = memadr; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC; DMA_InitStructure.DMA_BufferSize = bufsize; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; DMA_InitStructure.DMA_Mode = DMA_Mode_Normal; DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh; DMA_InitStructure.DMA_M2M = DMA_M2M_Disable; DMA_Init(DMA_CHx, &DMA_InitStructure); } // Start ADC with DMA ADC_Function_Init(); DMA_Tx_Init(DMA1_Channel1, (u32)&ADC1->RDATAR, (u32)TxBuf, 1024); DMA_Cmd(DMA1_Channel1, ENABLE); ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5); ADC_SoftwareStartConvCmd(ADC1, ENABLE); ``` -------------------------------- ### Configure GPIO Pins Source: https://context7.com/openwch/ch32v307/llms.txt Demonstrates initializing GPIO ports, setting pin modes, and performing read/write operations. Requires enabling the peripheral clock via RCC before initialization. ```c #include "debug.h" // GPIO initialization structure GPIO_InitTypeDef GPIO_InitStructure = {0}; // Enable GPIOA peripheral clock RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // Configure PA0 as push-pull output at 50MHz GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); // Toggle GPIO pin GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_SET); // Set pin high Delay_Ms(250); GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_RESET); // Set pin low // Read input pin state uint8_t pinState = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1); // Configure multiple pins as analog input (for ADC) GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; GPIO_Init(GPIOA, &GPIO_InitStructure); // GPIO Mode options: // GPIO_Mode_AIN - Analog input // GPIO_Mode_IN_FLOATING - Floating input // GPIO_Mode_IPD - Input pull-down // GPIO_Mode_IPU - Input pull-up // GPIO_Mode_Out_OD - Open-drain output // GPIO_Mode_Out_PP - Push-pull output // GPIO_Mode_AF_OD - Alternate function open-drain // GPIO_Mode_AF_PP - Alternate function push-pull ``` -------------------------------- ### Initialize PWM Output on TIM1 in C Source: https://context7.com/openwch/ch32v307/llms.txt Configures TIM1 to generate a PWM signal on PA8. The frequency is determined by the system clock, prescaler, and auto-reload register values. ```c #include "debug.h" void TIM1_PWMOut_Init(u16 arr, u16 psc, u16 ccp) { GPIO_InitTypeDef GPIO_InitStructure = {0}; TIM_OCInitTypeDef TIM_OCInitStructure = {0}; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure = {0}; // Enable clocks RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE); // Configure PA8 (TIM1_CH1) as alternate function push-pull GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); // Configure timer base TIM_TimeBaseInitStructure.TIM_Period = arr; // Auto-reload value TIM_TimeBaseInitStructure.TIM_Prescaler = psc; // Prescaler TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure); // Configure PWM output TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = ccp; // Duty cycle value TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC1Init(TIM1, &TIM_OCInitStructure); // Enable outputs and start timer TIM_CtrlPWMOutputs(TIM1, ENABLE); TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Disable); TIM_ARRPreloadConfig(TIM1, ENABLE); TIM_Cmd(TIM1, ENABLE); } // Initialize PWM: Period=100, Prescaler=48000, Duty=50% // PWM frequency = SystemCoreClock / (psc+1) / (arr+1) // 144MHz / 48000 / 100 = 30Hz TIM1_PWMOut_Init(100-1, 48000-1, 50); ``` -------------------------------- ### Utilize Timer-based Delay Functions Source: https://context7.com/openwch/ch32v307/llms.txt Provides microsecond and millisecond delay capabilities using the SysTick timer, requiring initialization via Delay_Init(). ```c #include "debug.h" // Initialize delay functions (required before use) Delay_Init(); // Microsecond delay Delay_Us(100); // 100 microseconds // Millisecond delay Delay_Ms(500); // 500 milliseconds // Typical main() initialization sequence int main(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); // Set interrupt priority grouping SystemCoreClockUpdate(); // Update SystemCoreClock variable Delay_Init(); // Initialize delay functions USART_Printf_Init(115200); // Initialize debug UART printf("SystemClk:%d\r\n", SystemCoreClock); printf("ChipID:%08x\r\n", DBGMCU_GetCHIPID()); // Application code here while(1); } ``` -------------------------------- ### Configure and Access I2C EEPROM Source: https://context7.com/openwch/ch32v307/llms.txt Initializes I2C2 and provides helper functions for reading and writing single bytes to an AT24CXX EEPROM. Uses open-drain GPIO configuration for SCL and SDA lines. ```c #include "debug.h" void IIC_Init(u32 bound, u16 address) { GPIO_InitTypeDef GPIO_InitStructure = {0}; I2C_InitTypeDef I2C_InitTSturcture = {0}; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE); // Configure I2C I2C_InitTSturcture.I2C_ClockSpeed = bound; // 100000 for 100kHz I2C_InitTSturcture.I2C_Mode = I2C_Mode_I2C; I2C_InitTSturcture.I2C_DutyCycle = I2C_DutyCycle_2; I2C_InitTSturcture.I2C_OwnAddress1 = address; I2C_InitTSturcture.I2C_Ack = I2C_Ack_Enable; I2C_InitTSturcture.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; I2C_Init(I2C2, &I2C_InitTSturcture); I2C_Cmd(I2C2, ENABLE); // Configure I2C2 pins: SCL(PB10), SDA(PB11) as open-drain GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); } // Read one byte from EEPROM u8 AT24CXX_ReadOneByte(u16 ReadAddr) { u8 temp = 0; while(I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY) != RESET); I2C_GenerateSTART(I2C2, ENABLE); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT)); I2C_Send7bitAddress(I2C2, 0xA0, I2C_Direction_Transmitter); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); I2C_SendData(I2C2, (u8)(ReadAddr & 0x00FF)); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); I2C_GenerateSTART(I2C2, ENABLE); // Repeated start while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT)); I2C_Send7bitAddress(I2C2, 0xA0, I2C_Direction_Receiver); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)); while(I2C_GetFlagStatus(I2C2, I2C_FLAG_RXNE) == RESET) I2C_AcknowledgeConfig(I2C2, DISABLE); temp = I2C_ReceiveData(I2C2); I2C_GenerateSTOP(I2C2, ENABLE); return temp; } // Write one byte to EEPROM void AT24CXX_WriteOneByte(u16 WriteAddr, u8 DataToWrite) { while(I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY) != RESET); I2C_GenerateSTART(I2C2, ENABLE); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT)); I2C_Send7bitAddress(I2C2, 0xA0, I2C_Direction_Transmitter); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); I2C_SendData(I2C2, (u8)(WriteAddr & 0x00FF)); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); if(I2C_GetFlagStatus(I2C2, I2C_FLAG_TXE) != RESET) I2C_SendData(I2C2, DataToWrite); while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); I2C_GenerateSTOP(I2C2, ENABLE); } ``` -------------------------------- ### Configure and Use SPI Full-Duplex Communication Source: https://context7.com/openwch/ch32v307/llms.txt Initializes SPI1 in master mode and performs a full-duplex data transfer. Requires GPIO and SPI clock enablement via RCC. ```c #include "debug.h" u16 TxData[18] = {0x0101, 0x0202, 0x0303, 0x0404, 0x0505, 0x0606, 0x1111, 0x1212, 0x1313, 0x1414, 0x1515, 0x1616, 0x2121, 0x2222, 0x2323, 0x2424, 0x2525, 0x2626}; u16 RxData[18]; void SPI_FullDuplex_Init(void) { GPIO_InitTypeDef GPIO_InitStructure = {0}; SPI_InitTypeDef SPI_InitStructure = {0}; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_SPI1, ENABLE); // Configure SPI1 pins: SCK(PA5), MISO(PA6), MOSI(PA7) // Master mode: SCK and MOSI as AF push-pull, MISO as floating input GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); // Configure SPI SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_LSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI1, &SPI_InitStructure); SPI_Cmd(SPI1, ENABLE); } // SPI data transfer u8 i = 0, j = 0; while((i < 18) || (j < 18)) { if(i < 18 && SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) != RESET) { SPI_I2S_SendData(SPI1, TxData[i++]); } if(j < 18 && SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) != RESET) { RxData[j++] = SPI_I2S_ReceiveData(SPI1); } } ``` -------------------------------- ### Implement Ethernet TCP Server Source: https://context7.com/openwch/ch32v307/llms.txt Configures a TCP listening socket and handles connection, disconnection, and data reception events using the WCHNET stack. ```c #include "eth_driver.h" u8 MACAddr[6]; u8 IPAddr[4] = {192, 168, 1, 10}; u8 GWIPAddr[4] = {192, 168, 1, 1}; u8 IPMask[4] = {255, 255, 255, 0}; u16 srcport = 1000; u8 SocketIdForListen; u8 socket[WCHNET_MAX_SOCKET_NUM]; u8 SocketRecvBuf[WCHNET_MAX_SOCKET_NUM][RECE_BUF_LEN]; void WCHNET_CreateTcpSocketListen(void) { SOCK_INF TmpSocketInf; memset((void *)&TmpSocketInf, 0, sizeof(SOCK_INF)); TmpSocketInf.SourPort = srcport; TmpSocketInf.ProtoType = PROTO_TYPE_TCP; u8 i = WCHNET_SocketCreat(&SocketIdForListen, &TmpSocketInf); mStopIfError(i); i = WCHNET_SocketListen(SocketIdForListen); mStopIfError(i); } void WCHNET_HandleSockInt(u8 socketid, u8 intstat) { if(intstat & SINT_STAT_RECV) { // Process received data u32 len; u8 i = WCHNET_SocketSend(socketid, (u8 *)SocketInf[socketid].RecvReadPoint, &len); if(i == WCHNET_ERR_SUCCESS) WCHNET_SocketRecv(socketid, NULL, &len); } if(intstat & SINT_STAT_CONNECT) { WCHNET_ModifyRecvBuf(socketid, (u32)SocketRecvBuf[socketid], RECE_BUF_LEN); printf("TCP Connect Success\r\n"); } if(intstat & SINT_STAT_DISCONNECT) printf("TCP Disconnect\r\n"); } int main(void) { SystemCoreClockUpdate(); Delay_Init(); USART_Printf_Init(115200); WCHNET_GetMacAddr(MACAddr); u8 i = ETH_LibInit(IPAddr, GWIPAddr, IPMask, MACAddr); mStopIfError(i); memset(socket, 0xff, WCHNET_MAX_SOCKET_NUM); WCHNET_CreateTcpSocketListen(); while(1) { WCHNET_MainTask(); if(WCHNET_QueryGlobalInt()) { u8 intstat = WCHNET_GetGlobalInt(); if(intstat & GINT_STAT_SOCKET) { for(u16 i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { u8 socketint = WCHNET_GetSocketInt(i); if(socketint) WCHNET_HandleSockInt(i, socketint); } } } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.