[外设篇]ESP8266-SDK教程(十)之DHT11、OLED1306

Hi,大家好,写这篇文章的时候“IAMLIUBO的神奇物联网之旅”专栏关注人数已经有186人了,首先很感谢大家的关注和相信,开始写第一篇的文章的时候也没想过会有这么多人感兴趣,看到关注的人数越来越多,当然对文章的质量也要有更高的要求,力求每篇文章没有错别字和错误的叙述,也希望大家可以帮我一起勘误。写这些文章的目的就是希望可以帮助更多人,当然也收获了很多知友,也有很多知友加我微信咨询一些问题,希望我的每一个回答都对你有所帮助,这篇文章是外设篇的第一篇,也是知友小牛最近在微信咨询我的一点问题,这里就记录成文章跟大家分享一下。

闲话少说,咱们开始来说正事,相信大家在做一些实际项目或者小发明创造的时候,多多少少都会用过温湿度传感器,或者说会采集温湿度数据加以展示和判断处理,那么我们这里说的DHT11就是一款非常不错的温湿度传感器,是广州奥松电子生产的一款温湿度传感器,在开发当中我是用的比较多的,上一张图给大家看一下。

image

当然,这款传感器尺寸不是很小,做一些对尺寸要求比较严格的产品还是不怎么推荐的,一般做比较小的产品,还是比较推荐盛思瑞的SHT系列,当然价格就不是那么美丽了,但是精度相对来说还是比较不错的,当然对大小和空间都有要求的话推荐美信的DS18B20。

image

下面我们来看一下这款传感器的具体参数:

image
image
image

上面这三个表,就可以很直观的看出这款传感器的参数了,这里就不再做过多的文字叙述了。

了解完了这些基本的,那我们再来看一下我们是如何从传感器取到温湿度的值呢?说到这里,那就不得不提一个概念了,相信搞嵌入式开发的都知道,那就是单总线通信方式,那么什么是单总线通信方式呢?它与其他通信方式又有什么不同呢?下面我们先来看一下百科:

单总线是美国DALLAS公司推出的外围串行扩展总线技术。与SPI、I²C串行数据通信方式不同.它采用单根信号线,既传输时钟又传输数据,而且数据传输是双向的,具有节省I/O口线、资源结构简单、成本低廉、便于总线扩展和维护等诸多优点。(百度百科)

简单来说,就是双方通信只通过一根线解决,不像其他通信方式有时钟线和数据线,这样的好处是极大的节省了I/O资源,当然这种通信方式的速率自然也会有所降低,像前面说的DS18B20也是采用单总线通信方式。

那么我们再来看一下DHT11通过单总线发送的数据格式,了解了数据格式可以更好的帮助我们理解程序是如何读取温湿度的,因为数据传输在硬件层就是电平高低,转化为计算机语言就是0/1,我们就是通过DHT11发送的这些0/1中找出温湿度的值:

image

可以看到一共是有40位数据的,每8位是一组,包含了温湿度和校验值,校验值等于温湿度的和,如果不理解,那么我们通过一个实际例子来看一下:

image

这就是一个完整的数据包过来,我们如何解包和验证,那么我们看一下代码:

static uint8_t ICACHE_FLASH_ATTR dht11ReadBit(void)
{
    uint8_t retry=0;

    while(DHT11_IN&&retry<100)                                  //wait become Low level
    {
        retry++;
        tempHumDelay(1);
    }

    retry=0;
    while(!DHT11_IN&&retry<100)                                 //wait become High level
    {
        retry++;
        tempHumDelay(1);
    }

    tempHumDelay(40);                                         //wait 40us

    if(DHT11_IN)
        return 1;
    else
        return 0;
}

static uint8_t ICACHE_FLASH_ATTR hdt11ReadByte(void)
{
    uint8_t i;
    uint8_t dat=0;

    for (i=0; i<8; i++)
    {
        dat<<=1;
        dat |= dht11ReadBit(); 
    }

    return dat;
}

