WiFi control working

This commit is contained in:
Jared Dunbar 2023-03-12 01:13:49 -05:00
parent bb6e0c75da
commit a1235262c7
4 changed files with 63 additions and 18 deletions

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
.pio
src/wifi.h
src/creds.h
.vscode/

View File

@ -16,4 +16,6 @@ name = WiFiTrainReceiver
[env:esp32dev]
platform = espressif32
framework = arduino
board = esp32dev
board = esp32dev
lib_deps =
ArduinoJson

16
src/creds.h.txt Normal file
View File

@ -0,0 +1,16 @@
#ifndef CREDS_H
#define CREDS_H
/*
INSTRUCTIONS:
Change the text inside of the " characters to contain your SSID and Password for your WiFi
After that, rename this file from ending in .txt to .h and compile.
*/
#define WIFI_SSID "YOUR SSID HERE"
#define WIFI_PASS "YOUR PASSWORD HERE!"
#endif

View File

@ -1,23 +1,33 @@
#include "Arduino.h"
#include <WiFi.h>
#include "WiFi.h"
#include <HTTPClient.h>
#include "creds.h"
#include <string>
#include <ArduinoJson.h>
#include "Syren50.h"
using namespace std;
Syren50 motor;
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
// delay required for motor controller boot-up
delay(1000);
initWiFi();
motor.init();
}
float throttle = 0.0f;
int8_t direction = 0;
bool horn = false;
bool bell = false;
bool lights = false;
int8_t last_direction = 0;
float last_throttle = 0.0f;
@ -30,25 +40,41 @@ void inertia(float throttle, int8_t direction, float &inertial_throttle, int8_t
float motor_throttle;
int8_t motor_direction;
void parse_json(String json_string, float &throttle, int8_t &direction) {
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, json_string);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
// Parse inputs and return them
throttle = doc["throttle"];
direction = (int8_t) doc["direction"];
}
void get_control_inputs(float &throttle, int8_t &direction) {
if (Serial.available() > 0) {
if (Serial.peek() == 'c') {
Serial.read();
Serial.println("Init motor");
motor.init();
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
String serverName = "http://10.0.2.148:2093/control";
http.begin(serverName.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String payload = http.getString();
parse_json(payload, throttle, direction);
} else {
int recvd = Serial.parseInt();
throttle = (float) recvd / 100.0;
Serial.println(throttle);
direction = 1;
Serial.println("Error communicating with webserver. Got HTTP status code:");
Serial.println(httpResponseCode);
}
http.end();
}
}
void loop() {
get_control_inputs(throttle, direction);
inertia(throttle, direction, motor_throttle, motor_direction);
Serial.println(motor_throttle);
motor.move(motor_direction, (uint8_t) (motor_throttle * 127.0));
delay(1);
}