"没有可用的插座" - Arduino上的Wifi Shield

时间:2017-03-30 22:32:22

标签: sockets arduino arduino-uno arduino-ide

我有一个LDR / Photocell,它将值1或0(取决于值)发送到我的网址上的文本文件。代码可以工作几秒钟然后打印出No Socket available

任何帮助将不胜感激;代码如下。

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

int LDR = A0;
int LED = 11;
char ssid[] = "SSID";
char password[] = "password";
int status = WL_IDLE_STATUS;


char server[] = "www.example.com";
int value;

void setup() {
  Serial.begin(9600);
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  connectWifi();
  printWifiStatus();
  // postData();
}

void loop() {
  value = analogRead(LDR);
  postData();

  delay(10000);
}

void connectWifi() {
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, password);
    delay(500);
  }
}

void printWifiStatus() {
  // Print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // Print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void postData() {
  WiFiClient client;
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    if (value > 350) {
      Serial.println("0");
      digitalWrite(LED, LOW);
      String data = "value=0";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    } else {
      Serial.println("1");
      digitalWrite(LED, HIGH);
      String data = "value=1";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    }
  } else {
    Serial.println("Connection failed");
    client.stop();
  }

}

输出:

Attempting to connect to SSID
SSID: SSID
IP Address: 255.255.255.255
signal strength (RSSI):-47 dBm
Connecting...
1
Connecting...
0
Connecting...
0
Connecting...
0
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available

省略了实际网址。

1 个答案:

答案 0 :(得分:1)

首先,尽量不要使用&#34; delay()&#34;并且你正在调用这个功能&#34; postData()&#34;每0.5秒。尝试使用millis()函数来执行计时器操作,如下所示:

unsigned long timerBefore = 0;
const int timer = 1000; //1 second

现在位于loop()

unsigned long timerNow=millis();
if((unsigned long)(timerNow-timerBefore)>=timer){
   postData();
   timerBefore=millis();
}

该代码我不会&#34;暂停&#34;你的微控制器,每隔一秒调用一次该功能。