zoukankan      html  css  js  c++  java
  • 温湿度传感器dht11的lcd显示[嵌入式系统]

                                夏任务105:做一个桌面温湿度计

    http://www.cnblogs.com/zxRPI/archive/2013/03/03/2941303.html

    实验要求

    用RPi采集温度、湿度和气压传感器的数据,在LCD显示

    实验工具:

    Raspberry Pi Model B主机,

    8G c10 SD卡,

    pl2303串口转usb线,

    USB充电线,

    电源需自备5v 1A电源充电头一个

    PC机一台(这里用的操作系统是windows7 64bit旗舰版)

    dht11温湿度传感器

    LED面板

    实验步骤:

    1. 连接dht11温度传感器如图所示

     

    DHT11引脚说明:

    Pin

    名称

    树莓派接口

    注释

    1

    VDD

    3.3V Power

    供电3~5.5V

    2

    DATA

    GPIO4

    串行数据总线

    3

    NC

    悬空

    空脚

    4

    GND

    Ground

    接地

    LCD的连接方法参考了李凡希学长的Blog:

    http://www.freemindworld.com/blog/2013/130310_raspberry_pi_with_lcd.shtml

    2在树莓派上安装树莓派的GPIO驱动库wIring pi,:教程见:http://blog.csdn.net/liang890319/article/details/8677437

    3编写驱动代码dht11.c:

    #include <wiringPi.h>

    #include <stdio.h>

    #include <stdlib.h>

    typedef unsigned char uint8;

    typedef unsigned int  uint16;

    typedef unsigned long uint32;

    #define HIGH_TIME 32

    int wiringPiSetup (void) ;

    int pinNumber = 7;  //use gpio1 to read data

    uint32 databuf;

    uint8 readSensorData(void)

    {

        uint8 crc;

        uint8 i;

        pinMode(pinNumber,OUTPUT); // set mode to output

        digitalWrite(pinNumber, 0); // output a high level

        delay(25);

        digitalWrite(pinNumber, 1); // output a low level

        pinMode(pinNumber, INPUT); // set mode to input

        pullUpDnControl(pinNumber,PUD_UP);

        delayMicroseconds(27);

        if(digitalRead(pinNumber)==0) //SENSOR ANS

           {

             while(!digitalRead(pinNumber)); //wait to high

          for(i=0;i<32;i++)

           {

           while(digitalRead(pinNumber)); //data clock start

           while(!digitalRead(pinNumber)); //data start

              delayMicroseconds(HIGH_TIME);

              databuf*=2;

               if(digitalRead(pinNumber)==1) //1

               {

                    databuf++;

               }

            }

          for(i=0;i<8;i++)

           {

           while(digitalRead(pinNumber)); //data clock start

           while(!digitalRead(pinNumber)); //data start

              delayMicroseconds(HIGH_TIME);

              crc*=2;

              if(digitalRead(pinNumber)==1) //1

               {

                    crc++;

               }

            }

        return 1;

           }

       else

            {

            return 0;

             }

    }

    int main (void)

    {

      printf("Use GPIO1 to read data!\n");

      if (-1 == wiringPiSetup()) {

        printf("Setup wiringPi failed!");

        return 1;

      }

      pinMode(pinNumber, OUTPUT); // set mode to output

      digitalWrite(pinNumber, 1); // output a high level

      printf("Enter OS——-\n");

      int i;

      for(i = 0; i < 2; i++)

      {

        pinMode(pinNumber,OUTPUT); // set mode to output

        digitalWrite(pinNumber, 1); // output a high level

        delay(1000);

        if(readSensorData())

        {

           printf("Congratulations ! Sensor data read ok!\n");

           printf("RH:%d.%d\n",(databuf>>24)&0xff,(databuf>>16)&0xff);

           printf("TMP:%d.%d\n",(databuf>>8)&0xff,databuf&0xff);

           databuf=0;

         }

        else

         {

            printf("Sorry! Sensor dosent ans!\n");

           databuf=0;

          }

      }

      return 0;

    }

    4编译运行该代码,获得温湿度数据:

     

      从结果可得:

        温度为26.0摄氏度

        湿度为44.0%

    5。接下来是LCD显示数据:

    LCD显示模块led_dht11.pyd 参考了git上的Adafruit_CharLCD()代码,主要的功能是读取dht11的执行结果进行lcd显示

     #!/usr/bin/python

    #

    # based on code from lrvick and LiquidCrystal

    # lrvic – https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py

    # LiquidCrystal – https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp

    #

    import subprocess

    import re

    import sys

    from time import sleep

    from datetime import datetime

    class Adafruit_CharLCD:

        # commands

        LCD_CLEARDISPLAY     = 0×01

        LCD_RETURNHOME       = 0×02

        LCD_ENTRYMODESET     = 0×04

        LCD_DISPLAYCONTROL       = 0×08

        LCD_CURSORSHIFT      = 0×10

        LCD_FUNCTIONSET      = 0×20

        LCD_SETCGRAMADDR     = 0×40

        LCD_SETDDRAMADDR     = 0×80

        # flags for display entry mode

        LCD_ENTRYRIGHT       = 0×00

        LCD_ENTRYLEFT     = 0×02

        LCD_ENTRYSHIFTINCREMENT = 0×01

        LCD_ENTRYSHIFTDECREMENT = 0×00

        # flags for display on/off control

        LCD_DISPLAYON     = 0×04

        LCD_DISPLAYOFF       = 0×00

        LCD_CURSORON      = 0×02

        LCD_CURSOROFF     = 0×00

        LCD_BLINKON       = 0×01

        LCD_BLINKOFF      = 0×00

        # flags for display/cursor shift

        LCD_DISPLAYMOVE      = 0×08

        LCD_CURSORMOVE       = 0×00

        # flags for display/cursor shift

        LCD_DISPLAYMOVE      = 0×08

        LCD_CURSORMOVE       = 0×00

        LCD_MOVERIGHT     = 0×04

        LCD_MOVELEFT      = 0×00

        # flags for function set

        LCD_8BITMODE      = 0×10

        LCD_4BITMODE      = 0×00

        LCD_2LINE         = 0×08

        LCD_1LINE         = 0×00

        LCD_5x10DOTS      = 0×04

        LCD_5x8DOTS       = 0×00

        def __init__(self, pin_rs=14, pin_e=15, pins_db=[17, 18, 27, 22], GPIO = None):

        # Emulate the old behavior of using RPi.GPIO if we haven’t been given

        # an explicit GPIO interface to use

        if not GPIO:

            import RPi.GPIO as GPIO

       self.GPIO = GPIO

            self.pin_rs = pin_rs

            self.pin_e = pin_e

            self.pins_db = pins_db

            self.GPIO.setmode(GPIO.BCM)

            self.GPIO.setup(self.pin_e, GPIO.OUT)

            self.GPIO.setup(self.pin_rs, GPIO.OUT)

            for pin in self.pins_db:

                self.GPIO.setup(pin, GPIO.OUT)

        self.write4bits(0×33) # initialization

        self.write4bits(0×32) # initialization

        self.write4bits(0×28) # 2 line 5×7 matrix

        self.write4bits(0x0C) # turn cursor off 0x0E to enable cursor

        self.write4bits(0×06) # shift cursor right

        self.displaycontrol = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF

        self.displayfunction = self.LCD_4BITMODE | self.LCD_1LINE | self.LCD_5x8DOTS

        self.displayfunction |= self.LCD_2LINE

        “”" Initialize to default text direction (for romance languages) “”"

        self.displaymode =  self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT

        self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) #  set the entry mode

            self.clear()

        def begin(self, cols, lines):

        if (lines > 1):

           self.numlines = lines

               self.displayfunction |= self.LCD_2LINE

           self.currline = 0

        def home(self):

        self.write4bits(self.LCD_RETURNHOME) # set cursor position to zero

        self.delayMicroseconds(3000) # this command takes a long time!

        def clear(self):

        self.write4bits(self.LCD_CLEARDISPLAY) # command to clear display

        self.delayMicroseconds(3000)    # 3000 microsecond sleep, clearing the display takes a long time

        def setCursor(self, col, row):

        self.row_offsets = [ 0x00, 0x40, 0x14, 0x54 ]

        if ( row > self.numlines ):

           row = self.numlines – 1 # we count rows starting w/0

        self.write4bits(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row]))

        def noDisplay(self):

        “”" Turn the display off (quickly) “”"

        self.displaycontrol &= ~self.LCD_DISPLAYON

        self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)

        def display(self):

        “”" Turn the display on (quickly) “”"

        self.displaycontrol |= self.LCD_DISPLAYON

        self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)

        def noCursor(self):

        “”" Turns the underline cursor on/off “”"

        self.displaycontrol &= ~self.LCD_CURSORON

        self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)

        def cursor(self):

        “”" Cursor On “”"

        self.displaycontrol |= self.LCD_CURSORON

        self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)

        def noBlink(self):

        “”" Turn on and off the blinking cursor “”"

        self.displaycontrol &= ~self.LCD_BLINKON

        self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)

        def noBlink(self):

        “”" Turn on and off the blinking cursor “”"

        self.displaycontrol &= ~self.LCD_BLINKON

        self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)

        def DisplayLeft(self):

        “”" These commands scroll the display without changing the RAM “”"

        self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT)

        def scrollDisplayRight(self):

        “”" These commands scroll the display without changing the RAM “”"

        self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT);

        def leftToRight(self):

        “”" This is for text that flows Left to Right “”"

        self.displaymode |= self.LCD_ENTRYLEFT

        self.write4bits(self.LCD_ENTRYMODESET | self.displaymode);

        def rightToLeft(self):

        “”" This is for text that flows Right to Left “”"

        self.displaymode &= ~self.LCD_ENTRYLEFT

        self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)

        def autoscroll(self):

        “”" This will ‘right justify’ text from the cursor “”"

        self.displaymode |= self.LCD_ENTRYSHIFTINCREMENT

        self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)

        def noAutoscroll(self):

        “”" This will ‘left justify’ text from the cursor “”"

        self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT

        self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)

        def write4bits(self, bits, char_mode=False):

            “”" Send command to LCD “”"

        self.delayMicroseconds(1000) # 1000 microsecond sleep

            bits=bin(bits)[2:].zfill(8)

            self.GPIO.output(self.pin_rs, char_mode)

            for pin in self.pins_db:

                self.GPIO.output(pin, False)

            for i in range(4):

                if bits[i] == “1″:

                    self.GPIO.output(self.pins_db[::-1][i], True)

        self.pulseEnable()

            for pin in self.pins_db:

                self.GPIO.output(pin, False)

            for i in range(4,8):

                if bits[i] == “1″:

                    self.GPIO.output(self.pins_db[::-1][i-4], True)

        self.pulseEnable()

        def delayMicroseconds(self, microseconds):

        seconds = microseconds / float(1000000)   # divide microseconds by 1 million for seconds

        sleep(seconds)

        def pulseEnable(self):

        self.GPIO.output(self.pin_e, False)

        self.delayMicroseconds(1)       # 1 microsecond pause – enable pulse must be > 450ns

        self.GPIO.output(self.pin_e, True)

        self.delayMicroseconds(1)       # 1 microsecond pause – enable pulse must be > 450ns

        self.GPIO.output(self.pin_e, False)

        self.delayMicroseconds(1)       # commands need > 37us to settle

        def message(self, text):

            “”" Send string to LCD. Newline wraps to second line”"”

            for char in text:

                if char == ‘\n’:

                    self.write4bits(0xC0) # next line

                else:

                    self.write4bits(ord(char),True)

    if __name__ == ‘__main__’:

        lcd = Adafruit_CharLCD()

        lcd.noBlink()

        while True:

            sleep(1)

            output = subprocess.check_output(["./dht11"]);

            #print output

            matches = re.search(“TMP:([0-9.]+)”,output)

            if (not matches):

                sleep(1)

                continue

            temp = float(matches.group(1))

            #print temp

            matches = re.search(“RH:([0-9.]+)”, output)

            if (not matches):

                sleep(1)

                continue

            humidity = float(matches.group(1))

            #print humidity

            lcd.clear()

            lcd.message(‘TMP:%s’ % ( temp ))

            lcd.message(‘ HM:%s’ % ( humidity ))

            lcd.message(datetime.now().strftime(‘\n%Y-%m-%d %H:%M:%S’))

  • 相关阅读:
    Unity—Json2
    Unity—Json1
    windows 命令行报错:file(s) not in client view
    winform listbox 使用DrawMode使用OwnerDrawVarialbe或OwnerDrawFixed无水平滚动条
    windows 命令行使用p4
    winform listbox增加鼠标双击事件
    lua5.3+luasocket
    centos 安装glide工具(golang)笔记
    centos 安装golang笔记
    centos安装redis,并设置开机自动启动项
  • 原文地址:https://www.cnblogs.com/zxRPI/p/3115867.html
Copyright © 2011-2022 走看看