GD32L23X官方例程没有I2C驱动实例,网上也不太好找,最后整合多方资料,完成了GD32L233KBT6+AHT20的I2C驱动调试。
一、环境准备
- VSCode+EIDE基础工程(参考GD32L233KBT6开源编译环境搭建)
- AHT20官方驱动github下载(aht20 drivers)
二、I2C移植
2.1 拷贝文件
拷贝三个文件到工程中:
- driver_aht20_read_test.c//里面有测试代码可以直接调用,包括初始化和读温湿度
- driver_aht20.c//aht20驱动
- driver_aht20_interface_template.c//aht20的i2c底层实现接口
- 上面三个文件对应的头文件
2.2 移植接口
在i2c读的接口中,需要注意一个地方就是收完字节流后,要加一个延时,不然gd32的stop信号无法正常发出,因此特意增加了一个aht20_interface_delay_us()函数。
硬件信息是:PB6-SCL, PB7-SDA,通过AF8映射到I2C1。
driver_aht20_interface_template.c是一个空的框架模板,在gd32上实现后的代码如下:
/**
* Copyright (c) 2015 - present LibDriver All rights reserved
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file driver_aht20_interface_template.c
* @brief driver aht20 interface template source file
* @version 1.0.0
* @author Shifeng Li
* @date 2022-10-31
*
* <h3>history</h3>
* <table>
* <tr><th>Date <th>Version <th>Author <th>Description
* <tr><td>2022/10/31 <td>1.0 <td>Shifeng Li <td>first upload
* </table>
*/
#include "driver_aht20_interface.h"
#include "gd32l23x_i2c.h"
#include "systick.h"
static void aht20_interface_delay_us(uint32_t us);
/**
* @brief interface iic bus init
* @return status code
* - 0 success
* - 1 iic init failed
* @note none
*/
uint8_t aht20_interface_iic_init(void)
{
// 初始化 I2C1
rcu_periph_clock_enable(RCU_I2C1);
rcu_periph_clock_enable(RCU_GPIOB);
//PB6,PB7通过AF4映射为I2C1
gpio_af_set(GPIOB, GPIO_AF_8, GPIO_PIN_6);//I2C1_SCL
gpio_af_set(GPIOB, GPIO_AF_8, GPIO_PIN_7);//I2C1_SDA
gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_6);
gpio_output_options_set(GPIOB, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, GPIO_PIN_6);
gpio_mode_set(GPIOB,