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");
  }
}
Output

Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad