Hey all,
I'm using an esp32-wroom-32 on a hexapod, and as part of that it's hosting a web server with a joystick which feeds the values to control the hexpod's movement. I soldered a perfboard to have a build in voltage divider running in the Vin, GND and 13 pins so that I can read the batteries voltage while also powered the esp32. The voltage divider works by itself, however when I host the server analogRead(13) just returns 0.00. I tried reading the voltage from a battery using a different pin and that also returned 0.
Aside from the analogRead, everything works fine. I have included the server part of the code because it seems to be causing the issue and also left some of the I2C code for the PCA9685 boards I am using in case that is also a problem.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
Adafruit_PWMServoDriver left = Adafruit_PWMServoDriver(0x41);
Adafruit_PWMServoDriver right = Adafruit_PWMServoDriver(0x40);
const char *ssid = "SSID";
const char *password = "PASSWORD";
/////////////////////////////////// Turn WiFi On And Off //////////////////////////////////
int connecttowifi = 1;
//////////////////////////////////////// Server ////////////////////////////////////////
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
//////////////////////////////////////// HTML and CSSCode ////////////////////////////////////////
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<meta charset="UTF-8" />
<meta name="author" content="bryan" />
<title>Joystick Testing</title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<style>
* {
box-sizing: content-box;
}
html {
font-size: 16px;
overflow: hidden;
touch-action: none;
}
body {
margin: 0;
width: 100vw;
height: 100vh;
/* width: -webkit-fill-available;
height: -webkit-fill-available; */
overflow: hidden;
}
.window {
height: 100%;
width: 100%;
}
.frame {
min-height: 29px;
max-height: 29px;
z-index: 2147483647;
}
.app {
flex-wrap: nowrap;
}
.app,
.main,
.frame,
.view,
.row,
.col {
flex: 1 0 auto;
}
.row,
.flx-row {
flex-direction: row;
}
.app,
.window,
.col,
.flx-col {
flex-direction: column;
}
.app,
.nav,
.main,
.frame,
.window,
.row,
.col,
.flx-1,
.flx-2,
.flx-3,
.flx-4,
.flx-5,
.flx-6,
.flx-7,
.flx-8,
.flx-9,
.flx-10,
.flx-11,
.flx-12,
.flx-row,
.flx-col,
.flx {
display: flex;
}
.flx-1 {
flex: 1 0 8.33%;
}
.flx-2 {
flex: 1 0 16.66%;
}
.flx-3 {
flex: 1 0 25%;
}
.flx-4 {
flex: 1 0 33.333%;
}
.flx-5 {
flex: 1 0 41.666%;
}
.flx-6 {
flex: 1 0 50%;
}
.flx-7 {
flex: 1 0 58.333%;
}
.flx-8 {
flex: 1 0 66.666%;
}
.flx-9 {
flex: 1 0 75%;
}
.flx-10 {
flex: 1 0 83.333%;
}
.flx-11 {
flex: 1 0 91.666%;
}
.flx-12 {
flex: 1 0 100%;
}
.view {
display: none;
}
.view:target {
display: flex !important;
}
.center,
.y-center-row,
.x-center-col {
align-items: center;
align-content: center;
}
.center,
.x-center-row,
.y-center-col {
justify-items: center;
justify-content: center;
}
.hide {
display: none !important;
}
.p-1 {
padding: 0.25rem;
}
.p-2 {
padding: 0.5rem;
}
body {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
color: rgb(128, 128, 128);
margin: 0;
overflow: hidden;
}
body,
.joystick,
.joystick-canvas {
flex-direction: column;
}
body,
.joystick,
.joystick-labels,
.joystick-canvas {
align-items: center;
}
body,
.nav,
.nav-options,
.joystick,
.joystick-labels,
.joystick-labels > span,
.joystick-canvas,
.header {
display: flex;
}
.header > h1 {
font-size: 2rem;
}
.nav-options {
flex: 1 0 auto;
flex-direction: row;
justify-content: space-evenly;
}
.canvas-joysticks {
touch-action: none;
}
.joystick {
flex: 1;
width: 100%;
}
.joystick-labels > span {
margin: 0 10px;
font-size: 1.75rem;
}
.x-label::before {
content: 'X:';
}
.y-label::before {
content: 'Y:';
}
.joystick-canvas {
width: 100%;
height: 100%;
}
.nav-button {
display: flex;
flex: 1;
max-width: 10rem;
margin: 0 0.5rem;
justify-content: center;
font-size: 1rem;
-webkit-border-radius: 0;
border-radius: 0;
-webkit-appearance: none;
}
.nav-button.active,
.nav-button:hover {
background-color: black;
color: white;
}
.btn {
border-radius: 0.5rem;
padding: 0.375rem;
border: 1px solid black;
color: black;
cursor: pointer;
text-decoration: none;
background-color: transparent;
}
</style>
</head>
<body>
<div class="window">
<div class="app">
<div class="nav">
<div class="col">
<!-- Nav Header -->
<div class="flx-row x-center-row">
<div class="header">
<h1>Joystick Testing</h1>
</div>
</div>
<!-- Nav Menu -->
<div class="flx-row x-center-row p-2">
<!-- Joysticks -->
<input type="button" name="nav-option" class="btn nav-button" id="nav-joysticks/" data-redirect="joysticks/" value="Joysticks" />
<!-- Slider -->
<input type="button" name="nav-option" class="btn nav-button" id="nav-slider/" data-redirect="slider/" value="Slider" />
</div>
</div>
</div>
<div class="main">
<div class="view" id="/slider/">
<div class="row">
<div class="flx-12 flx-col">
<div class="joystick">
<div class="joystick-labels"><span class="x-label" id="x-slider"></span></div>
<input type="range" class="sliders" min="0" max="8" value="4" data-x="x-slider" />
</div>
</div>
</div>
</div>
<div class="view" id="/joysticks/">
<div class="row">
<div class="flx-12 flx-col">
<!-- Joystick 1 -->
<div class="joystick">
<div class="joystick-labels">
<span class="x-label" id="x-joystick"></span><span class="y-label" id="y-joystick"></span>
</div>
<div class="joystick-canvas">
<canvas class="canvas-joysticks" data-x="x-joystick" data-y="y-joystick"></canvas>
</div>
</div>
<!-- Joystick 2 -->
<div class="joystick">
<div class="joystick-labels">
<span class="x-label" id="x-joystick1"></span><span class="y-label" id="y-joystick1"></span>
</div>
<div class="joystick-canvas">
<canvas class="canvas-joysticks" data-x="x-joystick1" data-y="y-joystick1"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function redirect(route) {
window.location.hash = `/${route}`;
window.scrollTo(0, 0);
}
window.addEventListener('load', function () {
// This prevents the page from scrolling down to where it was previously.
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
// This is needed if the user scrolls down during page load and you want to make sure the page is scrolled to the top once it's fully loaded. This has Cross-browser support.
window.scrollTo(0, 0);
// Active location handler for nav menu buttons
window.addEventListener('hashchange', e => {
const re = new RegExp(`${window.location.origin}${window.location.pathname}`, '');
const re1 = /#\//;
const css_active = 'active';
const el_new = document.getElementById(`nav-${window.location.hash.replace(re1, '')}`);
if (e.oldURL) {
const el_old = document.getElementById(`nav-${e.oldURL.replace(re, '').replace(re1, '')}`);
if (el_old) el_old.classList.remove(css_active);
}
if (el_new) el_new.classList.add(css_active);
});
// Navigate to the app home page defined in routes on startup
if (window.location.hash === '' || !window.location.hash) {
redirect('joysticks/');
}
// Handle unknown starting location
window.dispatchEvent(new Event('hashchange'));
// Setup
init();
});
function init() {
/**
* Initialise joysticks
*/
const setJoysticks = () => {
// Joystick color palette
const joystickPalette = [
{
background: '#d3d3d3',
fill: '#000000',
stroke: '#000001',
},
{
background: '#008000',
fill: '#000000',
stroke: '#000001',
},
];
// Get all joystick canvas elements
const els_canvasJoysticks = document.getElementsByClassName('canvas-joysticks');
for (let i = 0, l = els_canvasJoysticks.length; i < l; i++) {
// Variables
const canvas = els_canvasJoysticks[i];
const ctx = canvas.getContext('2d');
const coordLabels = {
x: document.getElementById(canvas.dataset.x),
y: document.getElementById(canvas.dataset.y),
};
let width, height, radius, multiplier, ratioX, ratioY;
let coord = { x: 0, y: 0 };
let paint = false;
/**
* Update the UI joystick coordinates
*/
const updateJoystickCoords = (x, y) => {
coordLabels.x.textContent = parseFloat(x.toFixed(2));
coordLabels.y.textContent = parseFloat(y.toFixed(2));
};
// Initalise coordinate labels
updateJoystickCoords(0, 0);
/**
* Shorthand WebSocket outgoing helper
*/
const send = (x, y) => {
console.log(`id:${i},x:${x},y:${y}`);
connection.send(`${i} ${x} ${y}`);
};
/**
* Get and set the mouse coordinates
*/
const getPosition = event => {
if (event) {
const mouse_x = event.clientX || event.touches[0].clientX;
const mouse_y = event.clientY || event.touches[0].clientY;
coord.x = mouse_x - canvas.offsetLeft;
coord.y = mouse_y - canvas.offsetTop;
}
};
/**
* Draw the joystick base (background)
*/
const background = () => {
ctx.beginPath();
ctx.arc(ratioX, ratioY, radius + 20, 0, Math.PI * 2, true);
ctx.fillStyle = joystickPalette[i].background;
ctx.fill();
};
/**
* Draw the joystick handle
*/
const joystick = (width, height) => {
ctx.beginPath();
ctx.arc(width, height, radius, 0, Math.PI * 2, true);
ctx.fillStyle = joystickPalette[i].fill;
ctx.fill();
ctx.strokeStyle = joystickPalette[i].stroke;
ctx.lineWidth = 8;
ctx.stroke();
};
/**
* Helper function to see if coordinates are within the given coordinates
*/
const isInCircle = coords => {
const current_radius = Math.sqrt(Math.pow(coords.x - ratioX, 2) + Math.pow(coords.y - ratioY, 2));
if (radius >= current_radius) return true;
else return false;
};
/**
* Drawing handler
*/
const Draw = event => {
if (paint) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
background();
let x, y;
const angle = Math.atan2(coord.y - ratioY, coord.x - ratioX);
if (isInCircle(coord)) {
joystick(coord.x, coord.y);
x = coord.x;
y = coord.y;
} else {
x = radius * Math.cos(angle) + ratioX;
y = radius * Math.sin(angle) + ratioY;
joystick(x, y);
}
getPosition(event);
const x_relative = Math.round((x - ratioX) * multiplier);
const y_relative = -Math.round((y - ratioY) * multiplier);
updateJoystickCoords(x_relative, y_relative);
send(x_relative, y_relative);
}
};
/**
* Test drawing conditions and call draw handler on true
*/
const startDrawing = event => {
paint = true;
getPosition(event);
if (isInCircle(coord)) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
background();
joystick(coord.x, coord.y);
Draw();
}
};
/**
* Reset joystick position (to center)
*/
const stopDrawing = () => {
paint = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
background();
joystick(ratioX, ratioY);
updateJoystickCoords(0, 0);
send(0, 0);
};
/**
* Resize the canvas and update joystick drawing
*/
function resize() {
ctx.canvas.width = width;
ctx.canvas.height = height;
background();
joystick(ratioX, ratioY);
}
/**
* Set the joystick dimensions
*/
function setDimensions() {
const el = document.getElementsByClassName('joystick-canvas')[0];
const el_width = el.offsetWidth;
const el_height = el.offsetHeight;
const x_y = el_height < el_width ? el_height : el_width;
const center = x_y / 2;
radius = x_y / 5;
width = x_y;
height = x_y;
multiplier = 100 / radius;
ratioX = center;
ratioY = center;
resize();
}
// Set both canvas dimensions
setDimensions();
// Add event listeners to the canvas
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mousemove', Draw);
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchend', stopDrawing);
canvas.addEventListener('touchcancel', stopDrawing);
canvas.addEventListener('touchmove', Draw);
}
// Update canvas dimensions when window is resized
window.addEventListener('resize', setDimensions);
};
/**
* Initialise slider
*/
const setSlider = () => {
// Get all slider elements
const els_sliders = document.getElementsByClassName('sliders');
for (let i = 0, l = els_sliders.length; i < l; i++) {
// Variables
const coordLabels = {
x: document.getElementById(els_sliders[i].dataset.x),
};
/**
* Update the UI slider coordinates
*/
const updateSliderCoords = x => {
coordLabels.x.textContent = x;
};
const send = x => {
console.log(`id ${2} x ${x} y ${0}`);
connection.send(`${2} ${x} ${0}`);
};
// Initalise coordinate labels
updateSliderCoords(els_sliders[i].value);
// Update the slider coordinates on slider update
els_sliders[i].addEventListener('input', e => {
const value = e.target.value.slice();
updateSliderCoords(value);
send(value);
});
}
};
/**
* Initialise navigation buttons
*/
const setNavRoutes = () => {
// Get all the navbar buttons
const els_navOptions = document.getElementsByName('nav-option');
// Attach a declared route to each button
for (let i = 0, l = els_navOptions.length; i < l; i++) {
els_navOptions[i].addEventListener('click', e => {
redirect(e.target.dataset.redirect);
setJoysticks();
});
}
};
// Call
setJoysticks();
setSlider();
setNavRoutes();
}
var gateway = `ws://${window.location.hostname}/ws`;
var connection = new WebSocket(gateway);
connection.onopen = function () {
connection.send('Connect ' + new Date());
};
connection.onerror = function (error) {
console.log('WebSocket Error ', error);
alert('WebSocket Error ', error);
};
connection.onmessage = function (e) {
console.log('Server: ', e.data);
};
</script>
</body>
</html>
)rawliteral";
////////////////////////////////////////// Initalisation ////////////////////////////////////////
void setup()
{
Serial.begin(115200);
delay(10);
// initialise PCA9685 boards
left.begin();
right.begin();
left.setOscillatorFrequency(27000000);
right.setOscillatorFrequency(27000000);
left.setPWMFreq(50);
right.setPWMFreq(50);
delay(20);
// intialise web socket connection
if (connecttowifi == 1)
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());
initWebSocket();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send_P(200, "text/html", index_html); });
server.begin();
}
}
//
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len)
{
UpdateRemote((char *)data);
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT)
{
data[len] = 0;
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}
void initWebSocket()
{
ws.onEvent(onEvent);
server.addHandler(&ws);
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++)
{
if (data.charAt(i) == separator || i == maxIndex)
{
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void UpdateRemote(String input)
{
String StringOutput[4];
for (int i = 0; i < 4; i++)
{
StringOutput[i] = getValue(input, ' ', i);
}
int remoteid = StringOutput[0].toInt();
if (remoteid == 0)
{
// xremote = 0.1 * StringOutput[1].toInt();
// zremote = 0.1 * StringOutput[2].toInt();
// Serial.print("remote values: ");
// Serial.print(xremote);
// Serial.print(" ");
// Serial.print(zremote);
// Serial.println(" ");
}
else if (remoteid == 1)
{
// degreeremote = 0.04 * StringOutput[1].toInt();
// Serial.print("degreeremote value: ");
// Serial.println(degreeremote);
}
else if (remoteid == 2)
{
// s = StringOutput[1].toInt();
// Serial.print("s = ");
// Serial.println(s);
}
return;
}
void CheckBattery()
{
float voltage = 0.00475*analogRead(13);
Serial.println(voltage);
return;
}
void loop()
{
CheckBattery();
}
Any help would be appreciated!