Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This sketch sends a string to a TCP server, and prints a one-line response.
- You must run a TCP server in your local network.
- For example, on Linux you can use this command: nc -v -l 3000
- */
- #include <ESP8266WiFi.h>
- #include <ESP8266WiFiMulti.h>
- #ifndef STASSID
- #define STASSID "SSID"
- #define STAPSK "PASSWORD"
- #endif
- const char* ssid = STASSID;
- const char* password = STAPSK;
- const char* host = "192.168.137.1";
- const uint16_t port = 8080;
- const int buttonPin = D2;
- int buttonState = 0;
- const int led = 13;
- ESP8266WiFiMulti WiFiMulti;
- void setup() {
- pinMode(buttonPin, INPUT);
- pinMode(led, OUTPUT);
- digitalWrite(led, 0);
- Serial.begin(115200);
- // We start by connecting to a WiFi network
- WiFi.mode(WIFI_STA);
- WiFiMulti.addAP(ssid, password);
- Serial.println();
- Serial.println();
- Serial.print("Wait for WiFi... ");
- while (WiFiMulti.run() != WL_CONNECTED) {
- Serial.print(".");
- delay(500);
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- delay(500);
- }
- void loop() {
- Serial.print("connecting to ");
- Serial.print(host);
- Serial.print(':');
- Serial.println(port);
- // Use WiFiClient class to create TCP connections
- WiFiClient client;
- if (!client.connect(host, port)) {
- Serial.println("connection failed");
- Serial.println("wait 5 sec...");
- delay(5000);
- return;
- }
- // This will send the request to the server
- digitalWrite(led, 1);
- buttonState = digitalRead(buttonPin);
- if (buttonState == HIGH) {
- client.println("1");
- } else {
- client.println("0");
- }
- //read back one line from server
- Serial.println("receiving from remote server");
- String line = client.readStringUntil('\r');
- Serial.println(line);
- Serial.println("closing connection");
- client.stop();
- Serial.println("wait 1 sec...");
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement