Programming Examples

Arduino program to read data from sensor and send it to a requesting client.


Write a program to read data from sensor and send it to a requesting client. (Using socket communication) Note: The client and server should be connected to same local area network.

Solution

#ifdef ESP8266
  #include 
#else
  #include 
#endif
const char* ssid = "Your_WiFi_Name";
const char* password = "Your_WiFi_Password";
WiFiServer server(80);     // TCP socket server on port 80
const int sensorPin = A0; // Sensor connected to A0
void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi Connected!");
  Serial.print("Server IP Address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}
void loop() {
  WiFiClient client = server.available();  // Wait for client
  if (client) {
    Serial.println("Client Connected");
    int sensorValue = analogRead(sensorPin);  // Read sensor
    // Send sensor data to client
    client.print("Sensor Value: ");
    client.println(sensorValue);
    client.stop();  // Close connection
    Serial.println("Client Disconnected");
  }
}
▶ RUN

Output/ Explanation:

Latest Current Affairs 2026 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad