Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

ESP8266 with Arduino IDE - Code Not Being Stored and an INA219A Question

Status
Not open for further replies.

JonSea

Well-Known Member
Most Helpful Member
I am programming a NodeMCU using the Arduino IDE. I am testing some code for someone and I'm having a few problems.

The first problem: I can compile the code and upload it. That works well. But if I remove power or press reset, the code disappears. I know I'm one of the only people who struggles with the "simple to use" ESP8266s, but I've never had much luck with them. Obviously, I am missing a step but I can't see what it is.


Second problem: I am reading an Adafruit INA219A current sensors. I need to get the maximum resolution from the bus voltage. Looking through the Adafruit INA219.h file, I see the following lines:

#define INA219_CONFIG_BADCRES_MASK (0x0780) // Bus ADC Resolution Mask
#define INA219_CONFIG_BADCRES_9BIT (0x0080) // 9-bit bus res = 0..511
#define INA219_CONFIG_BADCRES_10BIT (0x0100) // 10-bit bus res = 0..1023
#define INA219_CONFIG_BADCRES_11BIT (0x0200) // 11-bit bus res = 0..2047
#define INA219_CONFIG_BADCRES_12BIT (0x0400) // 12-bit bus res = 0..4097

I want the 12 bit resolution, but I don't see what to do with this in the INA219 library file.

Please excuse my somewhat ignorant questions. I just need to do some simple testing.
 
I currently have a Wemos mini next to me and if I press reset it runs my code which is a server reading temp and humidity. I have just changed the micro usb lead to a charge only lead and it still runs my code. I don't have a NodeMCU but I thought they were practically identical to the Wemos.

I would assume that somewhere in the INA219 library there is a xxxx.begin() that takes the define as a parameter.

Mike.
Edit, does this help, https://forums.adafruit.com/viewtopic.php?f=19&p=161485
 
Thank you Mike. That should be the ticket for the settings.

The NodeMCU and Wemos are essentially the same. I tried a different board with the same results. The code isn't permanent,
 
Could the code be somehow interacting with the development system? Have you tried a simple blink program?

Mike.
 
The code should be permanent I've not used one for this but I have 2 that turn on lights using the arduino ide to upload they work on reset.
 
Jon,

Here's the simplest program I could think of. It sets up an access point that you should be able to see.
Code:
#include <ESP8266WiFi.h>

const char WiFiAPPSK[] = "password";
const char AP_NameChar[] = "Mikes Board";

WiFiServer server(80);
IPAddress ip(192,168,1,100);      
IPAddress gateway(192,168,1,100);
IPAddress subnet(255, 255, 255, 0);

void setup() {
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(ip, gateway, subnet);
  WiFi.softAP(AP_NameChar, WiFiAPPSK);
}

void loop() {
}

If you compile this then a new access point should appear in your list called Mikes Board.

It's the only way I could think of to make it visible without using the serial.

Mike.
 
This is the same kind of problem I had in the past using a completely (non-Ardino) dev chain.

I believe the blink program did the same thing. I will try that again in the morning.

For what I'm doing now, all I really need to do is check the response of the INA219, but I'd like to be able to develop some working code now that I've got my feet wet.

One project I have in mind is an ESP8266 access point controlling a relay. Our cable modem and router sometimes get hung up and need a hard reset. They are inconvenient to reach and of course anything on our wifi network will be inaccessible when that happens. It would be handy to log on to the "reset network" to restart them when they are hung.
 
Mike, you answered my question as I was typing it! You are a genius :)
 
The code isn't permanent
Once programmed, you need to connect GPIO0 to 3.3v with a 10 K which your board should have.
But if you used that pin you have to make sure it can pull up the best thing just leave it alone
that would cause what you saying to happen if you some how have it held low
 
When you get around to your access point code, here's an example that uses 3 links to control an RGB LED on D0 - D2 on the Wemos.
Code:
#include <ESP8266WiFi.h>

const char WiFiAPPSK[] = "password";
const char AP_NameChar[] = "Mikes Board";

const int RED_PIN = D0;
const int BLUE_PIN = D1;
const int GREEN_PIN = D2;

WiFiServer server(80);
IPAddress ip(192,168,1,100);        // where xx is the desired IP Address
IPAddress gateway(192,168,1,100);   // set gateway to match your network
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
String Red,Blue,Green;

void setup() {
  Serial.begin(115200);
  while (!Serial);
  delay(100);
  pinMode(RED_PIN,OUTPUT);
  digitalWrite(RED_PIN,LOW);
  Red="<a href=\"/RED=ON\"><button><font size=3>Click here to turn ON RED.<br><br></button></a><br><br>";
  pinMode(GREEN_PIN,OUTPUT);
  digitalWrite(GREEN_PIN,LOW);
  Green="<a href=\"/GREEN=ON\"><button><font size=3>Click here to Turn ON GREEN.<br><br></button></a><br><br>";
  pinMode(BLUE_PIN,OUTPUT);
  digitalWrite(BLUE_PIN,LOW);
  Blue="<a href=\"/BLUE=ON\"><button><font size=3>Click here to Turn ON BLUE.<br><br></button></a><br><br>";
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(ip, gateway, subnet);
  WiFi.softAP(AP_NameChar, WiFiAPPSK);
  server.begin();
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.softAPIP());
  Serial.println("/");
  Serial.println("Initialization Complete");
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  if (request.indexOf("/RED=ON") != -1){
    Red="<a href=\"/RED=OFF\"><button style=\"background-color:red\"><font size=3>Click here to turn OFF RED.<br><br></button></a><br><br>";
    digitalWrite(RED_PIN, HIGH);
  }
  if (request.indexOf("/RED=OFF") != -1){
    Red="<a href=\"/RED=ON\"><button><font size=3>Click here to turn ON RED.<br><br></button></a><br><br>";
    digitalWrite(RED_PIN, LOW);
  }
  if (request.indexOf("/GREEN=ON") != -1){
    Green="<a href=\"/GREEN=OFF\"><button style=\"background-color:green\"><font size=3>Click here to Turn OFF GREEN.<br><br></button></a><br><br>";
    digitalWrite(GREEN_PIN, HIGH);
  }
  if (request.indexOf("/GREEN=OFF") != -1){
    Green="<a href=\"/GREEN=ON\"><button><font size=3>Click here to Turn ON GREEN.<br><br></button></a><br><br>";
    digitalWrite(GREEN_PIN, LOW);
  }
  if (request.indexOf("/BLUE=ON") != -1){
    Blue="<a href=\"/BLUE=OFF\"><button style=\"background-color:blue\"><font size=3>Click here to Turn OFF BLUE.<br><br></button></a><br><br>";
    digitalWrite(BLUE_PIN, HIGH);
  }
  if (request.indexOf("/BLUE=OFF") != -1){
    Blue="<a href=\"/BLUE=ON\"><button><font size=3>Click here to Turn ON BLUE.<br><br></button></a><br><br>";
    digitalWrite(BLUE_PIN, LOW);
  }
 
  //Build the html page
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.println(Red);
  client.println(Green);
  client.println(Blue);
  client.println("</html>");

  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
}

Mike.

Edit, above uses links to turn on/off. I have a slider version somewhere if you need it.
 
The NodeMCU board should already have that. The guy who I made this board for, and whose code I am running, doesn't have this issue, which mades it really weird.

Some pin we have used does interfere with programming; part of my testing will be to determine which pin(s) are causing problems and correct those in the next layout.

We pull the NodeMCU from the board for programming now.
 
New data point.

When I load the blink program, the program persists.

The program I'm testing has no visible indication it's running; it has serial output. Turns out the serial monitor needs to be shut down and restarted to see the output after disconnecting the ESP8266. Restarting the monitor shows the program still to be running.
 
Don't feel bad about that one the serial monitor had some updates and it changed how it works I've not tried the esp since it updated
It now shows up the uno as com 0 and if I unhook it just like you say I have to restart it but that kind of bugs me cause I use the arduino to fast test idea then try my damnedest to rewrite the same code on a pic using xc8 LOL
Kind of started liking arduino without the cores let's you write avr code and build with the arduino ide .
Get better speed without the bloat ware.
 
