ESP8266-5-使用API获取知心天气数据

首先让esp8266连接网络

写在boot就可以了

# # This file is executed on every boot (including wake-boot from deepsleep)
# #import esp
# #esp.osdebug(None)
# import uos, machine
# #uos.dupterm(None, 1) # disable REPL on UART(0)
# import gc
# #import webrepl
# #webrepl.start()
# gc.collect()
import network,time
sta = network.WLAN(network.STA_IF)
sta.active(True)

if not sta.isconnected():
    print("网络连接......")
    sta.connect('gl123', '17720556214')
    print("加入gl123")
    time.sleep(2)
    while not sta.isconnected():
        pass
    
print(sta.ifconfig())
print("wifi成功接入网络")
print(sta.status())
print("================")

然后建立main.py

# 导入网络模块
import network
# 导入httpclient
import urequests
# 导入ure库
import ure
import ujson
import time

#别人的key'https://api.seniverse.com/v3/weather/now.json?key=SBBRd0X8fidhmnBv2&location=guangzhou&language=zh-Hans&unit=c'
    # 请求武汉天气情况
resp = urequests.get('https://api.seniverse.com/v3/weather/now.json?key=SBBRd0X8fidhmnBv2&location=jiangxia&language=zh-Hans&unit=c')

# # 打印请求结果
print(type(resp.text),resp.text)
# json字符串转为python列表类型
json_str1 = ujson.loads(resp.text)
print(json_str1['results'][0]['location']['name'])
print(json_str1['results'][0]['now']['text'])
print(json_str1['results'][0]['now']['temperature'])
print(json_str1['results'][0]['last_update'])

这里直接在知心天气建立一个免费项目就可以了,免费用户只返回天气现象文字、代码和气温 3 项数据。API秘钥就是代码里的key,某些版本的esp8266的固件编译报错找不到urequests模块,则需要自己去Thonny下载。

这是返回结果说明

{
  "results": [
    {
      "location": {
        "id": "C23NB62W20TF",
        "name": "西雅图",
        "country": "US",
        "path": "西雅图,华盛顿州,美国",
        "timezone": "America/Los_Angeles",
        "timezone_offset": "-07:00"
      },
      "now": {
        "text": "多云", //天气现象文字
        "code": "4", //天气现象代码
        "temperature": "14", //温度,单位为c摄氏度或f华氏度
        "feels_like": "14", //体感温度,单位为c摄氏度或f华氏度
        "pressure": "1018", //气压,单位为mb百帕或in英寸
        "humidity": "76", //相对湿度,0~100,单位为百分比
        "visibility": "16.09", //能见度,单位为km公里或mi英里
        "wind_direction": "西北", //风向文字
        "wind_direction_degree": "340", //风向角度,范围0~360,0为正北,90为正东,180为正南,270为正西
        "wind_speed": "8.05", //风速,单位为km/h公里每小时或mph英里每小时
        "wind_scale": "2", //风力等级,请参考:http://baike.baidu.com/view/465076.htm
        "clouds": "90", //云量,单位%,范围0~100,天空被云覆盖的百分比 #目前不支持中国城市#
        "dew_point": "-12" //露点温度,请参考:http://baike.baidu.com/view/118348.htm #目前不支持中国城市#
      },
      "last_update": "2015-09-25T22:45:00-07:00" //数据更新时间(该城市的本地时间)
    }
  ]
}

在这里插入图片描述

这里提供一个基于Keil5和STM32F407VE芯片,利用ESP8266模块连接知心天气API获取天气信息的示例代码。 ```c #include "stdio.h" #include "string.h" #include "stdlib.h" #include "stm32f4xx.h" #include "stm32f4xx_conf.h" /* 定义ESP8266串口发送和接收函数 */ void ESP8266_SendString(char *str); void ESP8266_RecvString(char *str); /* 定义延时函数 */ void Delay(__IO uint32_t nCount); int main(void) { /* 声明变量 */ char recv_buf[1024] = {0}; char send_buf[1024] = {0}; char weather_str[1024] = {0}; char *p = NULL; uint8_t i = 0; /* 初始化串口1 */ USART_InitTypeDef USART_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; /* 使能GPIOA时钟 */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); /* 使能USART2时钟 */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); /* 连接GPIOA9和USART2的Tx引脚 */ GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1); /* 连接GPIOA10和USART2的Rx引脚 */ GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1); /* 配置GPIOA9和GPIOA10为复用功能 */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOA, &GPIO_InitStructure); /* 配置USART2的参数 */ USART_InitStructure.USART_BaudRate = 115200; 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(USART2, &USART_InitStructure); /* 使能USART2 */ USART_Cmd(USART2, ENABLE); /* 初始化ESP8266 */ ESP8266_SendString("AT\r\n"); Delay(1000); ESP8266_RecvString(recv_buf); printf("Recv: %s", recv_buf); /* 连接WiFi */ ESP8266_SendString("AT+CWJAP=\"你的WiFi名称\",\"你的WiFi密码\"\r\n"); Delay(5000); ESP8266_RecvString(recv_buf); printf("Recv: %s", recv_buf); /* 获取天气信息 */ ESP8266_SendString("AT+CIPSTART=\"TCP\",\"api.k780.com\",80\r\n"); Delay(2000); ESP8266_RecvString(recv_buf); printf("Recv: %s", recv_buf); sprintf(send_buf, "GET /weather/index.php?app=weather.future&weaid=1&appkey=你的appkey HTTP/1.1\r\nHost: api.k780.com\r\nConnection: keep-alive\r\n\r\n"); ESP8266_SendString(send_buf); Delay(5000); ESP8266_RecvString(recv_buf); printf("Recv: %s", recv_buf); /* 解析天气信息 */ p = strstr(recv_buf, "result"); if (p != NULL) { p += 10; for (i = 0; i < 1024; i++) { if (*p == '\"' || *p == '\n' || *p == '\r') { break; } weather_str[i] = *p; p++; } printf("Weather: %s", weather_str); } while (1) { /* 此处可以添加其他代码 */ } } /* ESP8266串口发送函数 */ void ESP8266_SendString(char *str) { while (*str != '\0') { while (USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET); USART_SendData(USART2, (uint16_t) *str); str++; } } /* ESP8266串口接收函数 */ void ESP8266_RecvString(char *str) { char ch = 0; uint8_t i = 0; while (1) { /* 等待接收到数据 */ while (USART_GetFlagStatus(USART2, USART_FLAG_RXNE) == RESET); /* 读取接收到的数据 */ ch = USART_ReceiveData(USART2); /* 将数据存入接收缓冲区 */ str[i++] = ch; /* 判断是否接收到结束符 */ if (ch == '\n' || i >= 1024) { /* 添加字符串结束符 */ str[i] = '\0'; break; } } } /* 延时函数 */ void Delay(__IO uint32_t nCount) { while(nCount--) { } } ``` 上述代码中需要替换的部分: 1. 你的WiFi名称和密码 2. 你的appkey 代码中通过ESP8266模块连接到知心天气API获取天气信息,并将结果打印在串口上。你可以根据需要修改代码实现其他功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值