Skip to content
Snippets Groups Projects
Commit 47c32db4 authored by mhby1g21's avatar mhby1g21
Browse files

works ish idk

parent 7acd6de3
No related branches found
No related tags found
No related merge requests found
...@@ -5,7 +5,7 @@ const char ssid[] = "SOTON-IoT"; ...@@ -5,7 +5,7 @@ const char ssid[] = "SOTON-IoT";
const char pass[] = "pUguZXWtBDzl"; const char pass[] = "pUguZXWtBDzl";
int status = WL_IDLE_STATUS; int status = WL_IDLE_STATUS;
unsigned long lastConnectionAttempt = 0; unsigned long lastConnectionAttempt = 0;
const unsigned long connectionRetryInterval = 10000; // 10 seconds between reconnection attempts const unsigned long connectionRetryInterval = 1000; // 1 seconds between reconnection attempts
// Server settings // Server settings
WiFiServer server(80); WiFiServer server(80);
...@@ -41,7 +41,7 @@ enum MovementState { ...@@ -41,7 +41,7 @@ enum MovementState {
MovementState currentState = STATE_STOP; MovementState currentState = STATE_STOP;
unsigned long lastCommandTime = 0; unsigned long lastCommandTime = 0;
const unsigned long commandTimeout = 10000; // 10 seconds timeout for safety const unsigned long commandTimeout = 30000; // 30 seconds timeout for safety
// Simple watchdog implementation // Simple watchdog implementation
unsigned long lastWatchdogTime = 0; unsigned long lastWatchdogTime = 0;
...@@ -54,6 +54,10 @@ bool newCommandReceived = false; ...@@ -54,6 +54,10 @@ bool newCommandReceived = false;
// Connection monitoring // Connection monitoring
unsigned long lastConnectionCheck = 0; unsigned long lastConnectionCheck = 0;
const unsigned long connectionCheckInterval = 5000; // Check connection every 5 seconds const unsigned long connectionCheckInterval = 5000; // Check connection every 5 seconds
bool hasValidIP = false;
// DNS settings to help with connectivity
IPAddress dns(8, 8, 8, 8); // Google DNS
void setup() { void setup() {
// Initialize serial // Initialize serial
...@@ -76,8 +80,16 @@ void setup() { ...@@ -76,8 +80,16 @@ void setup() {
stopMotors(); stopMotors();
digitalWrite(MOVING_LED, LOW); digitalWrite(MOVING_LED, LOW);
// Connect to WiFi // Connect to WiFi - try multiple times if needed
connectToWiFi(); bool connected = false;
for (int attempt = 0; attempt < 3 && !connected; attempt++) {
Serial.print("Connection attempt #");
Serial.println(attempt + 1);
connected = connectToWiFi();
if (!connected) {
delay(5000); // Wait between attempts
}
}
// Initialize watchdog time // Initialize watchdog time
lastWatchdogTime = millis(); lastWatchdogTime = millis();
...@@ -94,6 +106,8 @@ void loop() { ...@@ -94,6 +106,8 @@ void loop() {
checkWiFiConnection(); checkWiFiConnection();
} }
// Only handle client requests if we have a valid IP
if (hasValidIP) {
// Check for new HTTP connections // Check for new HTTP connections
handleHTTPClient(); handleHTTPClient();
...@@ -102,9 +116,10 @@ void loop() { ...@@ -102,9 +116,10 @@ void loop() {
processCommand(lastCommand); processCommand(lastCommand);
newCommandReceived = false; newCommandReceived = false;
} }
}
// Check for command timeout (safety feature) // Check for command timeout (safety feature)
if (currentState != STATE_STOP && if (commandTimeout > 0 && currentState != STATE_STOP &&
(currentMillis - lastCommandTime >= commandTimeout)) { (currentMillis - lastCommandTime >= commandTimeout)) {
Serial.println("Command timeout - stopping motors for safety"); Serial.println("Command timeout - stopping motors for safety");
executeStop(); executeStop();
...@@ -116,18 +131,39 @@ void simpleWatchdog() { ...@@ -116,18 +131,39 @@ void simpleWatchdog() {
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
if (currentMillis - lastWatchdogTime >= watchdogInterval) { if (currentMillis - lastWatchdogTime >= watchdogInterval) {
lastWatchdogTime = currentMillis; lastWatchdogTime = currentMillis;
// Perform any critical checks here
// This is a good place to verify system state // Report current state periodically
if (currentState != STATE_STOP) {
Serial.print("Currently ");
Serial.print(getStateString(currentState));
Serial.println(" - maintaining movement until stopped");
}
// Periodically check IP validity if we think we're connected
if (WiFi.status() == WL_CONNECTED) {
IPAddress ip = WiFi.localIP();
if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
hasValidIP = false;
Serial.println("WARNING: No valid IP address obtained");
} else {
if (!hasValidIP) {
// Just got a valid IP
hasValidIP = true;
server.begin();
printWiFiStatus();
}
}
}
} }
} }
void connectToWiFi() { bool connectToWiFi() {
// Check for WiFi module // Check for WiFi module
if (WiFi.status() == WL_NO_MODULE) { if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!"); Serial.println("Communication with WiFi module failed!");
// Blink error code on LED // Blink error code on LED
blinkLED(WIFI_LED, 5, 500); blinkLED(WIFI_LED, 5, 500);
while (true); // Cannot continue without WiFi module return false;
} }
// Print firmware version // Print firmware version
...@@ -138,6 +174,13 @@ void connectToWiFi() { ...@@ -138,6 +174,13 @@ void connectToWiFi() {
// Set WiFi LED to indicate connecting // Set WiFi LED to indicate connecting
digitalWrite(WIFI_LED, HIGH); digitalWrite(WIFI_LED, HIGH);
// Disconnect if already connected
WiFi.disconnect();
delay(1000);
// Configure WiFi to use Google DNS to help with IP acquisition
WiFi.setDNS(dns);
// Attempt to connect to WiFi network // Attempt to connect to WiFi network
Serial.print("Attempting to connect to Network: "); Serial.print("Attempting to connect to Network: ");
Serial.println(ssid); Serial.println(ssid);
...@@ -146,7 +189,7 @@ void connectToWiFi() { ...@@ -146,7 +189,7 @@ void connectToWiFi() {
// Wait for connection or timeout // Wait for connection or timeout
int attempts = 0; int attempts = 0;
while (status != WL_CONNECTED && attempts < 20) { while (status != WL_CONNECTED && attempts < 30) { // Increased timeout to 15 seconds
delay(500); delay(500);
Serial.print("."); Serial.print(".");
attempts++; attempts++;
...@@ -157,46 +200,57 @@ void connectToWiFi() { ...@@ -157,46 +200,57 @@ void connectToWiFi() {
if (status == WL_CONNECTED) { if (status == WL_CONNECTED) {
Serial.println("\nConnected to WiFi"); Serial.println("\nConnected to WiFi");
digitalWrite(WIFI_LED, HIGH); // Solid on for connected digitalWrite(WIFI_LED, HIGH); // Solid on for connected
// Check for valid IP address
IPAddress ip = WiFi.localIP();
if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
Serial.println("Connected to WiFi but no valid IP address obtained. Will retry...");
digitalWrite(WIFI_LED, LOW);
hasValidIP = false;
return false;
}
hasValidIP = true;
printWiFiStatus(); printWiFiStatus();
server.begin(); server.begin();
Serial.println("EMG-controlled car server started"); Serial.println("EMG-controlled car server started");
return true;
} else { } else {
Serial.println("\nFailed to connect to WiFi"); Serial.println("\nFailed to connect to WiFi");
digitalWrite(WIFI_LED, LOW); digitalWrite(WIFI_LED, LOW);
hasValidIP = false;
return false;
} }
lastConnectionAttempt = millis(); lastConnectionAttempt = millis();
} }
void checkWiFiConnection() { void checkWiFiConnection() {
if (WiFi.status() != WL_CONNECTED) { if (WiFi.status() != WL_CONNECTED || !hasValidIP) {
digitalWrite(WIFI_LED, LOW); digitalWrite(WIFI_LED, LOW);
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi connection lost!"); Serial.println("WiFi connection lost!");
} else {
Serial.println("Connected but no valid IP address!");
}
// Only try reconnecting if enough time has passed since last attempt // Only try reconnecting if enough time has passed since last attempt
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
if (currentMillis - lastConnectionAttempt >= connectionRetryInterval) { if (currentMillis - lastConnectionAttempt >= connectionRetryInterval) {
Serial.println("Attempting to reconnect..."); connectToWiFi();
WiFi.disconnect();
delay(1000);
status = WiFi.begin(ssid, pass);
// Wait briefly for connection
delay(5000);
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Successfully reconnected to WiFi");
digitalWrite(WIFI_LED, HIGH);
server.begin();
} else {
Serial.println("Reconnection failed");
}
lastConnectionAttempt = currentMillis; lastConnectionAttempt = currentMillis;
} }
} else { } else {
digitalWrite(WIFI_LED, HIGH); // Ensure LED is on when connected digitalWrite(WIFI_LED, HIGH); // Ensure LED is on when connected
// Double-check IP validity
IPAddress ip = WiFi.localIP();
if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
hasValidIP = false;
Serial.println("IP address became invalid!");
}
} }
} }
...@@ -262,7 +316,9 @@ void sendHTTPResponse() { ...@@ -262,7 +316,9 @@ void sendHTTPResponse() {
response += "{\r\n"; response += "{\r\n";
response += " \"status\": \"ok\",\r\n"; response += " \"status\": \"ok\",\r\n";
response += " \"movement\": \"" + getStateString(currentState) + "\",\r\n"; response += " \"movement\": \"" + getStateString(currentState) + "\",\r\n";
response += " \"command_received\": true\r\n"; response += " \"command_received\": true,\r\n";
response += " \"continuous\": true,\r\n";
response += " \"ip\": \"" + WiFi.localIP().toString() + "\"\r\n";
response += "}\r\n"; response += "}\r\n";
client.print(response); client.print(response);
...@@ -317,6 +373,12 @@ void processCommand(String command) { ...@@ -317,6 +373,12 @@ void processCommand(String command) {
// Just for connection testing // Just for connection testing
Serial.println("Ping received - connection test successful"); Serial.println("Ping received - connection test successful");
} }
else if (command == "reconnect") {
// Force WiFi reconnection
Serial.println("Reconnect command received - restarting WiFi");
hasValidIP = false;
connectToWiFi();
}
else { else {
Serial.println("Unknown command: " + command); Serial.println("Unknown command: " + command);
} }
...@@ -324,7 +386,7 @@ void processCommand(String command) { ...@@ -324,7 +386,7 @@ void processCommand(String command) {
void executeForward() { void executeForward() {
if (currentState != STATE_FORWARD) { if (currentState != STATE_FORWARD) {
Serial.println("Moving forward"); Serial.println("Moving forward - will continue until stopped");
// Motor A forward // Motor A forward
digitalWrite(IN1, HIGH); digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW); digitalWrite(IN2, LOW);
...@@ -337,12 +399,15 @@ void executeForward() { ...@@ -337,12 +399,15 @@ void executeForward() {
currentState = STATE_FORWARD; currentState = STATE_FORWARD;
digitalWrite(MOVING_LED, HIGH); digitalWrite(MOVING_LED, HIGH);
} else {
// Already moving forward, just refresh the command time
Serial.println("Already moving forward - continuing movement");
} }
} }
void executeBackward() { void executeBackward() {
if (currentState != STATE_BACKWARD) { if (currentState != STATE_BACKWARD) {
Serial.println("Moving backward"); Serial.println("Moving backward - will continue until stopped");
// Motor A backward // Motor A backward
digitalWrite(IN1, LOW); digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH); digitalWrite(IN2, HIGH);
...@@ -355,12 +420,15 @@ void executeBackward() { ...@@ -355,12 +420,15 @@ void executeBackward() {
currentState = STATE_BACKWARD; currentState = STATE_BACKWARD;
digitalWrite(MOVING_LED, HIGH); digitalWrite(MOVING_LED, HIGH);
} else {
// Already moving backward, just refresh the command time
Serial.println("Already moving backward - continuing movement");
} }
} }
void executeLeft() { void executeLeft() {
if (currentState != STATE_LEFT) { if (currentState != STATE_LEFT) {
Serial.println("Turning left"); Serial.println("Turning left - will continue until stopped");
// Motor A forward // Motor A forward
digitalWrite(IN1, HIGH); digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW); digitalWrite(IN2, LOW);
...@@ -373,12 +441,15 @@ void executeLeft() { ...@@ -373,12 +441,15 @@ void executeLeft() {
currentState = STATE_LEFT; currentState = STATE_LEFT;
digitalWrite(MOVING_LED, HIGH); digitalWrite(MOVING_LED, HIGH);
} else {
// Already turning left, just refresh the command time
Serial.println("Already turning left - continuing movement");
} }
} }
void executeRight() { void executeRight() {
if (currentState != STATE_RIGHT) { if (currentState != STATE_RIGHT) {
Serial.println("Turning right"); Serial.println("Turning right - will continue until stopped");
// Motor A backward for sharp turn // Motor A backward for sharp turn
digitalWrite(IN1, LOW); digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH); digitalWrite(IN2, HIGH);
...@@ -391,6 +462,9 @@ void executeRight() { ...@@ -391,6 +462,9 @@ void executeRight() {
currentState = STATE_RIGHT; currentState = STATE_RIGHT;
digitalWrite(MOVING_LED, HIGH); digitalWrite(MOVING_LED, HIGH);
} else {
// Already turning right, just refresh the command time
Serial.println("Already turning right - continuing movement");
} }
} }
...@@ -448,5 +522,5 @@ void printWiFiStatus() { ...@@ -448,5 +522,5 @@ void printWiFiStatus() {
Serial.print("http://"); Serial.print("http://");
Serial.print(ip); Serial.print(ip);
Serial.println("/command"); Serial.println("/command");
Serial.println("Where command is: forward, backward, left, right, or stop"); Serial.println("Where command is: forward, backward, left, right, stop, or reconnect");
} }
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment