#include #include #include #include #include #include #include #include #include unsigned int gpio_num = 0; #define DQ_IN gpio_direction_input(gpio_num) //#define DQ_OUT gpio_direction_output(gpio_num, gpio_get_value(gpio_num)) #define DQ_OUT gpio_direction_output(gpio_num, 1) #define DQ_H gpio_set_value(gpio_num, 1) #define DQ_L gpio_set_value(gpio_num, 0) #define DQ_V gpio_get_value(gpio_num) //spinlock_t lock; //#define DEFINE_MUTEX(LOCK) struct mutex mutex; //******************************** //功能:ds18b20复位 //******************************** int init_DS18B20(void) { unsigned int result; DQ_OUT; DQ_L; udelay(480); DQ_H; DQ_IN; udelay(65); result = DQ_V; udelay(240); //printk("ds18b20 init result %d,%d", result, DQ_V); udelay(180); return result; } //************************************* //功能:从ds18b20读一个字节的数据 //************************************* unsigned char read_char(void) { unsigned int i = 0; unsigned char dat = 0; // spin_lock(&lock); for(i=0; i<8; i++) { DQ_OUT; DQ_L; udelay(2); DQ_IN; dat >>= 1; udelay(2); if (DQ_V) dat |= 0x80; udelay(60); } //spin_unlock(&lock); return dat; } //************************************* //功能:向ds18b20写一个字节的数据 //************************************* void write_char(unsigned char dat) { unsigned int i = 0; //spin_lock(&lock); DQ_OUT; for(i=0; i<8; i++) { DQ_L; udelay(2); if (dat & 0x01) DQ_H; else DQ_L; udelay(60); DQ_H; udelay(2); dat >>= 1; } //spin_unlock(&lock); } int initDs18b20(unsigned int gpioNum) { gpio_num = gpioNum; //spin_lock_init(&lock); mutex_init(&mutex); return 0; } /*读取数据*/ void readDs18b20Data(unsigned char *value) { if (sizeof(&value) > 1){ value[0] = 0xff; value[1] = 0xff; } else { return; } mutex_lock(&mutex); // local_irq_disable(); if (init_DS18B20()) { // local_irq_enable(); mutex_unlock(&mutex); return; } write_char(0xCC); write_char(0x44); // local_irq_enable(); mdelay(750); //msleep(750); // local_irq_disable(); if (init_DS18B20()) { // local_irq_enable(); mutex_unlock(&mutex); return; } write_char(0xCC); write_char(0xBE); value[0] = read_char(); value[1] = read_char(); // local_irq_enable(); mutex_unlock(&mutex); //printk("%d: TH:%x, TL:%x, c:%x", gpio_num,read_char(),read_char(),read_char()); // mdelay(1); // init_DS18B20(); //write_char(0xB4); //DQ_OUT; //printk("%d: EC:%d", gpio_num,DQ_V); //write_char(0x4E); //write_char(0x64); //write_char(0x00); //write_char(0x7F); //init_DS18B20(); //write_char(0x48); } void freeDs18b20(void) { gpio_free(gpio_num); }