Rewrote server to work with Serial rather than Wifi (missing Wifi component on the Arduino)

This commit is contained in:
nmascrie 2025-03-05 15:21:57 +01:00
parent e9dc6c38ee
commit 7e2211dc50
5 changed files with 56 additions and 76 deletions

1
.gitignore vendored
View File

@ -0,0 +1 @@
ArduinoCube/arduino_secrets.h

View File

@ -12,8 +12,8 @@
*/ */
#include <Arduino_APDS9960.h> #include <Arduino_APDS9960.h>
//#include <WiFiNINA.h>
#include "arduino_secrets.h" #include "arduino_secrets.h"
#include <Arduino.h>
#define TRIGG_BOTTOM D12 #define TRIGG_BOTTOM D12
#define TRIGG_TOP D10 #define TRIGG_TOP D10
@ -41,21 +41,6 @@ int status = STATUS_SAFE;
int ledState = LOW; int ledState = LOW;
//please enter your sensitive data in the Secret tab
//char ssid[] = SECRET_SSID; // your network SSID (name)
//char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
unsigned long previousMillis = 0;
const long intervalLong = 750;
const long intervalMedLo = 250;
const long intervalMed = 150;
const long intervalMedSho = 80;
const long intervalShort = 20;
const int trigger = 12;
const int echo = 11;
//std::string sides[6]; //std::string sides[6];
std::string sides[6] = {"Bottom", "Top", "Right", "Front", "Left", "Back"}; std::string sides[6] = {"Bottom", "Top", "Right", "Front", "Left", "Back"};
@ -71,10 +56,14 @@ void setup() {
Serial.begin(9600); Serial.begin(9600);
Serial.println("Starting up"); Serial.println("Starting up");
while (!Serial);
Serial.println("Serial connected.");
if (!APDS.begin()) { if (!APDS.begin()) {
Serial.println("Error initializing APDS-9960 sensor!"); Serial.println("Error initializing APDS-9960 sensor!");
while (1); while (1);
} }
pinMode(LED_BUILTIN, OUTPUT); pinMode(LED_BUILTIN, OUTPUT);
//Init the sensors //Init the sensors
@ -114,26 +103,41 @@ int fire_sensor(int trigger, int echo)
return (dist); return (dist);
} }
/**
* Sends the data to the server.
*/
void send_JSON()
{
std::string json = "{";
json += "\"" + sides[0] + "\":" + std::to_string(distances[0]) + ",";
json += "\"" + sides[1] + "\":" + std::to_string(distances[1]) + ",";
json += "\"" + sides[2] + "\":" + std::to_string(distances[2]) + ",";
json += "\"" + sides[3] + "\":" + std::to_string(distances[3]) + ",";
json += "\"" + sides[4] + "\":" + std::to_string(distances[4]) + ",";
json += "\"" + sides[5] + "\":" + std::to_string(distances[5]) + "";
json += "}";
Serial.println(json.c_str());
}
void loop() { void loop() {
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
Serial.print("Measure number ");
Serial.println(count);
distances[0] = fire_sensor(TRIGG_BOTTOM, ECHO_BOTTOM); distances[0] = fire_sensor(TRIGG_BOTTOM, ECHO_BOTTOM);
distances[1] = fire_sensor(TRIGG_TOP, ECHO_TOP); distances[1] = fire_sensor(TRIGG_TOP, ECHO_TOP);
distances[2] = fire_sensor(TRIGG_1, ECHO_1); distances[2] = fire_sensor(TRIGG_1, ECHO_1);
distances[3] = fire_sensor(TRIGG_2, ECHO_2); distances[3] = fire_sensor(TRIGG_2, ECHO_2);
distances[4] = fire_sensor(TRIGG_3, ECHO_3); distances[4] = fire_sensor(TRIGG_3, ECHO_3);
distances[5] = fire_sensor(TRIGG_4, ECHO_4); distances[5] = fire_sensor(TRIGG_4, ECHO_4);
send_JSON();
for (int i = 0; i < 6; i++) /*for (int i = 0; i < 6; i++)
{ {
Serial.print("Sensor {"); Serial.print("Sensor {");
Serial.print(sides[i].c_str()); Serial.print(sides[i].c_str());
Serial.print("} : "); Serial.print("} : ");
Serial.print(distances[i]); Serial.print(distances[i]);
Serial.println("cm"); Serial.println("cm");
} }*/
//update_status(distance); //update_status(distance);
// wait a bit before reading again // wait a bit before reading again

View File

@ -1,5 +1,5 @@
#define SSID "Non" #define SSID "42LeHavre_guest"
#define PASS "Non" #define PASS ""
#define SERV_ADDR "Non" #define SERV_ADDR "10.11.3.3"
#define SERV_PORT "Non" #define SERV_PORT 8080
#define AI_KEY "Non" #define AI_KEY "Non"

0
secret Normal file
View File

View File

@ -1,57 +1,32 @@
#!/usr/bin/env python3 import serial
""" import requests
License: MIT License
Copyright (c) 2023 Miel Donkers
Very simple HTTP server in python for logging requests
Usage::
./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import json import json
class S(BaseHTTPRequestHandler): # Adjust this to match your serial port
def _set_response(self): SERIAL_PORT = "/dev/ttyACM0" # Linux/macOS (Check with `ls /dev/tty*`)
self.send_response(200) # SERIAL_PORT = "COM3" # Windows (Check with Device Manager)
self.send_header('Content-type', 'text/html') BAUD_RATE = 115200
self.end_headers() SERVER_URL = "http://127.0.0.1:8080" # Change to your server's IP if needed
def do_GET(self): # Open Serial Connection
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers)) ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
self._set_response() print(f"Listening on {SERIAL_PORT}...")
self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
def do_POST(self): while True:
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
# Parse JSON
try:
data = json.loads(post_data.decode('utf-8'))
logging.info("Received data: %s", data)
except json.JSONDecodeError:
logging.error("Failed to decode JSON")
self._set_response()
self.wfile.write("Received JSON data".encode('utf-8'))
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try: try:
httpd.serve_forever() if ser.in_waiting > 0:
data = ser.readline().decode("utf-8").strip()
print("Received:", data)
# Validate JSON
try:
json_data = json.loads(data)
# Send data to HTTP server
print("Server response:", json_data)
except json.JSONDecodeError:
print("Invalid JSON received:", data)
except KeyboardInterrupt: except KeyboardInterrupt:
pass print("\nClosing Serial Connection...")
httpd.server_close() ser.close()
logging.info('Stopping httpd...\n') break
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()