Commit 1c887a91 authored by Jonathan Poalses's avatar Jonathan Poalses

Initial commit

parents
#include <WiFiNINA.h>
//Set up wifi global variables
char ssid[] = "TP-Link_E9D7";
char pass[] = "27309612";
int status = WL_IDLE_STATUS;
//Set up server global variables
IPAddress server(192,168,0,65);
int serverPort = 28800;
//Set up delay global variables
int pollDelay = 1000;
int connectionDelay = 10000;
//Set up the PIR status
int lastStatus = 0;
//Set up the Wifi client
WiFiClient client;
void setup() {
//Set up serial connection
Serial.begin(9600);
while (!Serial);
//Set up the input pin
pinMode(4, INPUT);
digitalWrite(4, LOW);
//Set up the output pin
pinMode(8, OUTPUT);
digitalWrite(8, LOW);
//Set up the status LED
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
//Initial connection to Wifi and server
connectToWifi();
connectToServer();
}
void loop() {
//Check for wifi connection, if absent, reconnect
if (status != WL_CONNECTED) {
Serial.println("Wifi connection lost");
connectToWifi();
}
//Check for server connection, if absent, reconnect
if (!client.connected()) {
Serial.println("Server connection lost");
connectToServer();
}
//Read any data being sent from the server and print it the the serial
if (client.available()) {
while (client.available()) {
char data = client.read();
if (data == 'a') {
digitalWrite(8, HIGH);
Serial.println("Lights On");
} else if (data == 'd') {
digitalWrite(8, LOW);
Serial.println("Lights Off");
} else {
Serial.write(data);
}
}
}
//Read the input pin for the PIR sensor, and send results to the server
if (digitalRead(4) == HIGH) {
//If previously no person was detected, send a 1 and set last status to 1
if (lastStatus == 0) {
client.println("1");
lastStatus = 1;
}
} else {
//If previously a person was detected, send a 0 and set last status to 0
if (lastStatus == 1) {
client.println("0");
lastStatus = 0;
}
}
//Set built in LED low while waiting
digitalWrite(LED_BUILTIN, LOW);
//Wait a little to not spam the server
delay(pollDelay);
//Set built in LED high while working
digitalWrite(LED_BUILTIN, HIGH);
}
void connectToWifi() {
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to network: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(connectionDelay);
}
Serial.println("Connection Successful");
Serial.print("Connected with IP address: ");
Serial.println(WiFi.localIP());
}
void connectToServer() {
while (!client.connected()) {
Serial.print("Attempting to connect to server: ");
Serial.print(server);
Serial.print(":");
Serial.println(serverPort);
client.stop();
client.connect(server, serverPort);
delay(connectionDelay);
}
Serial.println("Connection Successful");
client.println("Hello!");
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment