Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Следующая версия
Предыдущая версия
products:laboratory_iot_c:exp71 [2024/12/17 18:54] – создано labuser30products:laboratory_iot_c:exp71 [2024/12/17 18:59] (текущий) – [Программный код эксперимента] labuser30
Строка 13: Строка 13:
 ==== Программный код эксперимента ==== ==== Программный код эксперимента ====
  
-<file python Exp71.py[enable_line_numbers="2", start_line_numbers_at="1"]> +<file arduino Exp71.ino[enable_line_numbers="2", start_line_numbers_at="1"]> 
-from machine import Pin, SPI +#include <SPI.h> 
-from tft import TFT_GREEN +#include <Adafruit_ST7735.h>  
-import font +#include "LittleFS_ImageReader.h"  
-import network +#include <ArduinoJson.h> 
-import gc +#include <ESP8266WiFi.h> 
-import time +#include <WiFiClient.h> 
-import socket +#include <ESP8266HTTPClient.h> 
-import json +  
-_init() +#define PIN_CS  2 
-gc.collect()+#define PIN_DC 
 +#define PIN_RST 5
  
-wlan_id = "Your_Wi-Fi+#define WIFI_NAME     "WiFi_name
-wlan_pass = "Your_Wi-Fi_Password"+#define WIFI_PASSWORD "WiFi_pass" 
 +  
 +Adafruit_ST7735 tft = Adafruit_ST7735(PIN_CS,  PIN_DC, PIN_RST); 
 +LittleFS_ImageReader reader;
  