I've been playing with websockets looks like a good way to send data fast and it keeps the esp alive
Code:
/*
 * ESP8266 Web server with Web Socket to control an LED.
 *
 * The web server keeps all clients' LED status up to date and any client may
 * turn the LED on or off.
 *
 * For example, clientA connects and turns the LED on. This changes the word
 * "LED" on the web page to the color red. When clientB connects, the word
 * "LED" will be red since the server knows the LED is on.  When clientB turns
 * the LED off, the word LED changes color to black on clientA and clientB web
 * pages.
 *
 * References:
 *
 * https://github.com/Links2004/arduinoWebSockets
 *
 */
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
static const char ssid[] = "Ratliffs";
static const char password[] = "8595364920";
MDNSResponder mdns;
static void writeLED(bool);
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
<title>Lights</title>
<style>
body {
    background-color: lightblue;
}
</style>
<style>
"body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }"
</style>
<script>
var websock;
function start() {
  websock = new WebSocket('ws://' + window.location.hostname + ':81/');
  websock.onopen = function(evt) { console.log('websock open'); };
  websock.onclose = function(evt) { console.log('websock close'); };
  websock.onerror = function(evt) { console.log(evt); };
  websock.onmessage = function(evt) {
    console.log(evt);
    var e = document.getElementById('ledstatus');
    if (evt.data === 'ledon') {
      e.style.color = 'blue';
    }
    else if (evt.data === 'ledoff') {
      e.style.color = 'black';
    }
    else {
      console.log('unknown event');
    }
  };
}
function buttonclick(e) {
  websock.send(e.id);
}
</script>
</head>
<body onload="javascript:start();">
<h1>Lights On</h1>
<div id="ledstatus"><b>LED</b></div>
<button id="ledon"  type="button" onclick="buttonclick(this);">On</button> 
<button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
</body>
</html>
)rawliteral";
// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 4;
// Current LED status
bool LEDStatus;
// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
  Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
  switch(type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\r\n", num);
      break;
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
        // Send the current LED status
        if (LEDStatus) {
          webSocket.sendTXT(num, LEDON, strlen(LEDON));
        }
        else {
          webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
        }
      }
      break;
    case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\r\n", num, payload);
      if (strcmp(LEDON, (const char *)payload) == 0) {
        writeLED(true);
      }
      else if (strcmp(LEDOFF, (const char *)payload) == 0) {
        writeLED(false);
      }
      else {
        Serial.println("Unknown command");
      }
      // send data to all connected clients
      webSocket.broadcastTXT(payload, length);
      break;
    case WStype_BIN:
      Serial.printf("[%u] get binary length: %u\r\n", num, length);
      hexdump(payload, length);
      // echo data back to browser
      webSocket.sendBIN(num, payload, length);
      break;
    default:
      Serial.printf("Invalid WStype [%d]\r\n", type);
      break;
  }
}
void handleRoot()
{
  server.send_P(200, "text/html", INDEX_HTML);
}
void handleNotFound()
{
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}
static void writeLED(bool LEDon)
{
  LEDStatus = LEDon;
  // Note inverted logic for Adafruit HUZZAH board
  if (LEDon) {
    digitalWrite(LEDPIN, 1);
  }
  else {
    digitalWrite(LEDPIN, 0);
  }
}
void setup()
{
  pinMode(LEDPIN, OUTPUT);
  writeLED(false);
  Serial.begin(115200);
  //Serial.setDebugOutput(true);
  Serial.println();
  Serial.println();
  Serial.println();
  for(uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
    Serial.flush();
    delay(1000);
  }
  WiFiMulti.addAP(ssid, password);
  while(WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (mdns.begin("espWebSock", WiFi.localIP())) {
    Serial.println("MDNS responder started");
    mdns.addService("http", "tcp", 80);
    mdns.addService("ws", "tcp", 81);
  }
  else {
    Serial.println("MDNS.begin failed");
  }
  Serial.print("Connect to http://espWebSock.local or http://");
  Serial.println(WiFi.localIP());
  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);
  server.begin();
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}
void loop()
{
  webSocket.loop();
  server.handleClient();
}
 
Status
Not open for further replies.

New Articles From Microcontroller Tips

Back
Top