Advertisement
Guest User

arduino code

a guest
Dec 7th, 2019
983
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /*
  2.     This sketch sends a string to a TCP server, and prints a one-line response.
  3.     You must run a TCP server in your local network.
  4.     For example, on Linux you can use this command: nc -v -l 3000
  5. */
  6.  
  7. #include <ESP8266WiFi.h>
  8. #include <ESP8266WiFiMulti.h>
  9.  
  10. #ifndef STASSID
  11. #define STASSID "SSID"
  12. #define STAPSK  "PASSWORD"
  13. #endif
  14.  
  15. const char* ssid     = STASSID;
  16. const char* password = STAPSK;
  17.  
  18. const char* host = "192.168.137.1";
  19. const uint16_t port = 8080;
  20.  
  21. const int buttonPin = D2;
  22. int buttonState = 0;
  23. const int led = 13;
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30. ESP8266WiFiMulti WiFiMulti;
  31.  
  32. void setup() {
  33.  
  34.   pinMode(buttonPin, INPUT);
  35.   pinMode(led, OUTPUT);
  36.   digitalWrite(led, 0);
  37.   Serial.begin(115200);
  38.  
  39.   // We start by connecting to a WiFi network
  40.   WiFi.mode(WIFI_STA);
  41.   WiFiMulti.addAP(ssid, password);
  42.  
  43.   Serial.println();
  44.   Serial.println();
  45.   Serial.print("Wait for WiFi... ");
  46.  
  47.   while (WiFiMulti.run() != WL_CONNECTED) {
  48.     Serial.print(".");
  49.     delay(500);
  50.   }
  51.  
  52.   Serial.println("");
  53.   Serial.println("WiFi connected");
  54.   Serial.println("IP address: ");
  55.   Serial.println(WiFi.localIP());
  56.  
  57.   delay(500);
  58. }
  59.  
  60.  
  61. void loop() {
  62.   Serial.print("connecting to ");
  63.   Serial.print(host);
  64.   Serial.print(':');
  65.   Serial.println(port);
  66.  
  67.   // Use WiFiClient class to create TCP connections
  68.   WiFiClient client;
  69.  
  70.   if (!client.connect(host, port)) {
  71.     Serial.println("connection failed");
  72.     Serial.println("wait 5 sec...");
  73.     delay(5000);
  74.     return;
  75.   }
  76.  
  77.   // This will send the request to the server
  78.   digitalWrite(led, 1);
  79.  
  80.   buttonState = digitalRead(buttonPin);
  81.  
  82.  
  83.   if (buttonState == HIGH) {
  84.     client.println("1");
  85.   } else {
  86.     client.println("0");
  87.   }
  88.  
  89.  
  90.   //read back one line from server
  91.   Serial.println("receiving from remote server");
  92.   String line = client.readStringUntil('\r');
  93.   Serial.println(line);
  94.  
  95.   Serial.println("closing connection");
  96.   client.stop();
  97.  
  98.   Serial.println("wait 1 sec...");
  99.   delay(1000);
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement