我采用了两个线程,主要实现两个功能,一个是根据超声波采集到的距离开关灯,另一个是根据采集到的温度使蜂鸣器响,但是有bug,只能亮灭灯,蜂鸣器不响,我初步感觉是因为不能同时read?但是每一个功能单独测试均可通过,合一块就不行了,还望解答。
代码如下
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <linux/fb.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <dirent.h>
#include <stdlib.h>
#include <fcntl.h>
#include <poll.h>
#include <linux/videodev2.h>
#include <sys/time.h>
#include <assert.h>
#include <sys/select.h>
#include <stdlib.h>
#include <linux/fb.h>
#include <linux/ioctl.h>
#define SR04_DEVICE "/dev/zszsr04" /* 超声波传感器设备文件 */
#define ds18b20_DEVICE "/dev/myds18b20" /* 温湿度传感器设备文件 */
#define led "/dev/myled"/*led*/
#define buffer "/dev/zszbuffer"
#define on 1
#define off 0
#define ring 1
#define unring 0
int sr04_fd;
int ds18b20_fd;
int led_fd;
int buffer_fd;
void* sr04_thread(void* arg) {
led_fd = open(led, O_RDWR);
int err1;
if (led_fd < 0)
{
perror("can not open led device");
pthread_exit(NULL);
}
sr04_fd = open(SR04_DEVICE, O_RDWR);
if (sr04_fd == -1) {
perror("Failed to open sr04 device");
pthread_exit(NULL);
}
while (1) {
int ns;
int data;
if (read(sr04_fd, &ns, sizeof(ns)) != sizeof(ns)) {
perror("Failed to read sr04 data");
continue;
}
printf("Distance: %d mm\n", ns * 340 / 2 / 1000000);
data=ns * 340 / 2 / 1000000;
if(data>100){
err1=ioctl(led_fd,off);
printf("%d\n",err1);
}
else{
err1= ioctl(led_fd,on);
printf("%d\n",err1);
}
sleep(1);
}
}
void* ds18b20_thread(void* arg) {
buffer_fd = open(buffer, O_RDWR);
int err_buffer;
if (buffer_fd < 0)
{
perror("can not open buffer device");
pthread_exit(NULL);
}
ds18b20_fd = open(ds18b20_DEVICE, O_RDWR);
if (ds18b20_fd == -1) {
perror("Failed to open ds18b20 device");
pthread_exit(NULL);
}
while (1) {
// 读取温度数据
unsigned char data[5];
unsigned int integer;
unsigned char decimal;
unsigned int tem;
if (read(ds18b20_fd, data, 5) == 5)
{
integer = data[0] | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
decimal = data[4];
printf("get temprature: %d.%d\n", integer, decimal);
}else
{
printf("get temprature: -1\n");
continue;
}
tem=integer;
if(tem>28){
err_buffer=ioctl(buffer_fd,ring);
printf("%d\n",err_buffer);
}else{
err_buffer= ioctl(buffer_fd,unring);
printf("%d\n",err_buffer);
}
sleep(1);
}
}
int main(int argc ,char *argv[])
{
int error;
int cnt=0;
int i=0;
int ListNum;
fd_set readfds;
pthread_t tid1;
pthread_t tid2;
if(argc!=2)
{
printf("./app /dev/video1\n");
return -1;
}
pthread_create(&tid1, NULL, sr04_thread, NULL);
pthread_detach(tid1);
pthread_create(&tid2, NULL, ds18b20_thread, NULL);
pthread_detach(tid2);
// 创建温度传感器线程
return 0;
}