1.应用层代码
#include "head.h"
#include "user.h"
/*******根据温湿度传感器获取数据并将数据在数码管上显示精度在两位数*********/
int main(int argc, char const *argv[])
{int tem, hum;float tem_h, hum_h;int number = -1;// 用于将温湿度的数据读取传输到应用层int fd_i2c = open("/dev/si7006", O_RDWR);if (fd_i2c < 0){printf("si7006文件打开失败:%d\n", __LINE__);exit(-1);}// 用于将温湿度的组合数据传输到驱动层,控制数码管的亮灭int fd_spi = open("/dev/m74hc595", O_RDWR);if (fd_spi < 0){printf("m74hc595文件打开失败:%d\n", __LINE__);}while (1){/*******I2C做的事********/// 温湿度的数据ioctl(fd_i2c, GET_HUM, &hum);ioctl(fd_i2c, GET_TEM, &tem);// 网络字节序的转换hum = ntohs(hum);tem = ntohs(tem);// 将数字量转换成模拟量hum_h = 125.0 * hum / 65536 - 6;tem_h = 175.72 * tem / 65536 - 46.85;/*******SPI做的事********//*组个数字量模拟量*/number = (int)hum_h * 100 + (int)tem_h;// printf("number=%d\n",number);ioctl(fd_spi, GET_SHUMA1, number);// sleep(1);}return 0;
}
2.驱动层
2.1温湿度的采集
int i2c_read(char reg) // 传输的数据
{short value; // 发送的数据 因为温湿度占据2个字节char r_buf[] = {reg}; // 寄存器所在的地址int ret;// 封装消息struct i2c_msg r_msg[] = {[0] = {// 写信号的包装.addr = client1->addr, // 从机的地址.flags = 0, // 表示写.len = sizeof(r_buf), // 传输的数据大小.buf = r_buf, // 数据的首地址},[1] = {// 读信号的包装.addr = client1->addr, // 从机地址.flags = 1, // 表示读.len = 1,.buf = (char *)&value,},};// 信号包装好以后,开始调用数据发送函数ret = i2c_transfer(client1->adapter, r_msg, 2);if (ret != 2){printk("数据传输失败:%d\n", __LINE__);return -EIO;}return value;
}
2.2温湿度转发到用户层
if (cmd == GET_HUM || cmd == GET_TEM){int hum, tem;int ret = -1;switch (cmd){case GET_HUM:// 获取从机发过来的温度数据hum = i2c_read(0xE5);// 将数据发送到用户空间ret = copy_to_user((void *)arg, &hum, 4);if (ret < 0){printk("温度数据传输失败:%d\n", __LINE__);return 0;}break;case GET_TEM:tem = i2c_read(0xE3);// 将数据发送到用户空间ret = copy_to_user((void *)arg, &hum, 4);if (ret < 0){printk("温度数据传输失败%d\n:", __LINE__);return 0;}break;}}
2.3将用户层传输过来的数据,打印在数码管上
if (cmd == GET_SHUMA1){char buf[2]="";int shuma[4];shuma[0] = arg / 1000; // 千shuma[1] = arg % 1000 / 100; // 百shuma[2] = arg % 1000 % 100 / 10; // 十shuma[3] = arg % 1000 % 100 % 10; // 个for (k = 0; k < 500; k++){for (i = 0; i < 4; i++){buf[0] = 0x1 << i; // 控制哪个灯switch (shuma[i]){case 0:buf[1] = 0x3f;break;case 1:buf[1] = 0x06;break;case 2:buf[1] = 0x5D;break;case 3:buf[1] = 0x4F;break;case 4:buf[1] = 0x66;break;case 5:buf[1] = 0x6D;break;case 6:buf[1] = 0x7D;break;case 7:buf[1] = 0x07;break;case 8:buf[1] = 0x7F;break;case 9:buf[1] = 0x6F;break;}spi_write(spi1, buf, sizeof(buf)); }}}