程序代码
main.c
uint8_t WriteBuffer[2*BufferSize] = {1,2,3,4,5,6,7,0}; //需要写的数据在WriteBuffer当中 uint8_t ReadBuffer[2*BufferSize]={0}; //读出来的数据放进ReadBuffer当中 uint8_t i; uint8_t data_addr = 0x01;/* USER CODE END 0 *///重定向printf()到串口发送和接收,方便应用int fputc(int ch, FILE *f){ uint8_t temp[1] = {ch}; HAL_UART_Transmit(&huart1, temp, 1, 0xffff);return ch;}//重定向scanf()函数和getchar()函数,方便应用int fgetc(FILE * f){ uint8_t ch = 0; HAL_UART_Receive(&huart1,&ch, 1, 0xffff); return ch;}/** * [url=home.php?mod=space&uid=247401]@brief[/url] The application entry point. * @retval int */int main(void){ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash inteRFace and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ AT_24c02_int(); for(i=0;i<BufferSize;i++) { AT_24c02_write_data(data_addr++,WriteBuffer); HAL_Delay(10);//写完一个字节的数据要记得延时10ms左右,否则会写错 } HAL_Delay(10); data_addr = 0x01; for(i=0;i<BufferSize;i++) { ReadBuffer = AT_24c02_read_data(data_addr++); //HAL_Delay(10); } /* 测试输出 */ for(i=0;i<BufferSize; i++) { printf("0x%02X\n ",ReadBuffer); //HAL_Delay(1); } while(1) { /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */}
24C02.c
void AT_24c02_int(void){ IIC_Init();}//data_addr 字节地址//data 数据void AT_24c02_write_data(uint8_t data_addr,uint8_t data){ IIC_Start(); IIC_Send_Byte(0xa0); IIC_Wait_Ack(); IIC_Send_Byte(data_addr); IIC_Wait_Ack(); IIC_Send_Byte(data); IIC_Wait_Ack(); IIC_Stop();}uint8_t AT_24c02_read_data(uint8_t data_addr){ uint8_t data=0; IIC_Start(); IIC_Send_Byte(0xa0); IIC_Wait_Ack(); IIC_Send_Byte(data_addr); IIC_Wait_Ack(); IIC_Start(); IIC_Send_Byte(0xa1); IIC_Wait_Ack(); data = IIC_Read_Byte(); IIC_NAck(); IIC_Stop(); return data; }
|