基于stc89c52RC单片机,通过esp8266连接知心天气并将数据显示在lcd1602上的完整代码
时间: 2024-02-03 21:13:49 浏览: 83
基于STC89C52RC单片机LCD12864液晶屏显示实例源代码+开发板PDF硬件参考设计原理图.zip
5星 · 资源好评率100%
这是一个基于STC89C52RC单片机和ESP8266模块连接知心天气API并将数据显示在LCD1602上的完整代码:
```
#include <reg52.h>
#include <stdio.h>
#include <string.h>
#define LCD_DATA P0
sbit RS = P2^0;
sbit RW = P2^1;
sbit EN = P2^2;
void delay(unsigned int i)
{
while(i--);
}
void lcdcmd(unsigned char cmd)
{
LCD_DATA=cmd;
RS=0;
RW=0;
EN=1;
delay(5);
EN=0;
}
void lcddata(unsigned char dat)
{
LCD_DATA=dat;
RS=1;
RW=0;
EN=1;
delay(5);
EN=0;
}
void lcdinit(void)
{
lcdcmd(0x38);
lcdcmd(0x0c);
lcdcmd(0x06);
lcdcmd(0x01);
}
void lcddisplay(unsigned char *s)
{
while(*s)
{
lcddata(*s++);
}
}
void init_serial()
{
SCON = 0x50; //8位数据,可变波特率
TMOD = 0x20; //设置定时器1为模式2
TH1 = 0xfd; //设定波特率为9600bps
TL1 = 0xfd; //设定波特率为9600bps
TR1 = 1; //启动定时器1
ES = 1; //使能串口中断
EA = 1; //开总中断
}
void send_char(unsigned char c)
{
SBUF = c;
while(!TI);
TI = 0;
}
void send_string(unsigned char *s)
{
while(*s)
{
send_char(*s++);
}
}
unsigned char receive_char(void)
{
while(!RI);
RI=0;
return SBUF;
}
void receive_string(unsigned char *s)
{
unsigned char i=0;
do
{
s[i] = receive_char();
}
while(s[i++]!='\r');
s[--i]='\0';
}
void esp8266_init(void)
{
send_string("AT+CWMODE=1\r\n");
delay(10000);
send_string("AT+RST\r\n");
delay(15000);
send_string("AT+CIPMUX=0\r\n");
delay(1000);
}
void get_weather(unsigned char *weather_str)
{
send_string("AT+CIPSTART=\"TCP\",\"api.seniverse.com\",80\r\n");
delay(5000);
send_string("AT+CIPSEND\r\n");
delay(3000);
send_string("GET /v3/weather/now.json?key=your_api_key&location=ip HTTP/1.1\r\n");
send_string("Host: api.seniverse.com\r\n");
send_string("Connection: close\r\n");
send_string("\r\n");
delay(5000);
receive_string(weather_str);
}
void main()
{
unsigned char weather_str[300];
unsigned char weather[20];
unsigned char temperature[10];
unsigned char humidity[10];
unsigned char *ptr;
lcdinit();
init_serial();
esp8266_init();
while(1)
{
get_weather(weather_str);
ptr = strstr(weather_str,"\"text\":\"");
ptr += 8;
strncpy(weather,ptr,strchr(ptr,'\"')-ptr);
ptr = strstr(weather_str,"\"temperature\":\"");
ptr += 15;
strncpy(temperature,ptr,strchr(ptr,'\"')-ptr);
ptr = strstr(weather_str,"\"humidity\":\"");
ptr += 12;
strncpy(humidity,ptr,strchr(ptr,'\"')-ptr);
lcdcmd(0x01);
lcddisplay("Weather:");
lcddisplay(weather);
lcdcmd(0xc0);
lcddisplay("Temp:");
lcddisplay(temperature);
lcddisplay("C");
lcdcmd(0x90);
lcddisplay("Humidity:");
lcddisplay(humidity);
lcddisplay("%");
delay(5000);
}
}
void serial_interrupt() interrupt 4
{
if(RI)
{
RI = 0;
}
if(TI)
{
TI = 0;
}
}
```
请注意,此代码中的 "your_api_key" 需要替换为您自己的知心天气API密钥。此外,您需要将ESP8266连接到正确的Wi-Fi网络并更改代码中的IP地址(或域名)以适应您的应用程序。
阅读全文