0% found this document useful (0 votes)
10 views9 pages

Arduino Ethernet Light Sensor Code

The document contains code for an Arduino project that reads light levels from a sensor and sends data to a server via Ethernet. It includes setup and loop functions to initialize the Ethernet connection and handle HTTP requests based on light levels. The code also features error handling and debugging outputs for monitoring the connection status and data transmission.

Uploaded by

nirjhormahfuj390
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Arduino Ethernet Light Sensor Code

The document contains code for an Arduino project that reads light levels from a sensor and sends data to a server via Ethernet. It includes setup and loop functions to initialize the Ethernet connection and handle HTTP requests based on light levels. The code also features error handling and debugging outputs for monitoring the connection status and data transmission.

Uploaded by

nirjhormahfuj390
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Task:

Arduine Screenshots

PushingBox Screenshots:
Email Screenshot:
Code:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {

0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED

};

// Set the static IP address

IPAddress ip(192, 168, 0, 111);

// initialize the library instance:

EthernetClient client;

char server[16] = "[Link]";

char url[2000], devID[30] = "v1E76705507807C6"; //device id

#define LDRPIN A0 // define the LDR pin number

int lightlevel = 0;

boolean sendBox =false;

// last time you connected to the server, in milliseconds

unsigned long lastConnectionTime = 0;

// delay between updates, in milliseconds

long timegap = 10000UL;


void setup() {

pinMode(LDRPIN, INPUT);

// set the LDR pin on input to read from the sensor

// [Link](pin) to configure the CS pin

[Link](32);

// start serial port:

[Link](57600);

[Link](mac, ip);

[Link]("My IP address: ");

[Link]([Link]());

// give the Ethernet shield a second to initialize:

delay(1000);

void loop() {
lightlevel = 1024 - analogRead(LDRPIN); // read the light

// if there's an incoming data from the net connection,

// send it out through serial port. This is for debugging

// purposes only:

if([Link]("\r\n\r\n")) {

while ([Link]()) {

char c = [Link]();

[Link](c);

if(c == '1') {

[Link](" Successfully recorded");

if(lightlevel > 600) {

sendBox = true;

timegap = 1000; // send the message in 1 s

else {[Link](" Failed");}

}
if (millis() - lastConnectionTime > timegap) { // wait for timegap secs

if(sendBox)

httpRequest(1);

else

httpRequest(0);

// this method makes a HTTP connection to the server

void httpRequest(int todo)

[Link]();

// close any connection before send a new request

[Link]();

// if there's a successful connection

if ([Link](server, 80)) {

[Link]("Connected to server");

// Make a HTTP request

memset(url, '\0', 2000);


if (todo == 0) { // send light data

sprintf(url, "GET /alacritas_direct.php?acc=ahmahfuj&call=KIT717/iot/[Link]&t=%d


HTTP/1.1", lightlevel);

else if(todo == 1) { // send pushingBox message

sprintf(url, "GET /pbox_direct.php?devid=%s HTTP/1.1", devID);

sendBox = false;

timegap = 10000UL; // reset the time gap

[Link](url);

delay(10);

[Link](url);

[Link]("Host: [Link]");

[Link]("Connection: close");

[Link]();

lastConnectionTime = millis();

else {

// if you couldn't make a connection

[Link]("Connection failed");
}

Common questions

Powered by AI

The function 'client.connect(server, 80)' is used to establish a TCP connection between the Arduino and the specified server at IP address '192.168.0.1' on port 80, which is the default port for HTTP communication. This facilitates the Arduino device's ability to send HTTP requests and receive responses from the server.

The 'mac' byte array is used to define the Ethernet hardware (MAC) address for the device. This address is necessary for network identification and communication, allowing other network devices to recognize and interact with the Arduino device. Setting a unique MAC address ensures that there is no conflict with other devices on the same network.

The variable 'timegap' is used to control the frequency of HTTP requests sent from the Arduino to the server. Initially set to 10,000 ms (10 seconds), this delay determines the minimum interval between consecutive requests, preventing the Arduino from overwhelming the server with too frequent data transmissions.

The inclusion of 'delay(10)' likely serves to provide a brief pause after URL preparation to ensure that the network stack has sufficient time to process and flush the previous operations before sending the request. This helps in stabilizing the communication by avoiding race conditions where the request may be sent prematurely, potentially causing incomplete data transfer or errors.

Hardcoding IP addresses, as seen in 'IPAddress ip(192, 168, 0, 111)' and 'char server[16] = "192.168.0.1"', might lead to network issues like conflicts if these addresses are used by other devices. It limits flexibility when network changes occur, requiring manual updates to the code for different environments. Additionally, it might prevent the Arduino device from functioning properly if the network topology or address ranges change, necessitating dynamic IP allocation through DHCP for greater adaptability.

Using 'millis()' for managing timed events allows for non-blocking delays, enabling the Arduino to perform other tasks simultaneously without halting execution. It tracks elapsed time since the board's startup, providing accuracy and reliability in managing periodic events like HTTP requests. This method is effective for real-time applications, ensuring that delays don't interfere with other processes, though care must be taken to handle 'millis()' rollover appropriately.

The Arduino sketch uses a conditional check 'if(lightlevel > 600)' to decide whether to set the 'sendBox' boolean to true. This condition ensures that the server only receives data when the light level surpasses 600, triggering a message send operation in the next loop iteration. This mechanism reduces unnecessary data transmission.

'Serial.println()' is used throughout the Arduino code to output messages to the serial console, aiding in real-time monitoring of the device's operations. By printing statuses like IP addresses and connection messages, developers can track network configuration successes and failures. These outputs provide essential insights during debugging, enabling quicker identification of issues and verifying the functionality of code segments, particularly for network and client-server interaction troubleshooting.

The Arduino code's approach involves direct HTTP requests without secure protocols like HTTPS, leaving data vulnerable to interception and tampering. Lack of authentication measures further exposes the device to unauthorized access. Such vulnerabilities pose significant security risks, especially in environments where sensitive data is transmitted, necessitating the implementation of secure communication protocols and authentication mechanisms to protect against potential threats.

The Arduino code reads the server response using 'client.read()' within a loop that executes if a valid HTTP header end is found ('if(client.find("\r\n\r\n"))'). The response characters are printed to the serial output, aiding in debugging by providing visibility into successful or failed server interactions, such as recording success with the character '1'. This approach allows developers to verify communication success and diagnose issues at runtime.

You might also like