From 5646c3d33be23f0855283fd13aa88cfa05b12fcb Mon Sep 17 00:00:00 2001 From: Lukas Bachschwell Date: Sat, 11 May 2024 17:16:12 +0200 Subject: [PATCH] working display Signed-off-by: Lukas Bachschwell --- src/accel.h | 17 +- src/receiver.cpp | 321 +++++++++++------ src/remote.cpp | 897 ++++++++++++++++++++++++++++++----------------- 3 files changed, 798 insertions(+), 437 deletions(-) diff --git a/src/accel.h b/src/accel.h index f4b57e5..646feda 100644 --- a/src/accel.h +++ b/src/accel.h @@ -10,18 +10,21 @@ int16_t GyY = 0; int16_t GyZ = 0; int16_t cels = 0; -void initAccel() { +void initAccel() +{ + return; Wire.begin(); Wire.beginTransmission(0x68); // I2C address of the MPU-6050 - Wire.write(0x6B); // PWR_MGMT_1 register - Wire.write(0); // set to zero (wakes up the MPU-6050) + Wire.write(0x6B); // PWR_MGMT_1 register + Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); } - -void readAccel() { +void readAccel() +{ + return; Wire.beginTransmission(MPU_addr); - Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) + Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU_addr, 14); // request a total of 14 registers LB : removing stop, no support in tiny wire @@ -32,5 +35,5 @@ void readAccel() { GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) - cels = Tmp / 340.00 + 36.53; //equation for temperature in degrees C from datasheet + cels = Tmp / 340.00 + 36.53; // equation for temperature in degrees C from datasheet } diff --git a/src/receiver.cpp b/src/receiver.cpp index a28065f..f11e0f7 100644 --- a/src/receiver.cpp +++ b/src/receiver.cpp @@ -1,11 +1,10 @@ // ESPNOWSkate Receiver by Lukas Bachschwell this device SLAVE =D -#include #include "Arduino.h" -#include "SSD1306.h" #include #include -#include -#include +// #include +// #include +#include "valuehelpers.h" #include "mac_config.h" @@ -13,9 +12,8 @@ #define esc2pin 13 #define voltageEnable 12 #define voltagePin 36 -#define failsafeValue 127 #define ONE_WIRE_BUS 14 -#define fanRelais 16 +#define fanRelais 18 // Changed from originally 16 to help hover usart #define DELETEBEFOREPAIR 0 @@ -24,13 +22,26 @@ const float deviderR1 = 1275; // needs to be calibrated carefully using a multim const float deviderR2 = 22000; const float refVoltage = 3.3; +#define VARIANT_HOVER 1 +// #define ENABLE_DISPLAY 1 + +#ifdef VARIANT_HOVER +#define failsafeValue 0 +#include "hoverusart.h" +#else +#define failsafeValue 127 +#include Servo esc1; Servo esc2; -SSD1306 display(0x3c, 5, 4); +#endif +#ifdef ENABLE_DISPLAY +#include "SSD1306.h" +SSD1306 display(0x3c, 5, 4); +#endif OneWire oneWire(ONE_WIRE_BUS); -DallasTemperature sensors(&oneWire); // one instance for all sensrs +// DallasTemperature sensors(&oneWire); // one instance for all sensrs esp_now_peer_info_t remote; @@ -47,7 +58,7 @@ uint8_t sendSpeedDecimals = 0; #include "rpm.h" -//#define pairingMode +// #define pairingMode #define CONNECTION_TIMEOUT 300 #define CHANNEL 1 long lastPacket = 0; @@ -62,11 +73,13 @@ bool lightActive = false; int fanMode = FANS_AUTO; #include "lights.h" -void setBoardOptions(uint8_t options) { - if(options != oldOptions) { +void setBoardOptions(uint8_t options) +{ + if (options != oldOptions) + { oldOptions = options; shouldUpdateLights = true; - Serial.println("true2"); + // Serial.println("true2"); } lightMode = options & 3; @@ -76,93 +89,137 @@ void setBoardOptions(uint8_t options) { // ESPNOW Functions ############################ // config AP -void configDeviceAP(bool hidden) { +void configDeviceAP(bool hidden) +{ bool result = WiFi.softAP("ESK8", "ESK8_Password+vD8z2YAvoDBW?Zx", CHANNEL, hidden); - if (!result) { + if (!result) + { Serial.println("AP Config failed."); - } else { + } + else + { Serial.println("AP Config Success. Broadcasting with AP: " + String("ESK8")); } } -void writeServos(uint8_t firstServo, uint8_t secondServo) { +void writeServos(uint16_t firstServo, uint16_t secondServo) +{ +#ifdef VARIANT_HOVER + Send(firstServo, secondServo); +#else esc1.write(firstServo); esc2.write(secondServo); +#endif } // callback when data is recv from remote -void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) { +void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) +{ char macStr[18]; - snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", - mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); - Serial.print("Last Packet Recv from: "); Serial.println(macStr); - uint8_t recData[3]; + snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); + Serial.print("Last Packet Recv from: "); + Serial.println(macStr); + uint8_t recData[5]; memcpy(recData, data, data_len); - Serial.print("Last Packet Recv Data: "); Serial.println(recData[0]); Serial.print(" "); Serial.print(recData[1]); Serial.print(" len:"); Serial.println(data_len); + Serial.print("Last Packet Recv Data: "); + Serial.println(make16(recData[0], recData[1])); + Serial.print(" "); + Serial.print(make16(recData[2], recData[3])); + Serial.print(" len:"); + Serial.println(data_len); -// Answer with response + // Answer with response - const uint8_t respData[] = { sendVoltage, sendVoltageDecimals, sendTemperature, sendTemperatureDecimals, sendSpeed, sendSpeedDecimals }; + const uint8_t respData[] = {sendVoltage, sendVoltageDecimals, sendTemperature, sendTemperatureDecimals, sendSpeed, sendSpeedDecimals}; Serial.print("Sending RESPONSE.... "); esp_err_t result = esp_now_send(mac_addr, respData, sizeof(respData)); - if (result == ESP_OK) { + if (result == ESP_OK) + { Serial.println("Success"); - } else if (result == ESP_ERR_ESPNOW_NOT_INIT) { + } + else if (result == ESP_ERR_ESPNOW_NOT_INIT) + { // How did we get so far!! Serial.println("ESPNOW not Init."); - } else if (result == ESP_ERR_ESPNOW_ARG) { + } + else if (result == ESP_ERR_ESPNOW_ARG) + { Serial.println("Invalid Argument"); - } else if (result == ESP_ERR_ESPNOW_INTERNAL) { + } + else if (result == ESP_ERR_ESPNOW_INTERNAL) + { Serial.println("Internal Error"); - } else if (result == ESP_ERR_ESPNOW_NO_MEM) { + } + else if (result == ESP_ERR_ESPNOW_NO_MEM) + { Serial.println("ESP_ERR_ESPNOW_NO_MEM"); - } else if (result == ESP_ERR_ESPNOW_NOT_FOUND) { + } + else if (result == ESP_ERR_ESPNOW_NOT_FOUND) + { Serial.println("Peer not found."); - } else if (result == ESP_ERR_ESPNOW_IF) { + } + else if (result == ESP_ERR_ESPNOW_IF) + { Serial.println("ESP_ERR_ESPNOW_IF"); - } else { + } + else + { Serial.println("Not sure what happened"); } - - lastPacket = millis(); isConnected = true; - // Could check mac here for some security - writeServos(recData[0], recData[1]); - setBoardOptions(recData[2]); - Serial.print("recieved: "); - Serial.println(recData[2], BIN); + // TODO: Could check mac here for some minimal security + writeServos(make16(recData[0], recData[1]), make16(recData[2], recData[3])); + + Serial.print("recieved Options: "); + setBoardOptions(recData[4]); + Serial.println(recData[4], BIN); +#ifdef ENABLE_DISPLAY display.clear(); char buf[25]; - sprintf(buf, "1: %i | 2: %i", recData[0], recData[1]); + sprintf(buf, "1: %i | 2: %i", make16(recData[0], recData[1]), make16(recData[2], recData[3])); display.drawString(2, 0, buf); display.display(); +#endif } -void deletePeer() { +void deletePeer() +{ const esp_now_peer_info_t *peer = &remote; const uint8_t *peer_addr = remote.peer_addr; esp_err_t delStatus = esp_now_del_peer(peer_addr); Serial.print("Slave Delete Status: "); - if (delStatus == ESP_OK) { + if (delStatus == ESP_OK) + { // Delete success Serial.println("Success"); - } else if (delStatus == ESP_ERR_ESPNOW_NOT_INIT) { + } + else if (delStatus == ESP_ERR_ESPNOW_NOT_INIT) + { // How did we get so far!! Serial.println("ESPNOW Not Init"); - } else if (delStatus == ESP_ERR_ESPNOW_ARG) { + } + else if (delStatus == ESP_ERR_ESPNOW_ARG) + { Serial.println("Invalid Argument"); - } else if (delStatus == ESP_ERR_ESPNOW_NOT_FOUND) { + } + else if (delStatus == ESP_ERR_ESPNOW_NOT_FOUND) + { Serial.println("Peer not found."); - } else { + } + else + { Serial.println("Not sure what happened"); } } -bool manageRemote() { - if (remote.channel == CHANNEL) { - if (DELETEBEFOREPAIR) { +bool manageRemote() +{ + if (remote.channel == CHANNEL) + { + if (DELETEBEFOREPAIR) + { deletePeer(); } @@ -171,39 +228,57 @@ bool manageRemote() { const uint8_t *peer_addr = remote.peer_addr; // check if the peer exists bool exists = esp_now_is_peer_exist(peer_addr); - if ( exists) { + if (exists) + { // Slave already paired. Serial.println("Already Paired"); return true; - } else { + } + else + { // Slave not paired, attempt pair esp_err_t addStatus = esp_now_add_peer(peer); - if (addStatus == ESP_OK) { + if (addStatus == ESP_OK) + { // Pair success Serial.println("Pair success"); return true; - } else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT) { + } + else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT) + { // How did we get so far!! Serial.println("ESPNOW Not Init"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_ARG) { + } + else if (addStatus == ESP_ERR_ESPNOW_ARG) + { Serial.println("Invalid Argument"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_FULL) { + } + else if (addStatus == ESP_ERR_ESPNOW_FULL) + { Serial.println("Peer list full"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_NO_MEM) { + } + else if (addStatus == ESP_ERR_ESPNOW_NO_MEM) + { Serial.println("Out of memory"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_EXIST) { + } + else if (addStatus == ESP_ERR_ESPNOW_EXIST) + { Serial.println("Peer Exists"); return true; - } else { + } + else + { Serial.println("Not sure what happened"); return false; } } - } else { + } + else + { // No slave found to process Serial.println("No Slave found to process"); return false; @@ -212,16 +287,19 @@ bool manageRemote() { // end ESPNOW functions - -void checkTemperature() { - sensors.requestTemperatures(); // Send the command to get temperatures - temperature = sensors.getTempCByIndex(0); - //Serial.print("Temp: "); - //Serial.println(temperature); - switch(fanMode) { +void checkTemperature() +{ + // sensors.requestTemperatures(); // Send the command to get temperatures + // temperature = sensors.getTempCByIndex(0); + // Serial.print("Temp: "); + // Serial.println(temperature); + switch (fanMode) + { case FANS_AUTO: - if(temperature < 35) digitalWrite(fanRelais, LOW); - if(temperature > 40) digitalWrite(fanRelais, HIGH); + if (temperature < 35) + digitalWrite(fanRelais, LOW); + if (temperature > 40) + digitalWrite(fanRelais, HIGH); break; case FANS_ON: digitalWrite(fanRelais, HIGH); @@ -235,81 +313,91 @@ void checkTemperature() { sendTemperatureDecimals = (temperature - sendTemperature) * 100; } -void checkVoltage() { +void checkVoltage() +{ digitalWrite(voltageEnable, HIGH); - //Serial.print("Voltage: "); + // Serial.print("Voltage: "); int value = analogRead(voltagePin); - //Serial.println(value); - + // Serial.println(value); float batteryVoltage = 0.0; int total = 0; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { total += analogRead(voltagePin); } batteryVoltage = (refVoltage / 4095.0) * ((float)total / 10.0); // Now we have the actual Voltage, lets calculate the value befor the devider - batteryVoltage = batteryVoltage / ( deviderR1 / (deviderR1 + deviderR2)); + batteryVoltage = batteryVoltage / (deviderR1 / (deviderR1 + deviderR2)); sendVoltage = abs(floor(batteryVoltage)); sendVoltageDecimals = (batteryVoltage - sendVoltage) * 100; - //Serial.print("Voltage: "); - //Serial.println(batteryVoltage); - digitalWrite(voltageEnable, LOW); // change to low + // Serial.print("Voltage: "); + // Serial.println(batteryVoltage); + digitalWrite(voltageEnable, LOW); // change to low } -void setup() { - +void setup() +{ Serial.begin(115200); Serial.println("ESPNowSkate Receiver"); +#ifdef ENABLE_DISPLAY display.init(); display.flipScreenVertically(); display.setFont(ArialMT_Plain_16); +#endif pinMode(voltageEnable, OUTPUT); pinMode(fanRelais, OUTPUT); - initRPMPins(); - +#ifdef VARIANT_HOVER + initHoverSerial(); +#else // Init escs, min and max value similar as Traxxas TQI 1100, 1900 // chanel, minAngel, maxAngel, minPulseWidth, maxPulseWidth esc1.attach(esc1pin, 0, 0, 255, 1100, 1900); esc2.attach(esc2pin, 1, 0, 255, 1100, 1900); - sensors.begin(); + initRPMPins(); +#endif - setupLights(); - lightOff(); + // setupLights(); + // lightOff(); - xTaskCreatePinnedToCore( - measureRpm, - "rpm task", - 1000, - NULL, - 1, - &rpmTaskHandle, - 0); + // xTaskCreatePinnedToCore( + // measureRpm, + // "rpm task", + // 1000, + // NULL, + // 1, + // &rpmTaskHandle, + // 0); + // Set device in AP mode to begin with + Serial.println("INIT Wifi"); - //Set device in AP mode to begin with WiFi.mode(WIFI_AP); - // configure device AP mode - #ifdef pairingMode + Serial.println("INIT Pair"); +// configure device AP mode +#ifdef pairingMode configDeviceAP(false); - #else +#else configDeviceAP(true); - #endif +#endif - Serial.print("AP MAC: "); Serial.println(WiFi.softAPmacAddress()); + Serial.print("AP MAC: "); + Serial.println(WiFi.softAPmacAddress()); // Init ESPNow - if (esp_now_init() == ESP_OK) { + if (esp_now_init() == ESP_OK) + { Serial.println("ESPNow Init Success"); } - else { + else + { Serial.println("ESPNow Init Failed"); ESP.restart(); } @@ -318,31 +406,40 @@ void setup() { // get recv packer info. esp_now_register_recv_cb(OnDataRecv); - for (int i = 0; i < 6; ++i ) { - remote.peer_addr[i] = (uint8_t) mac_remote[i]; + for (int i = 0; i < 6; ++i) + { + remote.peer_addr[i] = (uint8_t)mac_remote[i]; } remote.channel = CHANNEL; // pick a channel - remote.encrypt = 0; // no encryption - remote.ifidx = ESP_IF_WIFI_AP; + remote.encrypt = 0; // no encryption + remote.ifidx = WIFI_IF_AP; manageRemote(); } - -void loop() { - if(millis() - lastPacket > CONNECTION_TIMEOUT ) { +void loop() +{ + if (millis() - lastPacket > CONNECTION_TIMEOUT) + { + Serial.println("Con timeout!!"); isConnected = false; - //int failsafeValue = map(analogRead(fallbackpin), 0, 4095, 0, 180); - // Taking 127 because it should be the center value anyway + // int failsafeValue = map(analogRead(fallbackpin), 0, 4095, 0, 180); + // Taking 127 because it should be the center value anyway writeServos(failsafeValue, failsafeValue); +#ifdef ENABLE_DISPLAY display.clear(); char buf[25]; sprintf(buf, "FAIL: %i", failsafeValue); display.drawString(2, 0, buf); display.display(); +#endif } - checkTemperature(); - checkVoltage(); - if(shouldUpdateLights) updateLights(); + // checkTemperature(); + // checkVoltage(); +#ifdef VARIANT_HOVER + Receive(); +#endif + // if (shouldUpdateLights) + // updateLights(); } diff --git a/src/remote.cpp b/src/remote.cpp index f18e87f..d1f6f7f 100644 --- a/src/remote.cpp +++ b/src/remote.cpp @@ -6,29 +6,48 @@ #include #include +#include "valuehelpers.h" #include "mac_config.h" #include "graphics.h" #include "accel.h" +#define VARIANT_HOVER 1 + TaskHandle_t clickTaskHandle; Preferences preferences; -#define B_VOLT 0 -#define B_VOLT_D 1 -#define B_TEMP 2 -#define B_TEMP_D 3 -#define B_SPEED 4 +#define B_VOLT 0 +#define B_VOLT_D 1 +#define B_TEMP 2 +#define B_TEMP_D 3 +#define B_SPEED 4 #define B_SPEED_D 5 uint8_t boardData[6] = {0, 0, 0, 0, 0, 0}; -#define M_NORMAL 0 // Limit is a sub of normal -#define M_SELECT 1 +#define M_NORMAL 0 // Limit is a sub of normal +#define M_SELECT 1 #define M_SETTINGS 2 -#define M_CRUISE 3 +#define M_CRUISE 3 #define M_STEERING 4 -//#define steeringInfluential +#ifdef VARIANT_HOVER + +#define THROTTLE_MIN -1000 +#define THROTTLE_CENTER 0 +#define THROTTLE_MAX 1000 +#define THROTTLE_LIMITED 600 + +#else + +#define THROTTLE_MIN 0 +#define THROTTLE_CENTER 127 +#define THROTTLE_MAX 255 +#define THROTTLE_LIMITED 180 + +#endif + +// #define steeringInfluential uint8_t currentMode = M_NORMAL; uint8_t selectedIndex = 2; @@ -37,16 +56,16 @@ bool lightActive = false; bool shouldUpdateSettings = false; // Needed to update limitmode on core 1 instead of 0 bool crusing = false; -uint8_t crusingSpeed = 127; +int16_t crusingSpeed = THROTTLE_CENTER; #define DEBUG #ifdef DEBUG - #define DEBUG_PRINTLN(x) Serial.println(x) - #define DEBUG_PRINT(x) Serial.print(x) +#define DEBUG_PRINTLN(x) Serial.println(x) +#define DEBUG_PRINT(x) Serial.print(x) #else - #define DEBUG_PRINTLN(x) - #define DEBUG_PRINT(x) +#define DEBUG_PRINTLN(x) +#define DEBUG_PRINT(x) #endif bool connected = false; @@ -57,7 +76,7 @@ long lastClick = 0; #define clickDiff 250 // Defining variables for OLED display -U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2 (U8G2_R2, /* clock=*/ 15, /* data=*/ 4, /* reset=*/ 16); +U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R2, /* reset=*/16, /* clock=*/15, /* data=*/4); char displayBuffer[20]; String displayString; short displayData = 0; @@ -65,12 +84,12 @@ unsigned long lastSignalBlink; bool signalBlink = false; unsigned long lastDataRotation; - // Defining variables for Hall Effect throttle. short hallMeasurement; -int throttle = 127; -uint8_t esc1 = 127; -uint8_t esc2 = 127; +int throttle = THROTTLE_CENTER; + +int16_t esc1 = THROTTLE_CENTER; +int16_t esc2 = THROTTLE_CENTER; byte hallCenterMargin = 5; @@ -86,11 +105,11 @@ esp_now_peer_info_t board; #define CHANNEL 1 #define PRINTSCANRESULTS 0 #define DELETEBEFOREPAIR 0 -#define HAL_MIN 1390 // defaults -#define HAL_MAX 2230 // defaults +#define HAL_MIN 1390 // defaults +#define HAL_MAX 2230 // defaults #define HAL_CENTER 1880 // defaults -//#define pairingMode +// #define pairingMode #define leverPin 36 #define triggerPin 17 #define batteryMeasurePin 39 @@ -99,48 +118,65 @@ bool triggerActive(); #include "settings.h" +uint8_t *buf; -void setCrusing(uint8_t speed) { - if(speed < 127) { // no backward cruse! +void setCrusing(int16_t speed) +{ + if (speed < THROTTLE_CENTER) + { // no backward cruse! crusing = false; - crusingSpeed = 127; - } else { + crusingSpeed = THROTTLE_CENTER; + } + else + { crusing = true; - if(speed > crusingSpeed) crusingSpeed = speed; + if (speed > crusingSpeed) + crusingSpeed = speed; } } // ESPNOW functions ############################## // Scan for boards in AP mode // config AP -void configDeviceAP(bool hidden) { +void configDeviceAP(bool hidden) +{ bool result = WiFi.softAP("ESK8", "ESK8_Password+vD8z2YAvoDBW?Zx", CHANNEL, hidden); - if (!result) { + if (!result) + { Serial.println("AP Config failed."); - } else { + } + else + { Serial.println("AP Config Success. Broadcasting with AP: " + String("ESK8")); } } - #ifdef pairingMode -void ScanForBoard() { +void ScanForBoard() +{ int8_t scanResults = WiFi.scanNetworks(); // reset on each scan bool boardFound = 0; memset(&board, 0, sizeof(board)); DEBUG_PRINTLN(""); - if (scanResults == 0) { + if (scanResults == 0) + { DEBUG_PRINTLN("No WiFi devices in AP Mode found"); - } else { - DEBUG_PRINT("Found "); DEBUG_PRINT(scanResults); DEBUG_PRINTLN(" devices "); - for (int i = 0; i < scanResults; ++i) { + } + else + { + DEBUG_PRINT("Found "); + DEBUG_PRINT(scanResults); + DEBUG_PRINTLN(" devices "); + for (int i = 0; i < scanResults; ++i) + { // Print SSID and RSSI for each device found String SSID = WiFi.SSID(i); int32_t RSSI = WiFi.RSSI(i); String BSSIDstr = WiFi.BSSIDstr(i); - if (PRINTSCANRESULTS) { + if (PRINTSCANRESULTS) + { DEBUG_PRINT(i + 1); DEBUG_PRINT(": "); DEBUG_PRINT(SSID); @@ -152,21 +188,33 @@ void ScanForBoard() { delay(10); // Check if the current device starts with `board` - if (SSID.indexOf("ESK8") == 0) { + if (SSID.indexOf("ESK8") == 0) + { // SSID of interest DEBUG_PRINTLN("Found a board."); - DEBUG_PRINT(i + 1); DEBUG_PRINT(": "); DEBUG_PRINT(SSID); DEBUG_PRINT(" ["); DEBUG_PRINT(BSSIDstr); DEBUG_PRINT("]"); DEBUG_PRINT(" ("); DEBUG_PRINT(RSSI); DEBUG_PRINT(")"); DEBUG_PRINTLN(""); + DEBUG_PRINT(i + 1); + DEBUG_PRINT(": "); + DEBUG_PRINT(SSID); + DEBUG_PRINT(" ["); + DEBUG_PRINT(BSSIDstr); + DEBUG_PRINT("]"); + DEBUG_PRINT(" ("); + DEBUG_PRINT(RSSI); + DEBUG_PRINT(")"); + DEBUG_PRINTLN(""); // Get BSSID => Mac Address of the board int mac[6]; - if ( 6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x%c", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5] ) ) { - for (int ii = 0; ii < 6; ++ii ) { - board.peer_addr[ii] = (uint8_t) mac[ii]; + if (6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x%c", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5])) + { + for (int ii = 0; ii < 6; ++ii) + { + board.peer_addr[ii] = (uint8_t)mac[ii]; } } board.channel = CHANNEL; // pick a channel - board.encrypt = 0; // no encryption - board.ifidx = ESP_IF_WIFI_STA; + board.encrypt = 0; // no encryption + board.ifidx = WIFI_IF_STA; boardFound = 1; // we are planning to have only one board in this example; @@ -176,9 +224,12 @@ void ScanForBoard() { } } - if (boardFound) { + if (boardFound) + { DEBUG_PRINTLN("board Found, processing.."); - } else { + } + else + { DEBUG_PRINTLN("board Not Found, trying again."); } @@ -187,32 +238,45 @@ void ScanForBoard() { } #endif -void deletePeer() { +void deletePeer() +{ const esp_now_peer_info_t *peer = &board; const uint8_t *peer_addr = board.peer_addr; esp_err_t delStatus = esp_now_del_peer(peer_addr); DEBUG_PRINT("board Delete Status: "); - if (delStatus == ESP_OK) { + if (delStatus == ESP_OK) + { // Delete success DEBUG_PRINTLN("Success"); - } else if (delStatus == ESP_ERR_ESPNOW_NOT_INIT) { + } + else if (delStatus == ESP_ERR_ESPNOW_NOT_INIT) + { // How did we get so far!! DEBUG_PRINTLN("ESPNOW Not Init"); - } else if (delStatus == ESP_ERR_ESPNOW_ARG) { + } + else if (delStatus == ESP_ERR_ESPNOW_ARG) + { DEBUG_PRINTLN("Invalid Argument"); - } else if (delStatus == ESP_ERR_ESPNOW_NOT_FOUND) { + } + else if (delStatus == ESP_ERR_ESPNOW_NOT_FOUND) + { DEBUG_PRINTLN("Peer not found."); - } else { + } + else + { DEBUG_PRINTLN("Not sure what happened"); } } // Check if the board is already paired with the master. // If not, pair the board with master -bool manageBoard() { - if (board.channel == CHANNEL) { - if (DELETEBEFOREPAIR) { +bool manageBoard() +{ + if (board.channel == CHANNEL) + { + if (DELETEBEFOREPAIR) + { deletePeer(); } @@ -221,39 +285,57 @@ bool manageBoard() { const uint8_t *peer_addr = board.peer_addr; // check if the peer exists bool exists = esp_now_is_peer_exist(peer_addr); - if ( exists) { + if (exists) + { // board already paired. DEBUG_PRINTLN("Already Paired"); return true; - } else { + } + else + { // board not paired, attempt pair esp_err_t addStatus = esp_now_add_peer(peer); - if (addStatus == ESP_OK) { + if (addStatus == ESP_OK) + { // Pair success DEBUG_PRINTLN("Pair success"); return true; - } else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT) { + } + else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT) + { // How did we get so far!! DEBUG_PRINTLN("ESPNOW Not Init"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_ARG) { + } + else if (addStatus == ESP_ERR_ESPNOW_ARG) + { DEBUG_PRINTLN("Invalid Argument"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_FULL) { + } + else if (addStatus == ESP_ERR_ESPNOW_FULL) + { DEBUG_PRINTLN("Peer list full"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_NO_MEM) { + } + else if (addStatus == ESP_ERR_ESPNOW_NO_MEM) + { DEBUG_PRINTLN("Out of memory"); return false; - } else if (addStatus == ESP_ERR_ESPNOW_EXIST) { + } + else if (addStatus == ESP_ERR_ESPNOW_EXIST) + { DEBUG_PRINTLN("Peer Exists"); return true; - } else { + } + else + { DEBUG_PRINTLN("Not sure what happened"); return false; } } - } else { + } + else + { // No board found to process DEBUG_PRINTLN("No board found to process"); return false; @@ -261,88 +343,119 @@ bool manageBoard() { } // send data -void sendData() { - const uint8_t data[] = { esc1, esc2, boardOptions }; +void sendData() +{ + const uint8_t data[] = {split16(esc1, 0), split16(esc1, 1), split16(esc2, 0), split16(esc2, 1), boardOptions}; const uint8_t *peer_addr = board.peer_addr; - DEBUG_PRINT("Sending: "); DEBUG_PRINTLN(esc1); + DEBUG_PRINT("Sending: "); + DEBUG_PRINTLN(esc1); esp_err_t result = esp_now_send(peer_addr, data, sizeof(data)); DEBUG_PRINT("Send Status: "); - if(result != ESP_OK) setCrusing(0); - if (result == ESP_OK) { + if (result != ESP_OK) + setCrusing(0); + if (result == ESP_OK) + { DEBUG_PRINTLN("Success"); - } else if (result == ESP_ERR_ESPNOW_NOT_INIT) { + } + else if (result == ESP_ERR_ESPNOW_NOT_INIT) + { // How did we get so far!! DEBUG_PRINTLN("ESPNOW not Init."); - } else if (result == ESP_ERR_ESPNOW_ARG) { + } + else if (result == ESP_ERR_ESPNOW_ARG) + { DEBUG_PRINTLN("Invalid Argument"); - } else if (result == ESP_ERR_ESPNOW_INTERNAL) { + } + else if (result == ESP_ERR_ESPNOW_INTERNAL) + { DEBUG_PRINTLN("Internal Error"); - } else if (result == ESP_ERR_ESPNOW_NO_MEM) { + } + else if (result == ESP_ERR_ESPNOW_NO_MEM) + { DEBUG_PRINTLN("ESP_ERR_ESPNOW_NO_MEM"); - } else if (result == ESP_ERR_ESPNOW_NOT_FOUND) { + } + else if (result == ESP_ERR_ESPNOW_NOT_FOUND) + { DEBUG_PRINTLN("Peer not found."); - } else if (result == ESP_ERR_ESPNOW_IF) { + } + else if (result == ESP_ERR_ESPNOW_IF) + { DEBUG_PRINTLN("Interface error."); - } else { + } + else + { DEBUG_PRINT("Not sure what happened "); DEBUG_PRINTLN(result); } } // callback when data is sent from Master to board -void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { +void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) +{ char macStr[18]; - snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", - mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); - DEBUG_PRINT("Last Packet Sent to: "); DEBUG_PRINTLN(macStr); + snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); + DEBUG_PRINT("Last Packet Sent to: "); + DEBUG_PRINTLN(macStr); DEBUG_PRINT("Last Packet Send Status: "); - if(status == ESP_NOW_SEND_SUCCESS) { + if (status == ESP_NOW_SEND_SUCCESS) + { connected = true; DEBUG_PRINTLN("Delivery Success"); - } else { - connected = false; - DEBUG_PRINTLN("Delivery Fail"); - setCrusing(0); + return; } + + connected = false; + DEBUG_PRINTLN("Delivery Fail"); + setCrusing(0); } // callback when data is recv from board -void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) { +void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) +{ char macStr[18]; - snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", - mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); - DEBUG_PRINT("Last Response Recv from: "); DEBUG_PRINTLN(macStr); + snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); + DEBUG_PRINT("Last Response Recv from: "); + DEBUG_PRINTLN(macStr); memcpy(boardData, data, data_len); DEBUG_PRINT("Recieved data! len: "); DEBUG_PRINTLN(data_len); } -//############ End ESP Now +// ############ End ESP Now -//############ Hardware Helpers +// ############ Hardware Helpers -int c_map(int value, int inMin, int inMax, int outMin, int outMax) { +int c_map(int value, int inMin, int inMax, int outMin, int outMax) +{ return constrain(map(value, inMin, inMax, outMin, outMax), outMin, outMax); } // Return true if trigger is activated, false otherwice -bool triggerActive() { - if (digitalRead(triggerPin) == LOW) { +bool triggerActive() +{ + if (digitalRead(triggerPin) == LOW) + { vTaskDelay(pdMS_TO_TICKS(0.1)); - if (digitalRead(triggerPin) == LOW) return true; - } else { + if (digitalRead(triggerPin) == LOW) + return true; + } + else + { vTaskDelay(pdMS_TO_TICKS(0.1)); - if (digitalRead(triggerPin) == HIGH) return false; + if (digitalRead(triggerPin) == HIGH) + return false; } return false; // biased to false } -void calculateThrottlePosition() { +void calculateThrottlePosition() +{ // Hall sensor reading can be noisy, lets make an average reading. int total = 0; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { total += analogRead(leverPin); } @@ -350,110 +463,144 @@ void calculateThrottlePosition() { DEBUG_PRINT("HAL: "); DEBUG_PRINTLN(hallMeasurement); - int maxSpeed = 255; - if(settings[limitMode] == 1) maxSpeed = 180; + int maxSpeed = THROTTLE_MAX; + if (settings[limitMode] == 1) + { + maxSpeed = THROTTLE_LIMITED; + } - if (hallMeasurement >= settings[centerHallValue]) { - throttle = c_map(hallMeasurement, settings[centerHallValue], settings[maxHallValue], 127, maxSpeed); - } else { - throttle = c_map(hallMeasurement, settings[minHallValue], settings[centerHallValue], 0, 127); + if (hallMeasurement >= settings[centerHallValue]) + { + throttle = c_map(hallMeasurement, settings[centerHallValue], settings[maxHallValue], THROTTLE_CENTER, maxSpeed); + } + else + { + throttle = c_map(hallMeasurement, settings[minHallValue], settings[centerHallValue], THROTTLE_MIN, THROTTLE_CENTER); } // removeing center noise - if (abs(throttle - 127) < hallCenterMargin) { - throttle = 127; + if (abs(throttle - THROTTLE_CENTER) < hallCenterMargin) + { + throttle = THROTTLE_CENTER; } } // Function to calculate and return the remotes battery voltage. -float batteryVoltage() { +float batteryVoltage() +{ float batteryVoltage = 0.0; int total = 0; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { total += analogRead(batteryMeasurePin); } batteryVoltage = (refVoltage / 4095.0) * ((float)total / 10.0); // Now we have the actual Voltage, lets calculate the value befor the devider - batteryVoltage = batteryVoltage / ( deviderR1 / (deviderR1 + deviderR2)); + batteryVoltage = batteryVoltage / (deviderR1 / (deviderR1 + deviderR2)); DEBUG_PRINT("Batt: "); DEBUG_PRINTLN(batteryVoltage); return batteryVoltage; } // Function used to indicate the remotes battery level. -int batteryLevel() { +int batteryLevel() +{ float voltage = batteryVoltage(); - if (voltage <= minVoltage) { + if (voltage <= minVoltage) + { return 0; - } else if (voltage >= maxVoltage) { + } + else if (voltage >= maxVoltage) + { return 100; - } else { + } + else + { return (voltage - minVoltage) * 100 / (maxVoltage - minVoltage); } } // Take a number of measurements of the WiFi strength and return the average result. -int getStrength(int points){ +int getStrength(int points) +{ long rssi = 0; - long averageRSSI=0; - if (points == 1) return WiFi.RSSI(); + long averageRSSI = 0; + if (points == 1) + return WiFi.RSSI(); - for (int i=0; i < points; i++) { + for (int i = 0; i < points; i++) + { rssi += WiFi.RSSI(); delay(20); } - averageRSSI=rssi/points; + averageRSSI = rssi / points; DEBUG_PRINT("RSSI: "); DEBUG_PRINTLN(averageRSSI); return averageRSSI; } -void checkClicks(void * parameter) { - for (;;) { - //DEBUG_PRINT("Trig: "); DEBUG_PRINT(triggerActive()); DEBUG_PRINT(" LAST: "); DEBUG_PRINTLN(lastTriggerState); - if(millis()-lastClick > clickDiff && clickCounter!=0) { +void checkClicks(void *parameter) +{ + for (;;) + { + // DEBUG_PRINT("Trig: "); DEBUG_PRINT(triggerActive()); DEBUG_PRINT(" LAST: "); DEBUG_PRINTLN(lastTriggerState); + if (millis() - lastClick > clickDiff && clickCounter != 0) + { DEBUG_PRINTLN("reset"); - //timeout, check amount - if(clickCounter == 2) { + // timeout, check amount + if (clickCounter == 2) + { // cycle page if active DEBUG_PRINTLN("Double, rotate page"); - if(settings[pageDisplay] != 0) { + if (settings[pageDisplay] != 0) + { displayData++; - if (displayData > 2) { + if (displayData > 2) + { displayData = 0; } // write and save settings[pageDisplay] = displayData + 1; shouldUpdateSettings = true; } - } else if(clickCounter == 3) { + } + else if (clickCounter == 3) + { DEBUG_PRINTLN("YEAH TRIPPLE"); - if(currentMode == M_NORMAL) { + if (currentMode == M_NORMAL) + { currentMode = M_SELECT; selectedIndex = 2; - } else { + } + else + { currentMode = M_NORMAL; } } clickCounter = 0; } - if(!triggerActive() && lastTriggerState) { + if (!triggerActive() && lastTriggerState) + { DEBUG_PRINTLN("CLICK ##################### "); - int timeSinceLastClick = millis()-lastClick; + int timeSinceLastClick = millis() - lastClick; lastClick = millis(); - if(currentMode == M_SELECT) { - switch(selectedIndex) { + if (currentMode == M_SELECT) + { + switch (selectedIndex) + { case 0: currentMode = M_SETTINGS; break; case 1: - if(settings[limitMode] == 0) settings[limitMode] = 1; - else settings[limitMode] = 0; + if (settings[limitMode] == 0) + settings[limitMode] = 1; + else + settings[limitMode] = 0; shouldUpdateSettings = true; currentMode = M_NORMAL; break; @@ -471,46 +618,57 @@ void checkClicks(void * parameter) { } } - if(timeSinceLastClick < clickDiff) { + if (timeSinceLastClick < clickDiff) + { clickCounter++; - } else { + } + else + { clickCounter = 1; } lastClick = millis(); lastTriggerState = false; - } else if(triggerActive()) { + } + else if (triggerActive()) + { lastTriggerState = true; } vTaskDelay(pdMS_TO_TICKS(20)); } } -//############ End Hardware Helpers +// ############ End Hardware Helpers -//############ Drawing Functions +// ############ Drawing Functions -void drawBatteryLevel() { +void drawBatteryLevel() +{ int level = batteryLevel(); // Position on OLED - int x = 108; int y = 4; + int x = 108; + int y = 4; u8g2.drawFrame(x + 2, y, 18, 9); u8g2.drawBox(x, y + 2, 2, 5); - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) + { int p = round((100 / 5) * i); - if (p <= level) { - u8g2.drawBox(x + 4 + (3 * (4-i)), y + 2, 2, 5); + if (p <= level) + { + u8g2.drawBox(x + 4 + (3 * (4 - i)), y + 2, 2, 5); } } } -void drawThrottle() { +void drawThrottle() +{ int x = 0; int y = 18; uint8_t displayThrottle = throttle; - if(crusing) displayThrottle = crusingSpeed; + if (crusing) + displayThrottle = crusingSpeed; // Draw throttle u8g2.drawHLine(x, y, 52); u8g2.drawVLine(x, y, 10); @@ -518,56 +676,74 @@ void drawThrottle() { u8g2.drawHLine(x, y + 10, 5); u8g2.drawHLine(x + 52 - 4, y + 10, 5); - if (displayThrottle >= 127) { - int width = map(displayThrottle, 127, 255, 0, 49); + if (displayThrottle >= THROTTLE_CENTER) + { + int width = map(displayThrottle, THROTTLE_CENTER, THROTTLE_MAX, 0, 49); - for (int i = 0; i < width; i++) { + for (int i = 0; i < width; i++) + { u8g2.drawVLine(x + i + 2, y + 2, 7); } - } else { - int width = map(displayThrottle, 0, 126, 49, 0); - for (int i = 0; i < width; i++) { + } + else + { + int width = map(displayThrottle, THROTTLE_MIN, THROTTLE_CENTER - 1, 49, 0); + for (int i = 0; i < width; i++) + { u8g2.drawVLine(x + 50 - i, y + 2, 7); } } } -void drawSignal() { +void drawSignal() +{ // Position on OLED - int x = 114; int y = 17; - if (connected == true) { - if (triggerActive()) { + int x = 114; + int y = 17; + if (connected == true) + { + if (triggerActive()) + { u8g2.drawXBM(x, y, 12, 12, signal_transmitting_bits); - } else { + } + else + { u8g2.drawXBM(x, y, 12, 12, signal_connected_bits); } - } else { - if (millis() - lastSignalBlink > 500) { + } + else + { + if (millis() - lastSignalBlink > 500) + { signalBlink = !signalBlink; lastSignalBlink = millis(); } - if (signalBlink == true) { + if (signalBlink == true) + { u8g2.drawXBM(x, y, 12, 12, signal_connected_bits); - } else { + } + else + { u8g2.drawXBM(x, y, 12, 12, signal_noconnection_bits); } } } -void drawTitleScreen(String title) { - u8g2.firstPage(); - do { - title.toCharArray(displayBuffer, 20); - u8g2.setFont(u8g2_font_helvR10_tr ); - u8g2.drawStr(12, 20, displayBuffer); - } while ( u8g2.nextPage() ); +void drawTitleScreen(String title) +{ + + u8g2.clearBuffer(); + title.toCharArray(displayBuffer, 20); + u8g2.setFont(u8g2_font_helvR10_tr); + u8g2.drawStr(12, 20, displayBuffer); + + u8g2.sendBuffer(); delay(1500); } - - -void drawPage() { +void drawPage() +{ int decimals; String suffix; String prefix; @@ -578,21 +754,27 @@ void drawPage() { int y = 16; // Rotate the realtime data each 4s. - if(settings[pageDisplay] == 0) { - if ((millis() - lastDataRotation) >= 4000) { + if (settings[pageDisplay] == 0) + { + if ((millis() - lastDataRotation) >= 4000) + { lastDataRotation = millis(); displayData++; - if (displayData > 2) { + if (displayData > 2) + { displayData = 0; } } - } else { + } + else + { displayData = settings[pageDisplay] - 1; } - switch (displayData) { + switch (displayData) + { case 0: first = boardData[B_TEMP]; last = boardData[B_TEMP_D]; @@ -623,27 +805,41 @@ void drawPage() { u8g2.drawStr(x, y - 1, displayBuffer); // Add leading zero - if (first <= 9) { - if(connected) displayString = "0" + (String)first; - else displayString = "--"; - } else { - if(connected) displayString = (String)first; - else displayString = "--"; + if (first <= 9) + { + if (connected) + displayString = "0" + (String)first; + else + displayString = "--"; + } + else + { + if (connected) + displayString = (String)first; + else + displayString = "--"; } // Display numbers displayString.toCharArray(displayBuffer, 4); - u8g2.setFont(u8g2_font_logisoso22_tn ); + u8g2.setFont(u8g2_font_logisoso22_tn); u8g2.drawStr(x + 55, y + 13, displayBuffer); // Display decimals // Add leading zero - if (last <= 9) { - if(connected) displayString = ".0" + (String)last; - else displayString = ".--"; - } else { - if(connected) displayString = "." + (String)last; - else displayString = ".--"; + if (last <= 9) + { + if (connected) + displayString = ".0" + (String)last; + else + displayString = ".--"; + } + else + { + if (connected) + displayString = "." + (String)last; + else + displayString = ".--"; } // Display decimals @@ -656,36 +852,42 @@ void drawPage() { displayString.toCharArray(displayBuffer, 10); u8g2.setFont(u8g2_font_profont12_tr); u8g2.drawStr(x + 86 + 2, y + 13, displayBuffer); - } -void controlSelect() { - if (hallMeasurement >= (settings[maxHallValue] - 250) && settingsLoopFlag == false) { //settings[maxHallValue] +void controlSelect() +{ + if (hallMeasurement >= (settings[maxHallValue] - 250) && settingsLoopFlag == false) + { // settings[maxHallValue] // Up - if (selectedIndex != 0) { + if (selectedIndex != 0) + { selectedIndex--; settingsLoopFlag = true; } - } else if (hallMeasurement <= (settings[minHallValue] + 250) && settingsLoopFlag == false) { + } + else if (hallMeasurement <= (settings[minHallValue] + 250) && settingsLoopFlag == false) + { // Down - if (selectedIndex < 4) { + if (selectedIndex < 4) + { selectedIndex++; settingsLoopFlag = true; } - } else if (inRange(hallMeasurement, settings[centerHallValue] - 50, settings[centerHallValue] + 50)) { // settings[centerHallValue] + } + else if (inRange(hallMeasurement, settings[centerHallValue] - 50, settings[centerHallValue] + 50)) + { // settings[centerHallValue] settingsLoopFlag = false; } } -String selectionTitles[5] = { - "Settings","Limit","Light","Steering","Cruise" -}; +String selectionTitles[5] = { + "Settings", "Limit", "Light", "Steering", "Cruise"}; -uint16_t selectionGlyphs[5] = { - 0x0081, 0x008d, 0x0103, 0x00f6, 0x0088 -}; +uint16_t selectionGlyphs[5] = { + 0x0081, 0x008d, 0x0103, 0x00f6, 0x0088}; -void drawSelectionMenu() { +void drawSelectionMenu() +{ const uint8_t y = 35; const uint8_t xStart = 10; const uint8_t xSpace = 20; @@ -693,22 +895,24 @@ void drawSelectionMenu() { u8g2.setFontMode(0); u8g2.setDrawColor(1); - for(int i = 0; i < 5; i++) { - if(selectedIndex == i) { + for (int i = 0; i < 5; i++) + { + if (selectedIndex == i) + { String title = selectionTitles[i]; title.toCharArray(displayBuffer, 20); - u8g2.setFont(u8g2_font_helvR10_tr ); + u8g2.setFont(u8g2_font_helvR10_tr); u8g2.drawStr(30, 12, displayBuffer); u8g2.setFontMode(0); - //u8g2.drawBox(xStart-2 + xSpace * i, y-12, 15, 15); - u8g2.drawBox(xStart + xSpace * i, y-12, 15, 15); + // u8g2.drawBox(xStart-2 + xSpace * i, y-12, 15, 15); + u8g2.drawBox(xStart + xSpace * i, y - 12, 15, 15); u8g2.setDrawColor(0); } - //selectionItems[i].toCharArray(displayBuffer, 10); - //u8g2.setFont(u8g2_font_profont12_tr); - //u8g2.drawStr(xStart + xSpace * i, y, displayBuffer); + // selectionItems[i].toCharArray(displayBuffer, 10); + // u8g2.setFont(u8g2_font_profont12_tr); + // u8g2.drawStr(xStart + xSpace * i, y, displayBuffer); u8g2.setFont(u8g2_font_open_iconic_all_2x_t); u8g2.drawGlyph(xStart + xSpace * i, y, selectionGlyphs[i]); @@ -718,8 +922,10 @@ void drawSelectionMenu() { } } -void drawLight() { - if(lightActive) { +void drawLight() +{ + if (lightActive) + { displayString = "Light"; displayString.toCharArray(displayBuffer, 12); u8g2.setFont(u8g2_font_profont10_tr); @@ -727,24 +933,33 @@ void drawLight() { } } -void drawMode() { - if(currentMode == M_STEERING) { +void drawMode() +{ + if (currentMode == M_STEERING) + { displayString = (String)esc1 + " |S| " + (String)esc2; displayString.toCharArray(displayBuffer, 12); u8g2.setFont(u8g2_font_profont12_tr); u8g2.drawStr(25, 50, displayBuffer); - } else if(currentMode == M_NORMAL && settings[limitMode] == 1) { + } + else if (currentMode == M_NORMAL && settings[limitMode] == 1) + { displayString = "LIM"; displayString.toCharArray(displayBuffer, 12); u8g2.setFont(u8g2_font_profont12_tr); u8g2.drawStr(105, 50, displayBuffer); - } else if(currentMode == M_CRUISE) { - if(crusing) { - displayString = "ACTIVE: " + (String) crusingSpeed; + } + else if (currentMode == M_CRUISE) + { + if (crusing) + { + displayString = "ACTIVE: " + (String)crusingSpeed; displayString.toCharArray(displayBuffer, 12); u8g2.setFont(u8g2_font_profont12_tr); u8g2.drawStr(0, 50, displayBuffer); - } else { + } + else + { displayString = "Inactive"; displayString.toCharArray(displayBuffer, 12); u8g2.setFont(u8g2_font_profont12_tr); @@ -758,47 +973,55 @@ void drawMode() { } } -void updateMainDisplay() { - - u8g2.firstPage(); - do { - if(currentMode == M_SELECT) { - drawSelectionMenu(); - } else if (currentMode == M_SETTINGS) { - drawSettingsMenu(); - drawSettingNumber(); - } else { - drawThrottle(); - drawPage(); - drawBatteryLevel(); - drawSignal(); - drawLight(); - drawMode(); - } - - } while ( u8g2.nextPage() ); +void updateMainDisplay() +{ + long start = millis(); + u8g2.clearBuffer(); + if (currentMode == M_SELECT) + { + drawSelectionMenu(); + } + else if (currentMode == M_SETTINGS) + { + drawSettingsMenu(); + drawSettingNumber(); + } + else + { + drawThrottle(); + drawPage(); + drawBatteryLevel(); + drawSignal(); + drawLight(); + drawMode(); + } + u8g2.sendBuffer(); + Serial.printf("Took %dms\n", millis() - start); } -void drawStartScreen() { - u8g2.firstPage(); - do { - u8g2.drawXBM( 4, 4, 24, 24, logo_bits); +void drawStartScreen() +{ + u8g2.clearBuffer(); // clear the internal memory - displayString = "Esk8 remote"; - displayString.toCharArray(displayBuffer, 12); - u8g2.setFont(u8g2_font_helvR10_tr ); - u8g2.drawStr(34, 22, displayBuffer); - } while ( u8g2.nextPage() ); + u8g2.drawXBM(4, 4, 24, 24, logo_bits); + + displayString = "Esk8 remote"; + displayString.toCharArray(displayBuffer, 12); + u8g2.setFont(u8g2_font_helvR10_tr); + u8g2.drawStr(34, 22, displayBuffer); + + u8g2.sendBuffer(); // transfer internal memory to the display delay(800); } -//############ End Drawing Functions +// ############ End Drawing Functions -void setup() { +void setup() +{ Serial.begin(115200); - //Set device in STA mode to begin with - //WiFi.mode(WIFI_STA); - //Set device in AP mode to begin with + // Set device in STA mode to begin with + // WiFi.mode(WIFI_STA); + // Set device in AP mode to begin with WiFi.mode(WIFI_AP_STA); // configure device AP mode configDeviceAP(true); @@ -816,32 +1039,45 @@ void setup() { pinMode(triggerPin, INPUT_PULLUP); xTaskCreatePinnedToCore( - checkClicks, - "click task", - 1000, - NULL, - 1, - &clickTaskHandle, - 0); + checkClicks, + "click task", + 1000, + NULL, + 1, + &clickTaskHandle, + 0); initAccel(); DEBUG_PRINTLN("ESPNowSkate Sender"); + u8g2.setBusClock(400000); u8g2.begin(); + u8g2.setBusClock(400000); + + // buf = (uint8_t *)malloc(u8g2.getBufferSize()); + // u8g2.setBufferPtr(buf); + // u8g2.initDisplay(); + // u8g2.clearDisplay(); + // u8g2.setPowerSave(0); + drawStartScreen(); - if (triggerActive()) { + if (triggerActive()) + { currentMode = M_SETTINGS; drawTitleScreen("Remote Settings"); } // This is the mac address of the Master in Station Mode - DEBUG_PRINT("STA MAC: "); DEBUG_PRINTLN(WiFi.macAddress()); - if (esp_now_init() == ESP_OK) { + DEBUG_PRINT("STA MAC: "); + DEBUG_PRINTLN(WiFi.macAddress()); + if (esp_now_init() == ESP_OK) + { DEBUG_PRINTLN("ESPNow Init Success"); } - else { + else + { DEBUG_PRINTLN("ESPNow Init Failed"); ESP.restart(); } @@ -849,32 +1085,32 @@ void setup() { // Once ESPNow is successfully Init, we will register for Send CB to // get the status of Trasnmitted packet esp_now_register_send_cb(OnDataSent); - //ScanForBoard(); + // ScanForBoard(); // Once ESPNow is successfully Init, we will register for recv CB to // get recv packer info. esp_now_register_recv_cb(OnDataRecv); - // Retrieve board from config: - for (int i = 0; i < 6; ++i ) { - board.peer_addr[i] = (uint8_t) mac_receiver[i]; + for (int i = 0; i < 6; ++i) + { + board.peer_addr[i] = (uint8_t)mac_receiver[i]; } board.channel = CHANNEL; // pick a channel - board.encrypt = 0; // no encryption - //board.ifidx = ESP_IF_WIFI_STA; - + board.encrypt = 0; // no encryption + // board.ifidx = ESP_IF_WIFI_STA; } -void loop() { +void loop() +{ updateMainDisplay(); - //if(currentMode == M_STEERING) readAccel(); + // if(currentMode == M_STEERING) readAccel(); readAccel(); DEBUG_PRINT("Accel Value Left Right (Y): "); DEBUG_PRINT(map(AcY, -15000, 15000, -100, 100)); - //Serial.print("Help(Y): "); - //Serial.println(map(GyY, -15000, 15000, -100, 100)); + // Serial.print("Help(Y): "); + // Serial.println(map(GyY, -15000, 15000, -100, 100)); DEBUG_PRINT(" (X): "); DEBUG_PRINT(map(AcX, -15000, 15000, -100, 100)); @@ -885,88 +1121,113 @@ void loop() { // left rigt : Z forward Back : Y calculateThrottlePosition(); - if (currentMode == M_SELECT) { + if (currentMode == M_SELECT) + { controlSelect(); - esc1 = 127; - esc2 = 127; - } else if (currentMode == M_SETTINGS) { + esc1 = THROTTLE_CENTER; + esc2 = THROTTLE_CENTER; + } + else if (currentMode == M_SETTINGS) + { // Use throttle and trigger to change settings controlSettingsMenu(); - } else { + } + else + { // Use throttle and trigger to drive motors - if (triggerActive()) { - if(currentMode == M_STEERING) { + if (triggerActive()) + { + if (currentMode == M_STEERING) + { DEBUG_PRINT("Value: "); int map = c_map(AcZ, -15000, 15000, -60, 60); DEBUG_PRINTLN(map); #ifdef steeringInfluential - esc1 = (uint8_t) constrain(throttle - map, 0, 200); - esc2 = (uint8_t) constrain(throttle + map, 0, 200); + esc1 = (uint8_t)constrain(throttle - map, THROTTLE_MIN, THROTTLE_MAX); + esc2 = (uint8_t)constrain(throttle + map, THROTTLE_MIN, THROTTLE_MAX); #else - esc1 = (uint8_t) constrain(127 - map, 0, 200); - esc2 = (uint8_t) constrain(127 + map, 0, 200); - if(-10 < map && map < 10) { + esc1 = (uint8_t)constrain(THROTTLE_CENTER - map, THROTTLE_MIN, THROTTLE_MAX); + esc2 = (uint8_t)constrain(THROTTLE_CENTER + map, THROTTLE_MIN, THROTTLE_MAX); + if (-10 < map && map < 10) + { esc1 = throttle; esc2 = throttle; } // ignore reverse - if(throttle < 127) { + if (throttle < THROTTLE_CENTER) + { esc1 = throttle; esc2 = throttle; } #endif - if(throttle == 127) { - esc1 = 127; - esc2 = 127; + if (throttle == THROTTLE_CENTER) + { + esc1 = THROTTLE_CENTER; + esc2 = THROTTLE_CENTER; } - DEBUG_PRINT("SteeringMode: ESC1: "); DEBUG_PRINT(esc1); DEBUG_PRINT(" ESC2: "); DEBUG_PRINTLN(esc2); - } else if(currentMode == M_CRUISE) { + DEBUG_PRINT("SteeringMode: ESC1: "); + DEBUG_PRINT(esc1); + DEBUG_PRINT(" ESC2: "); + DEBUG_PRINTLN(esc2); + } + else if (currentMode == M_CRUISE) + { setCrusing(throttle); - esc1 = (uint8_t) throttle; - esc2 = (uint8_t) throttle; + esc1 = throttle; + esc2 = throttle; - if(crusing) { - esc1 = (uint8_t) crusingSpeed; - esc2 = (uint8_t) crusingSpeed; + if (crusing) + { + esc1 = crusingSpeed; + esc2 = crusingSpeed; } - - } else { - esc1 = (uint8_t) throttle; - esc2 = (uint8_t) throttle; } - - } else { - // 127 is the middle position - no throttle and no brake/reverse - esc1 = 127; - esc2 = 127; - if(crusing) setCrusing(0); + else + { + esc1 = throttle; + esc2 = throttle; + } + } + else + { + // THROTTLE_CENTER is the middle position - no throttle and no brake/reverse + esc1 = THROTTLE_CENTER; + esc2 = THROTTLE_CENTER; + if (crusing) + setCrusing(0); } } // If board is found, it would be populate in `board` variable // We will check if `board` is defined and then we proceed further - if (board.channel == CHANNEL) { // check if board channel is defined + if (board.channel == CHANNEL) + { // check if board channel is defined // `board` is defined // Add board as peer if it has not been added already bool isPaired = manageBoard(); - if (isPaired) { + if (isPaired) + { sendData(); - } else { + } + else + { // board pair failed DEBUG_PRINTLN("board not found / paired!"); } } - else { + else + { // No board found to process } - if(shouldUpdateSettings) { - updateSettings(); - shouldUpdateSettings = false; + if (shouldUpdateSettings) + { + // updateSettings(); + // shouldUpdateSettings = false; } }