首页 > 解决方案 > 连接被拒绝 ESP32

问题描述

我有使用带有 ESP32 的 GSR 传感器的项目。来自 ESP32 的数据保存在数据库中。

但是,在我的代码中我有一个错误。使用静态 IP 时,HTTPClient.begin()总是返回连接被拒绝。

我已经看到这个问题被问了几次,但从来没有得到一个好的答案。

#include <ssl_client.h>
#include <WiFiClientSecure.h>

#include <WiFi.h>
#include <SPI.h>
#include <WiFiClient.h>
#include <HTTPClient.h>

#define USE_SERIAL Serial

/* Konfigurasi pada SSID dan Password Wifi */
const char* ssid     = "AndroidAP";         
const char* password = "stayC00L";  

/* Konfigurasi koneksi ke server */
char server[] = "192.168.43.111";     // Ganti dengan IP Address komputer aplikasi 
int port = 81;

/*konfigurasi*/
const int GSR = 32;
float sensorValue = 0;
float gsr_average = 0;

IPAddress local_IP(192, 168, 43, 113);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(8, 8, 8, 8); // Google DNS

WiFiClient client;
void setup() {
  
  USE_SERIAL.begin(9600);         // Baudrate/kec. komunikasi pengiriman data ke serial terminal
  delay(10);
  Serial.println('\n');
  
  WiFi.begin(ssid, password);      
  USE_SERIAL.print("Terhubung ke ");
  USE_SERIAL.print(ssid);

  WiFi.config(local_IP, gateway, subnet, dns);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    USE_SERIAL.print('.');
  }

  USE_SERIAL.print('\n');
  USE_SERIAL.println("Identitas ESP-32");  
  USE_SERIAL.print("IP Address:\t");
  USE_SERIAL.println(WiFi.localIP());         // IP Address ESP-32  

  USE_SERIAL.print('\n');
  USE_SERIAL.println("Identitas Web Server");
  USE_SERIAL.println("IP Address:");
  USE_SERIAL.print(server);
  USE_SERIAL.print("\tport:\t");
  USE_SERIAL.print(port);
}


void loop() {
  
    long sum=0;
    for(int i=0;i<10;i++)           //Average the 10 measurements to remove the glitch
    {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(100);
    }
    gsr_average = sum/10;
    USE_SERIAL.println(gsr_average);

  if(WiFi.status() == WL_CONNECTED){
    //URL target untuk menyimpan data sensor GSR ke database
    String url = "http://192.168.43.111:81/";
    url += "TA/Monitoring/simpan/";
    url += String(gsr_average);

    HTTPClient http;
    USE_SERIAL.print("[HTTP] begin...\n");
    http.begin(url);
    USE_SERIAL.print("[HTTP] GET...\n");
    
    int httpCode = http.GET();
    if(httpCode > 0) {
        USE_SERIAL.printf("[HTTP] GET... code: %d\n", 
        httpCode);
      
         if(httpCode == HTTP_CODE_OK) {
            String payload = http.getString();
            USE_SERIAL.println(payload);
         }
      } else {
        USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", 
        http.errorToString(httpCode).c_str());
      } 
      http.end();
   }
}

错误是

拒绝连接

请帮我。我应该怎么办??

标签: c++c

解决方案


尝试删除:

IPAddress local_IP(192, 168, 43, 113);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(8, 8, 8, 8); // Google DNS

和 :

WiFi.config(local_IP, gateway, subnet, dns);

经过这次修改后,它对我来说非常有效。

回复 200


推荐阅读