static uint8_t ICACHE_FLASH_ATTR dht11ReadData(u8 * temperature, u8 * humidity)
{
    uint8_t i;
    uint8_t buf[5];

    dht11Rst(); 
    if(0 == dht11Check()) 
    {
        for(i=0; i<5; i++)
        {
            buf[i] = hdt11ReadByte(); 
        }
        if((buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
        {
            *humidity=buf[0];
            *temperature=buf[2];
        }
    }
    else
    {
        return 1;
    }

    return 0;
}

uint8_t ICACHE_FLASH_ATTR dh11Read(uint8_t * temperature, uint8_t * humidity)
{
    uint8_t ret = 0; 
    uint8_t cur_i = 0;
    uint8_t curTem = 0;
    uint8_t curHum = 0;
    uint16_t temMeans = 0;
    uint16_t hum_means = 0;

    ret = dht11ReadData(&curTem, &curHum);

    if(0 == ret) 
    {
        //Cycle store ten times stronghold
        if(MEAN_NUM > temphum_typedef.th_num)
        {
            temphum_typedef.th_bufs[temphum_typedef.th_num][0] = curTem;
            temphum_typedef.th_bufs[temphum_typedef.th_num][1] = curHum;

            temphum_typedef.th_num++;
        }
        else
        {
            temphum_typedef.th_num = 0;

            temphum_typedef.th_bufs[temphum_typedef.th_num][0] = curTem;
            temphum_typedef.th_bufs[temphum_typedef.th_num][1] = curHum;

            temphum_typedef.th_num++;
        }
    }
    else
    {
        return 1; 
    }

    if(MEAN_NUM <= temphum_typedef.th_num) 
    {
        temphum_typedef.th_amount = MEAN_NUM;
    }

    if(0 == temphum_typedef.th_amount) 
    {
        //Calculate Before ten the mean
        for(cur_i = 0; cur_i < temphum_typedef.th_num; cur_i++)
        {
            temMeans += temphum_typedef.th_bufs[cur_i][0];
            hum_means += temphum_typedef.th_bufs[cur_i][1];
        }

        temMeans = temMeans / temphum_typedef.th_num;
        hum_means = hum_means / temphum_typedef.th_num; 

        *temperature = temMeans;
        *humidity = hum_means;
    }
    else if(MEAN_NUM == temphum_typedef.th_amount) 
    {
        //Calculate After ten times the mean
        for(cur_i = 0; cur_i < temphum_typedef.th_amount; cur_i++) 
        {
            temMeans += temphum_typedef.th_bufs[cur_i][0];
            hum_means += temphum_typedef.th_bufs[cur_i][1];
        }

        temMeans = temMeans / temphum_typedef.th_amount; 
        hum_means = hum_means / temphum_typedef.th_amount; 

        *temperature = (uint8_t)temMeans; 
        *humidity = (uint8_t)hum_means; 
    }

    return 0;
}

这就是我们读温湿度的主要代码,大家可以看一下,我们是不是对40位的bit位的数据做了处理呢?后面我们会结合OLED显示屏来实际测试一下,这里就先不做测试了。

说完了DHT11,我们再来了解一下SSD1306,其实这是一款OLED屏幕的控制芯片,目前在淘宝等常见的0.96吋小OLED显示屏幕大多就是使用这款芯片的,当然还有一款功能一样的替代芯片叫SHT1106,不过两者指令兼容,所以会一款,另一款也就会了。这款主控芯片是香港晶门科技公司的,目前在一般小制作或者小创意上用这款主控的显示屏幕还是比较多的,我也一直在使用,这款芯片最大只能控制128x64个像素点,所以有时候我们常说的OLED12864,多也是使用这块主控的屏幕,当然这家公司也生产很多可以控制更多像素点的主控芯片,有兴趣的可以去官网了解一下:

晶门科技有限公司​www.solomon-systech.com.cn

图标

同样的,我们先来了解一下,遗憾的是没有找到官方的中文数据手册,又怕某些翻译的不太准确,所以这里就直接贴英文数据手册的截图了:

image

其中我们做开发需要关注的就是上面提到的两种通信方式了,可以看到是支持IIC和SPI通信方式的,还支持亮度调节,我这里其实最近重新撸了一下驱动,之前也是一直拿来别人写好的直接用,最近比较想自己动手撸一下,于是也借鉴别人写的,自己看着数据手册重新写了一下,当然过程没那么顺利,我这里是使用IIC通信的,但是由于ESP8266没有硬件IIC,这刷新效果也是有点感人,其实最重要的也是采用了全局刷新方式,没有写局部刷新的驱动,就导致每次修改某一个地方,都会把所有的像素点重新写一遍~自然这FPS就降下来了,后面再考虑优化吧,但是通过整个过程也是对工作方式有了更深的了解,呃呃呃,又讲远了。

我们再来看一下主要特性:

image

我们再来看一下尺寸,可以说是非常薄了,我们是不可能用手焊接的,一般买也是买别人把芯片跟显示屏封装好的模组的:

image

可以看到厚度只有0.3mm,这里给大家看一下跟屏幕封装好的模组,这也是前不久做一款STM32 Mini开发板的显示扩展板剩下的:

image
image

按理说接下来我们应该讲一下如何去驱动这款芯片了,但是相比于温湿度传感器来说,就有点复杂了,而且也比较难讲清楚,不过这里推荐大家看一下杜洋老师对这款芯片的视频讲解,戳看片观看:

优酷视频​v.youku.com

分了好几集,上面卡片是第一集,大家可以看一下,个人认为讲的还是比较不错的。

下面我们来看一下我这撸的驱动代码的,目前支持IIC通信和中英文显示,由于手头没有SPI接口的屏幕,也没法测试,所以有机会再更新SPI通信方式的。

/*
 * MIT License
 *
 * Copyright (c) 2018 imliubo
 *
 * Github  https://github.com/imliubo
 * Website https://www.makingfun.xyz
 * Zhihu   https://www.zhihu.com/people/MAKINGFUNXYZ
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "modules/ssd1306.h"

#if defined(SSD1306_USE_I2C)
int ICACHE_FLASH_ATTR
HAL_I2C_Mem_Write( uint16_t DevAddress, uint16_t MemAddress, uint8_t pData, uint16_t Size )
{
    i2c_master_start();
    i2c_master_writeByte( DevAddress );
    if ( !i2c_master_checkAck() )
    {
        i2c_master_stop();
        return(0);
    }

    i2c_master_writeByte( MemAddress );
    if ( !i2c_master_checkAck() )
    {
        i2c_master_stop();
        return(0);
    }

    i2c_master_writeByte( pData );
    if ( !i2c_master_checkAck() )
    {
        i2c_master_stop();
        return(0);
    }

    i2c_master_stop();
    return(1);
}

void ssd1306_Reset( void )
{
    /* for I2C - do nothing */
}

/* Send a byte to the command register */
void ssd1306_WriteCommand( uint8_t byte )
{
    HAL_I2C_Mem_Write( SSD1306_I2C_ADDR, 0x00, byte, 1 );
}

/* Send data */
void ssd1306_WriteData( uint8_t buffer, size_t buff_size )
{
    HAL_I2C_Mem_Write( SSD1306_I2C_ADDR, 0x40, buffer, buff_size );
}

#elif defined(SSD1306_USE_SPI)

#else
#error "You should define SSD1306_USE_SPI or SSD1306_USE_I2C macro"
#endif

/* Screenbuffer */
static uint8_t SSD1306_Buffer[SSD1306_WIDTH * SSD1306_HEIGHT / 8];

/* Screen object */
static SSD1306_t SSD1306;

/* Initialize the oled screen */
void ssd1306_Init( void )
{
    /* Reset OLED */
    ssd1306_Reset();

    /* Wait for the screen to boot */
    os_delay_us( 60000 );
    os_delay_us( 40000 );

/*     // Init OLED */
    ssd1306_WriteCommand( 0xAE );   /* display off */

    ssd1306_WriteCommand( 0x20 );   /* Set Memory Addressing Mode */
    ssd1306_WriteCommand( 0x10 );   /*
                                     * 00,Horizontal Addressing Mode; 01,Vertical Addressing Mode;
                                     * 10,Page Addressing Mode (RESET); 11,Invalid
                                     */

    ssd1306_WriteCommand( 0xB0 );   /* Set Page Start Address for Page Addressing Mode,0-7 */

#ifdef SSD1306_MIRROR_VERT
    ssd1306_WriteCommand( 0xC0 );   /* Mirror vertically */
#else
    ssd1306_WriteCommand( 0xC8 );   /* Set COM Output Scan Direction */
#endif

    ssd1306_WriteCommand( 0x00 );   /* ---set low column address */
    ssd1306_WriteCommand( 0x10 );   /* ---set high column address */

    ssd1306_WriteCommand( 0x40 );   /* --set start line address - CHECK */

    ssd1306_WriteCommand( 0x81 );   /* --set contrast control register - CHECK */
    ssd1306_WriteCommand( 0xFF );

#ifdef SSD1306_MIRROR_HORIZ
    ssd1306_WriteCommand( 0xA0 );   /* Mirror horizontally */
#else
    ssd1306_WriteCommand( 0xA1 );    /*--set segment re-map 0 to 127 - CHECK */
#endif

#ifdef SSD1306_INVERSE_COLOR
    ssd1306_WriteCommand( 0xA7 );   /* --set inverse color */
#else
    ssd1306_WriteCommand( 0xA6 );   /* --set normal color */
#endif

    ssd1306_WriteCommand( 0xA8 );   /* --set multiplex ratio(1 to 64) - CHECK */
    ssd1306_WriteCommand( 0x3F );   /*  */

    ssd1306_WriteCommand( 0xA4 );   /* 0xa4,Output follows RAM content;0xa5,Output ignores RAM content */

    ssd1306_WriteCommand( 0xD3 );   /* -set display offset - CHECK */
    ssd1306_WriteCommand( 0x00 );   /* -not offset */

    ssd1306_WriteCommand( 0xD5 );   /* --set display clock divide ratio/oscillator frequency */
    ssd1306_WriteCommand( 0xF0 );   /* --set divide ratio */

    ssd1306_WriteCommand( 0xD9 );   /* --set pre-charge period */
    ssd1306_WriteCommand( 0x22 );   /*  */

    ssd1306_WriteCommand( 0xDA );   /* --set com pins hardware configuration - CHECK */
    ssd1306_WriteCommand( 0x12 );

    ssd1306_WriteCommand( 0xDB );   /* --set vcomh */
    ssd1306_WriteCommand( 0x20 );   /* 0x20,0.77xVcc */

    ssd1306_WriteCommand( 0x8D );   /* --set DC-DC enable */
    ssd1306_WriteCommand( 0x14 );   /*  */
    ssd1306_WriteCommand( 0xAF );   /* --turn on SSD1306 panel */

    /* Clear screen */
    ssd1306_Fill( Black );

    /* Flush buffer to screen */
    ssd1306_UpdateScreen();

    /* Set default values for screen object */
    SSD1306.CurrentX    = 0;
    SSD1306.CurrentY    = 0;

    SSD1306.Initialized = 1;
}

/* Fill the whole screen with the given color */
void ssd1306_Fill( SSD1306_COLOR color )
{
    /* Set memory */
    uint32_t i;

    for ( i = 0; i < sizeof(SSD1306_Buffer); i++ )
    {
        SSD1306_Buffer[i] = (color == Black) ? 0x00 : 0xFF;
    }
}

/* Write the screenbuffer with changed to the screen */
void ssd1306_UpdateScreen( void )
{
    uint8_t i, j;
    for ( i = 0; i < 8; i++ )
    {
        ssd1306_WriteCommand( 0xB0 + i );
        ssd1306_WriteCommand( 0x00 );
        ssd1306_WriteCommand( 0x10 );
        for ( int j = 0; j < 128; j++ )
        {
            /* code */
            ssd1306_WriteData( SSD1306_Buffer[j + SSD1306_WIDTH * i], SSD1306_WIDTH );
        }
    }
}

/*
 *    Draw one pixel in the screenbuffer
 *    X => X Coordinate
 *    Y => Y Coordinate
 *    color => Pixel color
 */
void ssd1306_DrawPixel( uint8_t x, uint8_t y, SSD1306_COLOR color )
{
    if ( x >= SSD1306_WIDTH || y >= SSD1306_HEIGHT )
    {
        /* Don't write outside the buffer */
        return;
    }

    /* Check if pixel should be inverted */
    if ( SSD1306.Inverted )
    {
        color = (SSD1306_COLOR) !color;
    }

    /* Draw in the right color */
    if ( color == White )
    {
        SSD1306_Buffer[x + (y / 8) * SSD1306_WIDTH] |= 1 << (y % 8);
    } else {
        SSD1306_Buffer[x + (y / 8) * SSD1306_WIDTH] &= ~(1 << (y % 8) );
    }
}

/*
 * Draw 1 char to the screen buffer
 * ch         => char om weg te schrijven
 * Font     => Font waarmee we gaan schrijven
 * color     => Black or White
 */
char ssd1306_WriteChar( char ch, FontDef Font, SSD1306_COLOR color )
{
    uint32_t i, b, j;

    /* Check remaining space on current line */
    if ( SSD1306_WIDTH <= (SSD1306.CurrentX + Font.FontWidth) ||
         SSD1306_HEIGHT <= (SSD1306.CurrentY + Font.FontHeight) )
    {
        /* Not enough space on current line */
        return(0);
    }

    /* Use the font to write */
    for ( i = 0; i < Font.FontHeight; i++ )
    {
        os_printf("Font: %d\n",ch);
        b = Font.data[(ch - 32) * Font.FontHeight + i];
        for ( j = 0; j < Font.FontWidth; j++ )
        {
            if ( (b << j) & 0x8000 )
            {
                ssd1306_DrawPixel( SSD1306.CurrentX + j, (SSD1306.CurrentY + i), (SSD1306_COLOR) color );
            } else {
                ssd1306_DrawPixel( SSD1306.CurrentX + j, (SSD1306.CurrentY + i), (SSD1306_COLOR) !color );
            }
        }
    }

    /* The current space is now taken */
    SSD1306.CurrentX += Font.FontWidth;

    /* Return written char for validation */
    return(ch);
}

/*
 * Draw 1 Chinese char to the screen buffer
 * ch         => char 
 * color     => Black or White
 */
char ssd1306_WriteZhChar( signed char ch[], SSD1306_COLOR color ){

    uint32_t  b, j, k, data[32];

    /* Check remaining space on current line */
    if ( SSD1306_WIDTH <= (SSD1306.CurrentX + 16) ||
         SSD1306_HEIGHT <= (SSD1306.CurrentY + 16) )
    {
        /* Not enough space on current line */
        return(0);
    }

    for (int i = 0; i < 20; ++i)
    {
        if ((ZhFont16x16[i].Index[0] == ch[0]) && (ZhFont16x16[i].Index[1] == ch[1]) && (ZhFont16x16[i].Index[2] == ch[2]) )
        {
            for (int z = 0; z < ZH_CN_HEIGHT_WIDTH; z++)
            {
                data[z] = ZhFont16x16[i].Msk[z];

            }
        }
    }

    for ( int i = 0; i < ZH_CN_HEIGHT_WIDTH; i++ )
    {

        b = data[i];
        for ( j = 0; j < ZH_CN_HEIGHT_WIDTH; j++ )
        {
            //os_printf("Font: %d\n",Font.FontWidth);
            if ( (b << j) & 0x8000 )
            {
                ssd1306_DrawPixel( SSD1306.CurrentX + j, (SSD1306.CurrentY + i), (SSD1306_COLOR) color );
            } else {
                ssd1306_DrawPixel( SSD1306.CurrentX + j, (SSD1306.CurrentY + i), (SSD1306_COLOR) !color );
            }
        }
    }

    /* The current space is now taken */
    SSD1306.CurrentX += ZH_CN_HEIGHT_WIDTH;

    /* Return written char for validation */
     return(*ch);   
}

/* Write full string to screenbuffer */
char ssd1306_WriteString( char* str, FontDef Font, SSD1306_COLOR color )
{
    /* Write until null-byte */
    while ( *str )
    {
        if ( ssd1306_WriteChar( *str, Font, color ) != *str )
        {
            /* Char could not be written */

            return(*str);
        }

        /* Next char */
        str++;
    }

    /* Everything ok */
    return(*str);
}

/* Write full Chinese string to screenbuffer */
char ssd1306_WriteZhString( signed char *str, SSD1306_COLOR color ){

    /* Write until null-byte */
    while ( *str )
    {
        ssd1306_WriteZhChar( (signed char *)str, color );
        /* Next char */
        str = str + 3;

    }
    /* Everything ok */
    return(*str);

}

/* Position the cursor */
void ssd1306_SetCursor( uint8_t x, uint8_t y )
{
    SSD1306.CurrentX    = x;
    SSD1306.CurrentY    = y;
}

为了汉字显示的和谐统一,目前仅支持16*16点阵的宋体,汉字显示效果如下:

image

缺点:

  1. 不支持中英文混显,就是写中文和英文都有单独的函数,如果想在一行中显示中英文就可能需要分开写。
  2. 刷新速度慢,其实这里也不全是全局刷新的原因,也是ESP8266没有硬件IIC,只能使用模拟IICd的原因。

最后我们结合一下DHT11和SSD1306做一个桌面温湿度显示仪,主要代码:

uint8 temp,humd;
os_timer_t DHT11_Read_timer;

void ICACHE_FLASH_ATTR DHT11_Read(void)
{
    char temp_buffer[10],humd_buffer[10];
    os_timer_disarm(&DHT11_Read_timer);//取消定时器
    dh11Read(&temp,&humd);
    os_printf("Temp: %d'C Humd: %d%\n",temp,humd);
    os_sprintf(temp_buffer,":%d'",temp);
    os_sprintf(humd_buffer,":%d%",humd);
    ssd1306_SetCursor(0, 40);
    ssd1306_WriteZhString("温度",White);
    ssd1306_SetCursor(30, 44);
    ssd1306_WriteString(temp_buffer,Font_7x10,White);
    ssd1306_SetCursor(64, 40);
    ssd1306_WriteZhString("湿度",White);
    ssd1306_SetCursor(94, 44);
    ssd1306_WriteString(humd_buffer,Font_7x10,White);
    ssd1306_UpdateScreen();
    os_timer_arm(&DHT11_Read_timer, 5000, true);//使能定时器
}

void user_init(void)
{
    uart_init(115200, 115200);

    dh11Init();

    i2c_master_gpio_init();

    ssd1306_Init();

    ssd1306_Fill(Black);
    ssd1306_SetCursor(8, 0);
    ssd1306_WriteZhString("神奇物联网之旅",White);
    ssd1306_SetCursor(20, 16);
    ssd1306_WriteString("IAMLIUBO",Font_11x18,White);
    ssd1306_UpdateScreen();

    os_timer_disarm(&DHT11_Read_timer);//取消定时器
    os_timer_setfn(&DHT11_Read_timer, (os_timer_func_t *) DHT11_Read,NULL);//定时回调函数
    os_timer_arm(&DHT11_Read_timer, 5000, true);//使能定时器,设置时间为1s

}

我们直接看一下效果:

image

最后附上我的Github仓库,一些小的Demo没有写相应的文章,但是不断更新,建议大家Star或者watch一下,以便及时获得新的例程~

imliubo/makingfunxyz-esp8266​github.com

图标

欢迎大家去我的仓库点个star,有问题或者Bug可以提交issues,我看到后会第一时间回复,如果您对我的代码有改进意见,也欢迎fork后提交PR,我会及时采纳大家的意见。

夜深了,晚安。
QQ交流群:592587184

你可能感兴趣的:([外设篇]ESP8266-SDK教程(十)之DHT11、OLED1306)