一、什么是“软件I2C”和“硬件I2C”?
硬件I2C:对应芯片上的I2C外设,有相应的I2C驱动电路,其所使用的I2C管脚也是专用的,因而效率要远高于软件模拟的I2C;一般也较为稳定,但是程序较为繁琐。硬件I2C是直接调用内部寄存器进行配置;而软件I2C是没有寄存器这个概念的。
软件I2C:一般是使用GPIO管脚,用软件控制SCL,SDA线输出高低电平,模拟I2C协议的时序。
二、基于AHT20的温湿度数据采集
(1)实验环境:
硬件:
温湿度传感器:AHT20
开发板:STM32F103系列
软件:keil
(2)实验内容:
每隔2秒钟采集一次温湿度数据,并通过串口发送到上位机(win10)。
(3)代码实现:
相关资料链接:http://www.aosong.com/class-36.html
主要代码:
AHT20芯片读取数据:
void read_AHT20(void)
{
uint8_t i;
for(i=0; i<6; i++)
{
readByte[i]=0;
}
I2C_Start();//I2C启动
I2C_WriteByte(0x71);//I2C写数据
ack_status = Receive_ACK();//收到的应答信息
readByte[0]= I2C_ReadByte();//I2C读取数据
Send_ACK();//发送应答信息
readByte[1]= I2C_ReadByte();
Send_ACK();
readByte[2]= I2C_ReadByte();
Send_ACK();
readByte[3]= I2C_ReadByte();
Send_ACK();
readByte[4]= I2C_ReadByte();
Send_ACK();
readByte[5]= I2C_ReadByte();
SendNot_Ack();
//Send_ACK();
I2C_Stop();//I2C停止函数
//判断读取到的第一个字节是不是0x08,0x08是该芯片读取流程中规定的,如果读取过程没有问题,就对读到的数据进行相应的处理
if( (readByte[0] & 0x68) == 0x08 )
{
H1 = readByte[1];
H1 = (H1<<8) | readByte[2];
H1 = (H1<<8) | readByte[3];
H1 = H1>>4;
H1 = (H1*1000)/1024/1024;
T1 = readByte[3];
T1 = T1 & 0x0000000F;
T1 = (T1<<8) | readByte[4];
T1 = (T1<<8) | readByte[5];
T1 = (T1*2000)/1024/1024 - 500;
AHT20_OutData[0] = (H1>>8) & 0x000000FF;
AHT20_OutData[1] = H1 & 0x000000FF;
AHT20_OutData[2] = (T1>>8) & 0x000000FF;
AHT20_OutData[3] = T1 & 0x000000FF;
}
else
{
AHT20_OutData[0] = 0xFF;
AHT20_OutData[1] = 0xFF;
AHT20_OutData[2] = 0xFF;
AHT20_OutData[3] = 0xFF;
printf("读取失败!!!");
}
printf("\r\n");
printf("温度:%d%d.%d",T1/100,(T1/10)%10,T1%10);
printf("湿度:%d%d.%d",H1/100,(H1/10)%10,H1%10);
printf("\r\n");
}
(4)结果显示:
三、在Ardunio完成STM32的串口通信
(1)实验环境:
硬件:
主控芯片:STM32F103RCT6
USB转串口
野火MINI STM32开发板
软件:
Arduino IDE 1.8.12
(2)代码编写
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);//设置串口的波特率
pinMode(PC2,OUTPUT);//PC2是蓝色的,PC2表示LED的接口,还有一个是PC3
}
int flag=1;//串口发送标志位,1表示发送,0表示停止发送
void loop() {
// put your main code here, to run repeatedly:
if (flag == 1)
{
Serial.println("Hello World!");
digitalWrite(PC2, HIGH); //LED灭
delay(500); // 延时
digitalWrite(PC2, LOW); //LED亮
delay(500); //延时
}
stopSendData();
}
void stopSendData()
{
String stopflag="stop!";//停止发送数据信号
String receivedata="";//存放接受到的数据
while(Serial.available()>0)//判断串口是否还有数据
{
receivedata=Serial.readString();//读取接收到的数据
}
if(receivedata==stopflag)//判断接收到的数据是否为停止发送数据的信号
{
flag=0;
}
}
运行时可能出现如下错误,是因为没有下载Arduino SAM开发板,需要在选项栏工具-开发板-开发板管理器,下载安装Arduino SAM开发板。
再运行代码看看
四、参考
1、https://blog.csdn.net/qq_43279579/article/details/111597278
2、https://blog.csdn.net/hhhhhh277523/article/details/111397514