首先在贸泽上找到传感器
打开手册
里面有个型号表,我用的就是iic协议,0~30psi(1psi=6895pa),
用RTThread Studio创建工程,开启iic
如果想打印iic通信的详细过程可以把debug message打开。
因为代码较少,这里就直接贴出整个main.c代码了
#include <rtthread.h>
#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>
#include "board.h"
#define I2C_BUS_NAME "i2c1" /* 传感器连接的I2C总线设备名称 */
#define PA2A3_ADDR 0x28 /* 从机地址 */
static struct rt_i2c_bus_device *i2c_bus = RT_NULL; /* I2C总线设备句柄 */
int temp_src=0,pre_src=0;//原始数据
int temperaturex100=0,pressurex100=0;//转换后的数据,温度扩大了100倍
#define csee_pin GET_PIN(B,3)
#define csadc_pin GET_PIN(B,2)
/* 读传感器寄存器数据 */
static rt_err_t read_regs(struct rt_i2c_bus_device *bus, rt_uint8_t len, rt_uint8_t *buf)
{
struct rt_i2c_msg msgs;
msgs.addr = PA2A3_ADDR;
msgs.flags = RT_I2C_RD;
msgs.buf = buf;
msgs.len = len;
/* 调用I2C设备接口传输数据 */
if (rt_i2c_transfer(bus, &msgs, 1) == 1)
{
return RT_EOK;
}
else
{
return -RT_ERROR;
}
}
int main(void)
{
/* 查找I2C总线设备,获取I2C总线设备句柄 */
i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(I2C_BUS_NAME);
if (i2c_bus == RT_NULL){
rt_kprintf("can't find %s device!\n", I2C_BUS_NAME);
return RT_ERROR;
}else{
rt_kprintf("i2c find %s device!\n",I2C_BUS_NAME);
}//0X28
rt_uint8_t temp[4]={0};
//rt_kprintf("START %s \n",temp);
read_regs( i2c_bus, 4, temp);
//rt_kprintf("AFTER 0: %x 1: %x 2: %d 3: %x\n",temp[0],temp[1],temp[2],temp[3]);//01100000001
temp_src=(temp[2]<<3)+((temp[3]&0xe0)>>5);//768
pre_src=(temp[0]&0x3f)<<8|temp[1];//7680+18
temperaturex100=(temp_src*20000/2047)-5000;
pressurex100=((pre_src-1638)*(30-0)*6895)/13107+(0);//6.895 30 13107
rt_kprintf("temperature %d.%d C \n pressure %d.%d kpa\n",temperaturex100/100,temperaturex100%100,pressurex100/1000,pressurex100%1000);
rt_pin_write(csee_pin, 1);
rt_pin_write(csee_pin, 0);
//inH2O =+- 5*259.014pa
int count = 1;
while (count++)
{
// read_regs( i2c_bus, 4, temp);
//
// temp_src=(temp[2]<<3)+((temp[3]&0xe0)>>5);//768
// pre_src=(temp[0]&0x3f)<<8|temp[1];//7680+18
// temperaturex100=(temp_src*20000/2047)-5000;
// pressurex100=((pre_src-1638)*(30-0)*6895)/13107+(0);//6.895 30 13107
//
// rt_kprintf("%d temperature %d.%d C \n pressure %d.%d kpa\n",count,temperaturex100/100,temperaturex100%100,pressurex100/1000,pressurex100%1000);
rt_thread_mdelay(2000);
}
return RT_EOK;
}
温度和压力转化有个公式,参考霍尼韦尔的I2C Communications with Honeywell Digital Output Pressure Sensors技术手册
有3种读取模式,我使用的第3种,就是全部读取。
byte1的前两位是状态位,00就是正常,byte1的后6位,和byte2一共有14位是数据,需要把byte1的后6位左移8位再加上byte2的8位共同合成压力数据
压力数据的计算公式,outputmax和outputmin都不变,pressuremax就是传感器测的最大值,我这里是30psi,同理pressuremin就是能测的最小值,我这里是0psi,代码中我计算扩大了100倍。
温度的更简单
按照这个来计算就行,贴的代码运行如下