-dc  = Pin(4, Pin.OUT)  +String httpGet(String url{ 
-cs  = Pin(2, Pin.OUT) +  WiFiClient client; 
-rst Pin(5, Pin.OUT)+  HTTPClient http; 
 +  String data "";
  
-spi = SPI(1baudrate=40000000, polarity=0, phase=0+  if (http.begin(clienturl)) {   
-tft TFT_GREEN(128, 160, spi, dc, cs, rst, rotate=0+    Serial.println("[HTTP] GET"); 
-tft.initr(tft.BGR# tft.initr(tft.RGB#Если вместо синего цвета отображается красный, а вместо красного синий+    int httpCode http.GET(); 
 +    if (httpCode > 0) { 
 +      Serial.printf("[HTTP] GET code: %d\n"httpCode); 
 +      if (httpCode == HTTP_CODE_OK{ 
 +        data http.getString()
 +      } else { 
 +        Serial.printf("[HTTP] GET failed, error: %s\n", http.errorToString(httpCode).c_str()); 
 +      } 
 +      http.end()
 +    } else { 
 +      Serial.println("[HTTP] Unable to connect"); 
 +    } 
 +  } 
 +  return data; 
 +}
  
 +void setup() {
 +  Serial.begin(9600);
 +  Serial.println();
 +  
 +  LittleFS.begin();
 +  tft.initR(INITR_BLACKTAB);
 +  tft.setRotation(2); 
  
-FontColor = tft.rgbcolor(33,14982+  Serial.print("Connecting to WiFi");  
-FontColor2 tft.rgbcolor(8,85, 41)+  WiFi.mode(WIFI_STA);                                          
 +  WiFi.begin(WIFI_NAMEWIFI_PASSWORD); 
 +  while (WiFi.status() !WL_CONNECTED) { 
 +    Serial.print("."); 
 +    delay(500); 
 +  } 
 +  Serial.println(); 
 +  Serial.println("WiFi connected"); 
 +  Serial.print("IP address: "); 
 +  Serial.println(WiFi.localIP());
  
-wlan network.WLAN(network.STA_IF) +  String API_key "YourApiKey"; 
-wlan.active(True) +  String city_name = "Moscow";
-wlan.connect(wlan_id, wlan_pass)+
  
-tft.clear(tft.rgbcolor(255,255, 255)+  String json_string = httpGet("http://api.weatherbit.io/v2.0/current?city=" + city_name + "&key=" + API_key); 
 +  JsonDocument json_doc; 
 +  deserializeJson(json_docjson_string);
  
 +  String w_city = json_doc["data"][0]["city_name"];
 +  int w_temp = json_doc["data"][0]["temp"];
 +  int w_temp_feels = json_doc["data"][0]["app_temp"];
 +  int w_humidity = json_doc["data"][0]["rh"];
 +  float w_wind = json_doc["data"][0]["wind_spd"];
 +  String w_pod = json_doc["data"][0]["pod"];
 +  int w_code = int(json_doc["data"][0]["weather"]["code"]);
  
-while wlan.isconnected() == False: +  String w_pic; 
-    pass+  if (w_code <= 233w_pic "11"; 
 +  else if ((w_code >300 && w_code <= 520) || w_code == 522) w_pic = "09"; 
 +  else if (w_code >= 521 && w_code <= 600) w_pic = "10"; 
 +  else if (w_code >= 601 && w_code <= 622) w_pic = "13"; 
 +  else if (w_code >= 623 && w_code <= 751) w_pic = "50"; 
 +  else if (w_code == 800) w_pic = "01"; 
 +  else if (w_code >= 801 && w_code <=802) w_pic = "02"; 
 +  else if (w_code == 803) w_pic = "03"; 
 +  else if (w_code == 804) w_pic = "04";
  
-print('Device IP:', wlan.ifconfig()[0])+  String w_pic_temp; 
 +  if (w_temp > 0) w_pic_temp = "tp"; 
 +  else w_pic_temp = "tn"; 
 +  
 +  unsigned int font_color = tft.color565(33, 149, 82)
 +  unsigned int font_color2 = tft.color565(8, 85, 41);
  
-apiKey = 'Your_Key' +  tft.fillScreen(ST77XX_WHITE);
-cityName = 'Moscow,RU'+
  
 +  tft.setTextColor(font_color);
 +  tft.setTextSize(2);
 +  tft.setCursor(5, 1);
 +  tft.print(w_city);
  
-def http_get(url, port=80): +  reader.drawBMP("/weather/" + w_pic + w_pod + ".bmp", tft34, 16); 
-    _, _, host, path = url.split('/', 3) +  reader.drawBMP("/weather/" + w_pic_temp + ".bmp"tft5, 70);
-    addr = socket.getaddrinfo(hostport)[0][-1] +
-     +
-    s = socket.socket(+
-    s.connect(addr) +
-    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (pathhost)'utf8'))+
  
-    text = ''+  tft.setTextSize(4); 
 +  tft.setCursor(30, 75); 
 +  tft.print(w_temp);
  
-    while True: +  tft.setTextColor(font_color2); 
-        data = s.recv(100+  tft.setTextSize(1); 
-        if data: +  tft.setCursor(5, 120); 
-            text += str(data'utf8'+  tft.print("Feels:String(w_temp_feels)); 
-            pass +  tft.setCursor(5130); 
-        else+  tft.print("Humidity" + String(w_humidity) + "%"); 
-            a = text.split('\r\n\r\n'2)[1] +  tft.setCursor(5140); 
-            return a +  tft.print("Wind: " + String(w_wind, 1) + "m/s"); 
-            break+}
  
 +void loop() {
 +}
 +</file>
  
-json_data = http_get('http://api.weatherbit.io/v2.0/current?city=' + cityName + '&key=' + apiKey) +Не забудь заменить в коде название сети Wi-Fi и ее пароль.
- +
-if not json_data: +
-    raise SystemExit +
- +
-data = json.loads(json_data) +
- +
-wCity = data['data'][0]['city_name'+
-wTemp = round(data['data'][0]['temp']) +
-wTempFeels = data['data'][0]['app_temp'+
-wHumidity = data['data'][0]['rh'+
-wWind = data['data'][0]['wind_spd'+
- +
-pod = data['data'][0]['pod'+
- +
-wCode = int(data['data'][0]['weather']['code']) +
- +
-if wCode <= 233: +
-    wPic = '11' +
-elif (wCode >= 300 and wCode <= 520) or wCode == 522: +
-    wPic = '09' +
-elif wCode in  (521, 600): +
-    wPic = '10' +
-elif wCode >= 601 and wCode <= 622: +
-    wPic = '13' +
-elif wCode >= 623 and wCode <= 751: +
-    wPic = '50' +
-elif wCode == 800: +
-    wPic = '01' +
-elif wCode in (801, 802): +
-    wPic = '02' +
-elif wCode == 803: +
-    wPic = '03' +
-elif wCode == 804: +
-    wPic = '04' +
- +
-if (wTemp > 0): +
-    wTempPic = 'tp' +
-else: +
-    wTempPic = 'tn' +
- +
-tft.text(1,1,wCity, font.terminalfont, FontColor, 2) +
- +
-tft.draw_bmp(34,16,'/weather/' + wPic + pod + '.bmp'+
-tft.draw_bmp(5,70,'/weather/' + wTempPic + '.bmp'+
- +
-tft.text(30,75, str(wTemp), font.terminalfont, FontColor, 4) +
- +
-tft.text(5,120,"Feels: " + str(wTempFeels), font.terminalfont, FontColor2, 1) +
-tft.text(5,128,"Humidity: " + str(wHumidity) + "%", font.terminalfont, FontColor2, 1) +
-tft.text(5,136,"Wind: " + str(wWind) + "m/s", font.terminalfont, FontColor2, 1) +
-</file>+
  
-Не забудь заменить в коде название сети Wi-Fi и ее пароль +<code arduino[enable_line_numbers="2", start_line_numbers_at="13"]> 
-<code python[enable_line_numbers="2", start_line_numbers_at="12"]> +#define WIFI_NAME     "WiFi_name
-wlan_id = "Your_Wi-Fi+#define WIFI_PASSWORD "WiFi_pass"
-wlan_pass = "Your_Wi-Fi_Password"+
 </code> </code>
  
 Не забудь заменить в коде ключ доступа к сервису weatherbit.io, который мы получили во время эксперимента 69 Не забудь заменить в коде ключ доступа к сервису weatherbit.io, который мы получили во время эксперимента 69
-<code python[enable_line_numbers="2", start_line_numbers_at="39"]> +<code arduino[enable_line_numbers="2", start_line_numbers_at="62"]> 
-apiKey 'Your_Key'+  String API_key "YourApiKey";
 </code> </code>