基于STM32F1单片机、ESP8266WIFI模块、DHT11温湿度传感的WIFI网络温湿度传输系统完整工程
基于嵌入式的温湿度网络传输系统包含:温湿度采集端与温湿度监控端。
温湿度采集端可实时采集温度与湿度数据,通过WIFI透传技术,将温湿度数据传送到温度监控端。温度监控端实时接收温湿度采集端所发送的温湿度数据,显示在网站上。
注:目前只是在局域网下测试。
温湿度采集端STM32F1单片机、DHT11温湿度传感器、ESP8266WIFI模块
ESP8266与STM32F103连接图:
DHT11与STM32F103连接图:
温湿度监控端普通电脑需要JAVA环境
/************************************************************************************/
@file main.c
@function 初始化各模块
*************************************************************************************/
#include "stm32f10x.h"
#include "bsp_usart1.h"
#include "bsp_SysTick.h"
#include "bsp_esp8266.h"
#include "test.h"
#include "bsp_dht11.h"
int main ( void )
{
USARTx_Config ();
SysTick_Init ();
ESP8266_Init ();
DHT11_Init ();
ESP8266_StaTcpClient_UnvarnishTest ();
while ( 1 );
}
/****************************END OF FILE***************************/
/************************************************************************************/
@file stm32f10x_conf.h
@function 调用库包含
*************************************************************************************/
#ifndef __STM32F10x_CONF_H
#define __STM32F10x_CONF_H
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_tim.h"
#include "stm32f10x_usart.h"
#include "misc.h"
#ifdef USE_FULL_ASSERT
#else
#define assert_param(expr) ((void)0)
#endif
#endif
/****************************END OF FILE***************************/
/************************************************************************************/
@file stm32f10x_it.h
@function 中断头文件
*************************************************************************************/
#ifndef __STM32F10x_IT_H
#define __STM32F10x_IT_H
#ifdef __cplusplus
extern "C" {
#endif
void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void SVC_Handler(void);
void DebugMon_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
#ifdef __cplusplus
}
#endif
#endif
/****************************END OF FILE***************************/
/************************************************************************************/
@file stm32f10x_it.c
@function 中断服务程序
*************************************************************************************/
#include "stm32f10x_it.h"
#include
#include
#include "bsp_SysTick.h"
#include "bsp_esp8266.h"
#include "test.h"
void macESP8266_USART_INT_FUN ( void )
{
uint8_t ucCh;
if ( USART_GetITStatus ( macESP8266_USARTx, USART_IT_RXNE ) != RESET )
{
ucCh = USART_ReceiveData( macESP8266_USARTx );
if(strEsp8266_Fram_Record.InfBit.FramLength<(RX_BUF_MAX_LEN-1))
strEsp8266_Fram_Record.Data_RX_BUF[strEsp8266_Fram_Record .InfBit .FramLength++]= ucCh;
}
if ( USART_GetITStatus( macESP8266_USARTx, USART_IT_IDLE ) == SET )
{
strEsp8266_Fram_Record .InfBit .FramFinishFlag = 1;
ucCh = USART_ReceiveData( macESP8266_USARTx );
"CLOSED\r\n" )
}
}
/****************************END OF FILE***************************/
/************************************************************************************/
@file bsp_usart1.h
@function USART头文件
*************************************************************************************/
#ifndef __USART1_H
#define __USART1_H
#include "stm32f10x.h"
#include
****/
#define macUSART_BAUD_RATE 115200
#define macUSARTx USART1
#define macUSART_APBxClock_FUN RCC_APB2PeriphClockCmd
#define macUSART_CLK RCC_APB2Periph_USART1
#define macUSART_GPIO_APBxClock_FUN RCC_APB2PeriphClockCmd
#define macUSART_GPIO_CLK RCC_APB2Periph_GPIOA
#define macUSART_TX_PORT GPIOA
#define macUSART_TX_PIN GPIO_Pin_9
#define macUSART_RX_PORT GPIOA
#define macUSART_RX_PIN GPIO_Pin_10
#define macUSART_IRQ USART1_IRQn
#define macUSART_INT_FUN USART1_IRQHandler
void USARTx_Config ( void );
#endif
/****************************END OF FILE***************************/
/************************************************************************************/
@file bsp_usart1.c
@function USART配置
*************************************************************************************/
#include "bsp_usart1.h"
void USARTx_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
macUSART_APBxClock_FUN(macUSART_CLK, ENABLE);
macUSART_GPIO_APBxClock_FUN(macUSART_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = macUSART_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(macUSART_TX_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = macUSART_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(macUSART_RX_PORT, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = macUSART_BAUD_RATE;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(macUSARTx, &USART_InitStructure);
USART_Cmd(macUSARTx, ENABLE);
}
int fputc(int ch, FILE *f)
{
USART_SendData(macUSARTx, (uint8_t) ch);
while (USART_GetFlagStatus(macUSARTx, USART_FLAG_TXE) == RESET);
return (ch);
}
int fgetc(FILE *f)
{
while(USART_GetFlagStatus(macUSARTx,USART_FLAG_RXNE)==RESET);
return (int)USART_ReceiveData(macUSARTx);
}
/**********************************END OF FILE*********************/
/************************************************************************************/
@file bsp_SysTick.h
@function 软件定时头文件
*************************************************************************************/
#ifndef __SYSTICK_H
#define __SYSTICK_H
#include "stm32f10x.h"
#define Delay_ms(x) Delay_us(1000*x)
void SysTick_Init( void );
void TimingDelay_Decrement( void );
void Delay_us ( __IO u32 nTime );
#endif
/**********************************END OF FILE*********************/
/************************************************************************************/
@file bsp_SysTick.c
@function 软件定时
*************************************************************************************/
#include "bsp_SysTick.h"
static __IO u32 TimingDelay = 0;
void SysTick_Init( void )
{
if ( SysTick_Config(SystemCoreClock / 1000000) )
{
while (1);
}
SysTick->CTRL &= ~ SysTick_CTRL_ENABLE_Msk;
}
void Delay_us( __IO u32 nTime )
{
TimingDelay = nTime;
SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
while( TimingDelay != 0 );
}
void TimingDelay_Decrement(void)
{
if ( TimingDelay != 0x00 )
{
TimingDelay --;
}
}
/**********************************END OF FILE*******************/
/************************************************************************************/
@file bsp_esp8266.h
@function WIFI模块头文件
*************************************************************************************/
#ifndef __BSP_ESP8266_H
#define __BSP_ESP8266_H
#include "stm32f10x.h"
#include "common.h"
#include
#include
#if defined ( __CC_ARM )
#pragma anon_unions
#endif
typedef enum{
STA,
AP,
STA_AP
} ENUM_Net_ModeTypeDef;
typedef enum{
enumTCP,
enumUDP,
} ENUM_NetPro_TypeDef;
typedef enum{
Multiple_ID_0 = 0,
Multiple_ID_1 = 1,
Multiple_ID_2 = 2,
Multiple_ID_3 = 3,
Multiple_ID_4 = 4,
Single_ID_0 = 5,
} ENUM_ID_NO_TypeDef;
typedef enum{
OPEN = 0,
WEP = 1,
WPA_PSK = 2,
WPA2_PSK = 3,
WPA_WPA2_PSK = 4,
} ENUM_AP_PsdMode_TypeDef;
#define RX_BUF_MAX_LEN 1024
extern struct STRUCT_USARTx_Fram
{
char Data_RX_BUF [ RX_BUF_MAX_LEN ];
union {
__IO u16 InfAll;
struct {
__IO u16 FramLength :15;
__IO u16 FramFinishFlag :1;
} InfBit;
};
} strEsp8266_Fram_Record;
#define macESP8266_CH_PD_APBxClock_FUN RCC_APB2PeriphClockCmd
#define macESP8266_CH_PD_CLK RCC_APB2Periph_GPIOB
#define macESP8266_CH_PD_PORT GPIOB
#define macESP8266_CH_PD_PIN GPIO_Pin_8
#define macESP8266_RST_APBxClock_FUN RCC_APB2PeriphClockCmd
#define macESP8266_RST_CLK RCC_APB2Periph_GPIOB
#define macESP8266_RST_PORT GPIOB
#define macESP8266_RST_PIN GPIO_Pin_9
#define macESP8266_USART_BAUD_RATE 115200
#define macESP8266_USARTx USART3
#define macESP8266_USART_APBxClock_FUN RCC_APB1PeriphClockCmd
#define macESP8266_USART_CLK RCC_APB1Periph_USART3
#define macESP8266_USART_GPIO_APBxClock_FUN RCC_APB2PeriphClockCmd
#define macESP8266_USART_GPIO_CLK RCC_APB2Periph_GPIOB
#define macESP8266_USART_TX_PORT GPIOB
#define macESP8266_USART_TX_PIN GPIO_Pin_10
#define macESP8266_USART_RX_PORT GPIOB
#define macESP8266_USART_RX_PIN GPIO_Pin_11
#define macESP8266_USART_IRQ USART3_IRQn
#define macESP8266_USART_INT_FUN USART3_IRQHandler
#define macESP8266_Usart( fmt, ... ) USART_printf ( macESP8266_USARTx, fmt, ##__VA_ARGS__ )
#define macPC_Usart( fmt, ... ) printf ( fmt, ##__VA_ARGS__ )
//#define macPC_Usart( fmt, ... )
#define macESP8266_CH_ENABLE() GPIO_SetBits ( macESP8266_CH_PD_PORT, macESP8266_CH_PD_PIN )
#define macESP8266_CH_DISABLE() GPIO_ResetBits ( macESP8266_CH_PD_PORT, macESP8266_CH_PD_PIN )
#define macESP8266_RST_HIGH_LEVEL() GPIO_SetBits ( macESP8266_RST_PORT, macESP8266_RST_PIN )
#define macESP8266_RST_LOW_LEVEL() GPIO_ResetBits ( macESP8266_RST_PORT, macESP8266_RST_PIN )
void ESP8266_Init ( void );
void ESP8266_Rst ( void );
bool ESP8266_Cmd ( char * cmd, char * reply1, char * reply2, u32 waittime );
void ESP8266_AT_Test ( void );
bool ESP8266_Net_Mode_Choose ( ENUM_Net_ModeTypeDef enumMode );
bool ESP8266_JoinAP ( char * pSSID, char * pPassWord );
bool ESP8266_BuildAP ( char * pSSID, char * pPassWord, ENUM_AP_PsdMode_TypeDef enunPsdMode );
bool ESP8266_Enable_MultipleId ( FunctionalState enumEnUnvarnishTx );
bool ESP8266_Link_Server ( ENUM_NetPro_TypeDef enumE, char * ip, char * ComNum, ENUM_ID_NO_TypeDef id);
bool ESP8266_StartOrShutServer ( FunctionalState enumMode, char * pPortNum, char * pTimeOver );
uint8_t ESP8266_Get_LinkStatus ( void );
uint8_t ESP8266_Get_IdLinkStatus ( void );
uint8_t ESP8266_Inquire_ApIp ( char * pApIp, uint8_t ucArrayLength );
bool ESP8266_UnvarnishSend ( void );
void ESP8266_ExitUnvarnishSend ( void );
bool ESP8266_SendString ( FunctionalState enumEnUnvarnishTx, char * pStr, u32 ulStrLength, ENUM_ID_NO_TypeDef ucId );
char * ESP8266_ReceiveString ( FunctionalState enumEnUnvarnishTx );
#endif
/**********************************END OF FILE*******************/
/************************************************************************************/
@file bsp_esp8266.c
@function WIFI模块功能文件
*************************************************************************************/
#include "bsp_esp8266.h"
#include "common.h"
#include
#include
#include
#include "bsp_SysTick.h"
static void ESP8266_GPIO_Config ( void );
static void ESP8266_USART_Config ( void );
static void ESP8266_USART_NVIC_Configuration ( void );
struct STRUCT_USARTx_Fram strEsp8266_Fram_Record = {
0 };
void ESP8266_Init ( void )
{
ESP8266_GPIO_Config ();
ESP8266_USART_Config ();
macESP8266_RST_HIGH_LEVEL();
macESP8266_CH_DISABLE();
}
static void ESP8266_GPIO_Config ( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
macESP8266_CH_PD_APBxClock_FUN ( macESP8266_CH_PD_CLK, ENABLE );
GPIO_InitStructure.GPIO_Pin = macESP8266_CH_PD_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init ( macESP8266_CH_PD_PORT, & GPIO_InitStructure );
macESP8266_RST_APBxClock_FUN ( macESP8266_RST_CLK, ENABLE );
GPIO_InitStructure.GPIO_Pin = macESP8266_RST_PIN;
GPIO_Init ( macESP8266_RST_PORT, & GPIO_InitStructure );
}
static void ESP8266_USART_Config ( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
macESP8266_USART_APBxClock_FUN ( macESP8266_USART_CLK, ENABLE );
macESP8266_USART_GPIO_APBxClock_FUN ( macESP8266_USART_GPIO_CLK, ENABLE );
GPIO_InitStructure.GPIO_Pin = macESP8266_USART_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(macESP8266_USART_TX_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = macESP8266_USART_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(macESP8266_USART_RX_PORT, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = macESP8266_USART_BAUD_RATE;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl
USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(macESP8266_USARTx, &USART_InitStructure);
USART_ITConfig ( macESP8266_USARTx, USART_IT_RXNE, ENABLE );
USART_ITConfig ( macESP8266_USARTx, USART_IT_IDLE, ENABLE );
ESP8266_USART_NVIC_Configuration ();
USART_Cmd(macESP8266_USARTx, ENABLE);
}
static void ESP8266_USART_NVIC_Configuration ( void )
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig ( macNVIC_PriorityGroup_x );
NVIC_InitStructure.NVIC_IRQChannel = macESP8266_USART_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void ESP8266_Rst ( void )
{
#if 0
ESP8266_Cmd ( "AT+RST", "OK", "ready", 2500 );
#else
macESP8266_RST_LOW_LEVEL();
Delay_ms ( 500 );
macESP8266_RST_HIGH_LEVEL();
#endif
}
bool ESP8266_Cmd ( char * cmd, char * reply1, char * reply2, u32 waittime )
{
strEsp8266_Fram_Record .InfBit .FramLength = 0;
macESP8266_Usart ( "%s\r\n", cmd );
if ( ( reply1 == 0 ) && ( reply2 == 0 ) )
return true;
Delay_ms ( waittime );
strEsp8266_Fram_Record.Data_RX_BUF[strEsp8266_Fram_Record.InfBit .FramLength ]='\0';
macPC_Usart ( "%s", strEsp8266_Fram_Record .Data_RX_BUF );
if ( ( reply1 != 0 ) && ( reply2 != 0 ) )
return((bool)strstr strEsp8266_Fram_Record .Data_RX_BUF,reply1)||
(bool)strstr ( trEsp8266_Fram_Record .Data_RX_BUF, reply2 ));
else if ( reply1 != 0 )
return ( ( bool ) strstr ( strEsp8266_Fram_Record .Data_RX_BUF, reply1 ) );
else
return ( ( bool ) strstr ( strEsp8266_Fram_Record .Data_RX_BUF, reply2 ) );
}
void ESP8266_AT_Test ( void )
{
char count=0;
macESP8266_RST_HIGH_LEVEL();
Delay_ms ( 1000 );
while ( count < 10 )
{
if( ESP8266_Cmd ( "AT", "OK", NULL, 500 ) ) return;
ESP8266_Rst();
++ count;
}
}
bool ESP8266_Net_Mode_Choose ( ENUM_Net_ModeTypeDef enumMode )
{
switch ( enumMode )
{
case STA:
return ESP8266_Cmd ( "AT+CWMODE=1", "OK", "no change", 2500 );
case AP:
return ESP8266_Cmd ( "AT+CWMODE=2", "OK", "no change", 2500 );
case STA_AP:
return ESP8266_Cmd ( "AT+CWMODE=3", "OK", "no change", 2500 );
default:
return false;
}
}
bool ESP8266_JoinAP ( char * pSSID, char * pPassWord )
{
char cCmd [120];
sprintf ( cCmd, "AT+CWJAP=\"%s\",\"%s\"", pSSID, pPassWord );
return ESP8266_Cmd ( cCmd, "OK", NULL, 5000 );
}
bool ESP8266_BuildAP ( char * pSSID, char * pPassWord, ENUM_AP_PsdMode_TypeDef enunPsdMode )
{
char cCmd [120];
sprintf ( cCmd, "AT+CWSAP=\"%s\",\"%s\",1,%d", pSSID, pPassWord, enunPsdMode );
return ESP8266_Cmd ( cCmd, "OK", 0, 1000 );
}
bool ESP8266_Enable_MultipleId ( FunctionalState enumEnUnvarnishTx )
{
char cStr [20];
sprintf ( cStr, "AT+CIPMUX=%d", ( enumEnUnvarnishTx ? 1 : 0 ) );
return ESP8266_Cmd ( cStr, "OK", 0, 500 );
}
bool ESP8266_Link_Server ( ENUM_NetPro_TypeDef enumE, char * ip, char * ComNum, ENUM_ID_NO_TypeDef id)
{
char cStr [100] = {
0 }, cCmd [120];
switch ( enumE )
{
case enumTCP:
sprintf ( cStr, "\"%s\",\"%s\",%s", "TCP", ip, ComNum );
break;
case enumUDP:
sprintf ( cStr, "\"%s\",\"%s\",%s", "UDP", ip, ComNum );
break;
default:
break;
}
if ( id < 5 )
sprintf ( cCmd, "AT+CIPSTART=%d,%s", id, cStr);
else
sprintf ( cCmd, "AT+CIPSTART=%s", cStr );
return ESP8266_Cmd ( cCmd, "OK", "ALREAY CONNECT", 4000 );
}
bool ESP8266_StartOrShutServer ( FunctionalState enumMode, char * pPortNum, char * pTimeOver )
{
char cCmd1 [120], cCmd2 [120];
if ( enumMode )
{
sprintf ( cCmd1, "AT+CIPSERVER=%d,%s", 1, pPortNum );
sprintf ( cCmd2, "AT+CIPSTO=%s", pTimeOver );
return ( ESP8266_Cmd ( cCmd1, "OK", 0, 500 ) &&
ESP8266_Cmd ( cCmd2, "OK", 0, 500 ) );
}
else
{
sprintf ( cCmd1, "AT+CIPSERVER=%d,%s", 0, pPortNum )
return ESP8266_Cmd ( cCmd1, "OK", 0, 500 );
}
uint8_t ESP8266_Get_LinkStatus ( void )
{
if ( ESP8266_Cmd ( "AT+CIPSTATUS", "OK", 0, 500 ) )
{
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "STATUS:2\r\n" ) )
return 2;
else if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "STATUS:3\r\n" ) )
return 3;
else if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "STATUS:4\r\n" ) )
return 4;
}
return 0;
}
uint8_t ESP8266_Get_IdLinkStatus ( void )
{
uint8_t ucIdLinkStatus = 0x00;
if ( ESP8266_Cmd ( "AT+CIPSTATUS", "OK", 0, 500 ) )
{
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "+CIPSTATUS:0," ) )
ucIdLinkStatus |= 0x01;
else
ucIdLinkStatus &= ~ 0x01;
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "+CIPSTATUS:1," ) )
ucIdLinkStatus |= 0x02;
else
ucIdLinkStatus &= ~ 0x02;
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "+CIPSTATUS:2," ) )
ucIdLinkStatus |= 0x04;
else
ucIdLinkStatus &= ~ 0x04;
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "+CIPSTATUS:3," ) )
ucIdLinkStatus |= 0x08;
else
ucIdLinkStatus &= ~ 0x08;
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "+CIPSTATUS:4," ) )
ucIdLinkStatus |= 0x10;
else
ucIdLinkStatus &= ~ 0x10;
}
return ucIdLinkStatus;
}
uint8_t ESP8266_Inquire_ApIp ( char * pApIp, uint8_t ucArrayLength )
{
char uc;
char * pCh;
ESP8266_Cmd ( "AT+CIFSR", "OK", 0, 500 );
pCh = strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "APIP,\"" );
if ( pCh )
pCh += 6;
else
return 0;
for ( uc = 0; uc < ucArrayLength; uc ++ )
{
pApIp [ uc ] = * ( pCh + uc);
if ( pApIp [ uc ] == '\"' )
{
pApIp [ uc ] = '\0';
break;
}
}
return 1;
}
bool ESP8266_UnvarnishSend ( void )
{
if ( ! ESP8266_Cmd ( "AT+CIPMODE=1", "OK", 0, 500 ) )
return false;
return
ESP8266_Cmd ( "AT+CIPSEND", "OK", ">", 500 );
}
void ESP8266_ExitUnvarnishSend ( void )
{
Delay_ms ( 1000 );
macESP8266_Usart ( "+++" );
Delay_ms ( 500 );
}
bool ESP8266_SendString ( FunctionalState enumEnUnvarnishTx, char * pStr, u32 ulStrLength, ENUM_ID_NO_TypeDef ucId )
{
char cStr [20];
bool bRet = false;
if ( enumEnUnvarnishTx )
{
macESP8266_Usart ( "%s", pStr );
bRet = true;
}
else
{
if ( ucId < 5 )
sprintf ( cStr, "AT+CIPSEND=%d,%d", ucId, ulStrLength + 2 );
else
sprintf ( cStr, "AT+CIPSEND=%d", ulStrLength + 2 );
ESP8266_Cmd ( cStr, "> ", 0, 1000 );
bRet = ESP8266_Cmd ( pStr, "SEND OK", 0, 1000 );
}
return bRet;
}
char * ESP8266_ReceiveString ( FunctionalState enumEnUnvarnishTx )
{
char * pRecStr = 0;
strEsp8266_Fram_Record .InfBit .FramLength = 0;
strEsp8266_Fram_Record .InfBit .FramFinishFlag = 0;
while ( ! strEsp8266_Fram_Record .InfBit .FramFinishFlag );
strEsp8266_Fram_Record .Data_RX_BUF [ strEsp8266_Fram_Record .InfBit .FramLength ] = '\0';
if ( enumEnUnvarnishTx )
pRecStr = strEsp8266_Fram_Record .Data_RX_BUF;
else
{
if ( strstr ( strEsp8266_Fram_Record .Data_RX_BUF, "+IPD" ) )
pRecStr = strEsp8266_Fram_Record .Data_RX_BUF;
}
return pRecStr;
}
/*******************************************************************/
@file common.h
@function 通用功能头文件
********************************************************************/
#ifndef __COMMON_H
#define __COMMON_H
#include "stm32f10x.h"
#define macNVIC_PriorityGroup_x NVIC_PriorityGroup_2
void USART_printf ( USART_TypeDef * USARTx, char * Data, ... );
#endif
/*******************************END OF FILE************************/
/********************************************************************
@file common.c
@function 通用功能
********************************************************************/
#include "common.h"
#include "stm32f10x.h"
#include
static char * itoa ( int value, char * string, int radix );
void USART_printf ( USART_TypeDef * USARTx, char * Data, ... )
{
const char *s;
int d;
char buf[16];
va_list ap;
va_start(ap, Data);
while ( * Data != 0 )
{
if ( * Data == 0x5c )
{
switch ( *++Data )
{
case 'r':
USART_SendData(USARTx, 0x0d);
Data ++;
break;
case 'n':
USART_SendData(USARTx, 0x0a);
Data ++;
break;
default:
Data ++;
break;
}
}
else if ( * Data == '%')
{
switch ( *++Data )
{
case 's':
s = va_arg(ap, const char *);
for ( ; *s; s++)
{
USART_SendData(USARTx,*s);
while( USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET );
}
Data++;
break;
case 'd':
d = va_arg(ap, int);
itoa(d, buf, 10);
for (s = buf; *s; s++)
{
USART_SendData(USARTx,*s);
while( USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET );
}
Data++;
break;
default:
Data++;
break;
}
}
else USART_SendData(USARTx, *Data++);
while ( USART_GetFlagStatus ( USARTx, USART_FLAG_TXE ) == RESET );
}
}
static char * itoa( int value, char *string, int radix )
{
int i, d;
int flag = 0;
char *ptr = string;
/* This implementation only works for decimal numbers. */
if (radix != 10)
{
*ptr = 0;
return string;
}
if (!value)
{
*ptr++ = 0x30;
*ptr = 0;
return string;
}
/* if this is a negative value insert the minus sign. */
if (value < 0)
{
*ptr++ = '-';
/* Make the value positive. */
value *= -1;
}
for (i = 10000; i > 0; i /= 10)
{
d = value / i;
if (d || flag)
{
*ptr++ = (char)(d + 0x30);
value -= (d * i);
flag = 1;
}
}
/* Null terminate the string. */
*ptr = 0;
return string;
}
/**********************************END OF FILE*********************/
/*******************************************************************/
@file bsp_dht11.h
@function 温湿度度采集模块头文件
********************************************************************/
#ifndef __DHT11_H
#define __DHT11_H
#include "stm32f10x.h"
typedef struct
{
uint8_t humi_int;
uint8_t humi_deci;
uint8_t temp_int;
uint8_t temp_deci;
uint8_t check_sum;
} DHT11_Data_TypeDef;
#define macDHT11_Dout_SCK_APBxClock_FUN RCC_APB2PeriphClockCmd
#define macDHT11_Dout_GPIO_CLK RCC_APB2Periph_GPIOE
#define macDHT11_Dout_GPIO_PORT GPIOE
#define macDHT11_Dout_GPIO_PIN GPIO_Pin_6
#define macDHT11_Dout_0 GPIO_ResetBits ( macDHT11_Dout_GPIO_PORT, macDHT11_Dout_GPIO_PIN )
#define macDHT11_Dout_1 GPIO_SetBits ( macDHT11_Dout_GPIO_PORT, macDHT11_Dout_GPIO_PIN )
#define macDHT11_Dout_IN() GPIO_ReadInputDataBit ( macDHT11_Dout_GPIO_PORT, macDHT11_Dout_GPIO_PIN )
void DHT11_Init ( void );
uint8_t DHT11_Read_TempAndHumidity( DHT11_Data_TypeDef * DHT11_Data );
#endif
/**********************************END OF FILE*********************/
/*******************************************************************/
@file bsp_dht11.c
@function 温湿度度采集模块功能文件
********************************************************************/
#include "bsp_dht11.h"
#include "bsp_SysTick.h"
static void DHT11_GPIO_Config ( void );
static void DHT11_Mode_IPU ( void );
static void DHT11_Mode_Out_PP ( void );
static uint8_t DHT11_ReadByte ( void );
void DHT11_Init ( void )
{
DHT11_GPIO_Config ();
macDHT11_Dout_1;
}
static void DHT11_GPIO_Config ( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
macDHT11_Dout_SCK_APBxClock_FUN ( macDHT11_Dout_GPIO_CLK, ENABLE );
GPIO_InitStructure.GPIO_Pin = macDHT11_Dout_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init ( macDHT11_Dout_GPIO_PORT, &GPIO_InitStructure );
}
static void DHT11_Mode_IPU(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = macDHT11_Dout_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU ;
GPIO_Init(macDHT11_Dout_GPIO_PORT, &GPIO_InitStructure);
}
static void DHT11_Mode_Out_PP(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = macDHT11_Dout_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(macDHT11_Dout_GPIO_PORT, &GPIO_InitStructure);
}
static uint8_t DHT11_ReadByte ( void )
{
uint8_t i, temp=0;
for(i=0;i<8;i++)
{
while(macDHT11_Dout_IN()==Bit_RESET);
Delay_us(40);
if(macDHT11_Dout_IN()==Bit_SET)
{
while(macDHT11_Dout_IN()==Bit_SET);
temp|=(uint8_t)(0x01<<(7-i));
}
{
temp&=(uint8_t)~(0x01<<(7-i));
}
}
return temp;
}
uint8_t DHT11_Read_TempAndHumidity(DHT11_Data_TypeDef *DHT11_Data)
{
DHT11_Mode_Out_PP();
macDHT11_Dout_0;
/*延时18ms*/
Delay_ms(18);
/*总线拉高 主机延时30us*/
macDHT11_Dout_1;
Delay_us(30);
DHT11_Mode_IPU();
if(macDHT11_Dout_IN()==Bit_RESET)
{
while(macDHT11_Dout_IN()==Bit_RESET);
while(macDHT11_Dout_IN()==Bit_SET);
DHT11_Data->humi_int= DHT11_ReadByte();
DHT11_Data->humi_deci= DHT11_ReadByte();
DHT11_Data->temp_int= DHT11_ReadByte();
DHT11_Data->temp_deci= DHT11_ReadByte();
DHT11_Data->check_sum= DHT11_ReadByte();
DHT11_Mode_Out_PP();
macDHT11_Dout_1;
if(DHT11_Data->check_sum == DHT11_Data->humi_int + DHT11_Data->humi_deci + DHT11_Data->temp_int+ DHT11_Data->temp_deci)
return SUCCESS;
else
return ERROR;
}
else
return ERROR;
}
/*****************************END OF FILE***************************/
/*******************************************************************/
@file test.h
@function TCP连接配置功能文件
********************************************************************/
#ifndef __TEST_H
#define __TEST_H
#include "stm32f10x.h
#define macUser_ESP8266_ApSsid "test" //要连接的热点的名称
#define macUser_ESP8266_ApPwd "xuhao123456" //要连接的热点的密钥
#define macUser_ESP8266_TcpServer_IP "192.168.1.100"
//要连接的服务器的 IP
#define macUser_ESP8266_TcpServer_Port "8888"
//要连接的服务器的端口extern volatile uint8_t ucTcpClosedFlag;
void ESP8266_StaTcpClient_UnvarnishTest ( void );
#endif
/**********************************END OF FILE*********************/
/*******************************************************************/
@file test.c
@function TCP连接发送
********************************************************************/
#include "test.h"
#include "bsp_esp8266.h"
#include "bsp_SysTick.h"
#include
#include
#include
#include "bsp_dht11.h"
volatile uint8_t ucTcpClosedFlag = 0;
void ESP8266_StaTcpClient_UnvarnishTest ( void )
{
uint8_t ucStatus;
char cStr [ 100 ] = {
0 };
DHT11_Data_TypeDef DHT11_Data;
printf ( "\r\n正在配置 ESP8266 ......\r\n" );
macESP8266_CH_ENABLE();
ESP8266_AT_Test ();
ESP8266_Net_Mode_Choose ( STA );
while ( ! ESP8266_JoinAP ( macUser_ESP8266_ApSsid, macUser_ESP8266_ApPwd ) );
ESP8266_Enable_MultipleId ( DISABLE );
while ( ! ESP8266_Link_Server ( enumTCP, macUser_ESP8266_TcpServer_IP, macUser_ESP8266_TcpServer_Port, Single_ID_0 ) );
while ( ! ESP8266_UnvarnishSend () );
printf ( "\r\n配置 ESP8266 完毕\r\n" );
while ( 1 )
{
if ( DHT11_Read_TempAndHumidity ( & DHT11_Data ) == SUCCESS )
sprintf ( cStr, "Hy%d.%d%%RH Te%d.%dC\r\n",
DHT11_Data .humi_int, DHT11_Data .humi_deci, DHT11_Data .temp_int, DHT11_Data.temp_deci );
ESP8266_SendString ( ENABLE, cStr, 0, Single_ID_0 );
Delay_ms ( 1000 );
if ( ucTcpClosedFlag )
{
ESP8266_ExitUnvarnishSend ();
do ucStatus = ESP8266_Get_LinkStatus ();
while ( ! ucStatus );
if ( ucStatus == 4 )
{
printf ( "\r\n正在重连热点和服务器 ......\r\n" );
while ( ! ESP8266_JoinAP ( macUser_ESP8266_ApSsid, macUser_ESP8266_ApPwd ) );
while ( ! ESP8266_Link_Server ( enumTCP, macUser_ESP8266_TcpServer_IP, macUser_ESP8266_TcpServer_Port, Single_ID_0 ) );
printf ( "\r\n重连热点和服务器成功\r\n" );
}
while ( ! ESP8266_UnvarnishSend () );
}
}
}
/**********************************END OF FILE*********************/
/****************************************************************************
@file index.html-
@function 通过WebSocket获取到的数据的页面显示
*****************************************************************************/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Monitoring</title>
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript">
var data = [];
var count = 0;
var humidity = 0;
var temperature = 0;
var time = 0;
window.onload = function () {
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/index");//向要显示数据的网页发送websocket连接请求
} else {
alert('当前浏览器不支持Websocket')
}
websocket.onerror = function () {
alert(window.location.href);
};
websocket.onopen = function () {
//alert("Websocket建立成功");
}
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
websocket.onclose = function () {
//alert("Websocket连接关闭")
}
window.onbeforeunload = function () {
closeWebSocket();
}
function getTime() {
var dateObj = new Date();
var year = dateObj.getFullYear();
var month = dateObj.getMonth()+1;
var day = dateObj.getDate();
var hour = dateObj.getHours();
var min = dateObj.getMinutes();
return year + "-" + month + "-" + day + "-" + hour + "-" + min;
}
function setMessageInnerHTML(innerHTML) {
var json = {
};
json.time = getTime();
json.message = innerHTML;
data[count++] = json;
//document.getElementById('text').innerHTML += JSON.stringify(data[count]) + '
';
var str = JSON.stringify(json.message);
time = JSON.stringify(json.time);
humidity = parseFloat(JSON.stringify(json.message).substring(str.indexOf("y") + 1, str.indexOf("R")-1));
temperature = parseFloat(JSON.stringify(json.message).substring(str.indexOf("e") + 1, str.indexOf("C")));
document.getElementById('text').innerHTML += "时间:"+ time + "\t湿度:" + humidity.toString() + '%RH\t温度:'+ temperature.toString() + '℃\n';
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "温度湿度动态显示图"
},
data: [{
type: "column",
yValueFormatString: "#,###.#",
indexLabel: "{y}",
dataPoints: [
{
label: "boiler1", y: humidity},
{
label: "boiler2", y: temperature},
]
}]
});
function updateChart() {
var boilerColor, yVal;
var dps = chart.options.data[0].dataPoints;
for (var i = 0; i < dps.length; i++) {
yVal = dps[i].y;
boilerColor1 = yVal > 120 ? "#FF2500" : yVal >= 91 ? "#FF6000" : yVal >= 20 ? "#6B8E23 " : null;
boilerColor2 = yVal > 37 ? "#FF2500" : yVal >= 27 ? "#FF6000" : yVal >= 0 ? "#6B8E23 " : null;
if (i === 0) {
dps[i] = {
label: "湿度 %RH", y: yVal, color: boilerColor1};
} else if (i === 1) {
dps[i] = {
label: "温度 ℃", y: yVal, color: boilerColor2};
}
}
chart.options.data[0].dataPoints = dps;
chart.render();
};
updateChart();
}
}
function search() {
var count = 1;
var str = '"'+ document.getElementById('val').value + '"';
for (var i = 0 ;i<data.length;i++){
if (JSON.stringify(data[i].time) == str){
if (count == 1){
document.getElementById('text').innerHTML = "";
document.getElementById('text').innerHTML = "搜索结果如下:\n";
count = 0;
}
var temp = JSON.stringify(data[i].message);
var H = temp.substring(temp.indexOf('y')+1,temp.indexOf('R')-1);
var T = temp.substring(temp.indexOf('e')+1,temp.indexOf('C'));
document.getElementById('text').innerHTML += str + ": 湿度为"+H+"%RH 温度为"+T+"℃\n";
}
}
}
function closeWebSocket() {
websocket.close();
}
</script>
<script src="js/canvasjs.min.js"></script>
</head>
<body>
<div id="message">
<div id="chartContainer" style="height: 370px; max-width: 850px; margin: 0px auto;"></div>
<div class="parent">
<input id="val" type="text" value="">
<input id="search" type="button" value="按时间搜索" onclick="search()">
</div>
<textarea id="text" readonly></textarea>
</div>
</body>
</html>
/******************************END OF FILE************************************/
/****************************************************************************
@file style.css -
@function 前端页面样式*****************************************************************************/
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background-repeat: no-repeat;
background-attachment: fixed;
overflow: hidden;
bottom: 0px;
background-color: #c6ecd9;
}
.parent {
width: 100%;
height: 42px;
top: 4px;
position: relative;
}
#val{
width: 750px;
height: 40px;
margin-left: 530px;
border: 1px solid #ccc;
font-size: 16px;
outline: none;
border-radius: 1.2rem;
}
#search {
/*button按钮border并不占据外围大小,设置高度42px*/
width: 100px;
height: 40px;
position: absolute;
background: #317ef3;
border: 1px solid #317ef3;
color: #fff;
font-size: 16px;
outline: none;
border-radius: 1.2rem;
}
#message{
width: auto;
height: auto;
}
#text{
width: 850px;
height: 500px;
margin-left: 530px;
padding: 0;
font-size: 18px;
border-radius: 1.1rem;
/*cursor: pointer;*/
resize: none;
outline: none;
}
/******************************END OF FILE************************************/
/****************************************************************************
@file WebSocketServer.java -
@function 集成ServerSocket以及WebSocket 通过ServerSocket监听获取的数据以WebSocket传送到页面显示
*****************************************************************************/
package com.example.tcpwebsocket;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/index")
@Component
public class WebSocketServer extends Thread {
//与某个客户端的连接会话,需要通过它来给客户端发送数据
Session session;
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("输入待监听的端口:");
int port = scanner.nextInt();
WebSocketServer server = new WebSocketServer(port, session);
server.start();
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message) throws IOException {
System.out.println("来自客户端的消息:" + message);
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
}
/**
* @param message
* @throws IOException
*/
//给客户端传递消息
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
ServerSocket server = null;
Socket socket = null;
public WebSocketServer() {
}
public WebSocketServer(int port, Session session) {
try {
this.session = session;
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
super.run();
try {
while (true) {
socket = server.accept();
if (socket != null) {
InputStream in = socket.getInputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
sendMessage(new String(buf, 0, len));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/******************************END OF FILE************************************/
/****************************************************************************
@file HelloController.java
@function SpringBoot主程序web首页设定*****************************************************************************/
package com.example.tcpwebsocket.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class HelloController implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
/******************************END OF FILE************************************/
/****************************************************************************
@file WebSocketConfig.java
@function WebSocket的配置部分*****************************************************************************/
package com.example.tcpwebsocket.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter 作用
*
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
/******************************END OF FILE************************************/