body:
I am using a 5v Arduino pro mini (with regulator and power led removed).

I have been reading how to accurately measure Li-ion batteries when powering from the same battery you are trying to measure from. Using the 1.1V internal analog reference to measure a draining VCC source by using a voltage divider on it, and math to show that converted reading.

Reading the Arduino forums I came across [this answer][1].

      long readVcc() {
      long result;
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Convert
      while (bit_is_set(ADCSRA,ADSC));
      result = ADCL;
      result |= ADCH<<8;
      result = 1126400L / result; // Back-calculate AVcc in mV
      return result;
    }

    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      Serial.println( readVcc(), DEC );
      delay(1000);
    }

However, I cant see a analogRead anywhere in this sketch. (Is this a strictly internal reference?)
At the bottom of the thread someone is saying that you can do this without a voltage divider on the analog pin.

Can someone confirm or explain this? **I don't want to fry my Arduino...**

  [1]: https://forum.arduino.cc/index.php?topic=520674.msg4123985#msg4123985

title: Measuring li-ion that arduino is running from

Answers: 3

body:
Instead of calling `analogRead()`, this sketch performs the equivalent actions by directly manipulating the hardware registers to begin a conversion, wait until the conversion is complete, and collect the converted value.

Just reading the final value is accomplished by the statements:
```
result = ADCL;
result |= ADCH<<8;
```

All of the statements following `delay(2)` up to and including the above 2, taken together, do what `analogRead()` does.

body:
> Using the 1.1V internal analog reference to measure a draining VCC
> source by using a voltage divider on it

You could indeed use a voltage divider, and measure a scaled-down Vcc
against the internal 1.1 V reference. This is, however, not what
the code you posted is doing. It is instead measuring the internal
reference against Vcc, as stated in the comment within the code. The
REFS0 bit selects Vcc as the reference for the ADC. The bits MUX1...MUX3
select the internal reference as the input channel.

> ```c++
> result = ADCL;
> result |= ADCH<<8;
> ```

This idiom dates back from a time when the compiler did not know how to
read 16-bit I/O registers: you had to explicitly read one byte at a time
and then put these together into a 16-bit word. This time is long gone,
and you can now just access the 16-bit register as `ADC` directly. I
would even get rid of the `result` variable and just:

```cpp
return 1126400L / ADC;  // Vcc in mV
```

**Edit**: As suggested by the busybee, here is the explanation of the
factor 1126400: The ADC meaures the ratio of its input voltage to its
reference voltage, and returns this ratio scaled by a factor 1024. In
this case,

  ADC = 1024 × (Vbg ÷ Vcc)

where Vbg is the voltage of the 1.1 V bandgap reference. Thus,

  Vcc = 1024 × Vbg ÷ ADC

If we want Vcc in millivolts, we plus the Vbg voltage in millivolts in
the above equation and get

  Vcc (in mV) = 1024 × 1100 ÷ ADC = 1126400 ÷ ADC

body:
If anyone else is confused by this:

**Will it hurt your Arduino?**

 - **No**, this is a internal voltage reference between VCC & the 1.1v internal analog reference.

**Is a voltage divider necessary?**

 - Not unless you have something external of the Arduino to measure!

**Is the internal reference actually 1.1v?**

 - No, it seems like each pro mini I have the the 1.1v reference is slightly different. My pro minis do not have a break out for the AREF pin, so you need to figure out what the value is for **each individual Arduino**.

I used this,

    1.15 x 1023 x 1000 = [value in quotation from second to last line in the Function]

    return "1125300L" / ADC;

I just incremented the 1.1v reference by 0.01 a couple of times until the output matched the voltage reading on my digital multi-meter. I would think with a known voltage you could do this math backwards to find what AREF actually is. I am sure that would be easier.

A big thanks to JRobert & @ EdgarBonnet for your answers!


body:
I want to show some digits in a 3x3 p10 red led pannel where the number will come from the cloud and the number keeps updating. For this I have used esp8266 based Nodemcu. I have used WiFi Manager library and DMD2 library for this and I am requesting the server every 5 seconds to get the number in response. Everything is working fine but it keeps restarting after some time and there is no fixed timing for this but it keeps restarting. It provides a message that "reset cause 4 boot mode(3,6)" wdt reset... I have tried different hardware and esp board version but nothing is working. I am currently using arduino 1.8.9 and esp8266 board version 2.5.2

please look into my code and suggest me what is wrong....

    #include <Arduino.h>
#include <WiFiManager.h>
#include <math.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <EEPROM.h>
#include <ESP8266WiFi.h>

WiFiManager wifiManager;
int countT;

HTTPClient http;
String svrHost = "";
unsigned int svrPort = 80;
String svrURL = "";

//DMD
#include <SPI.h>
#include <DMD2.h>
#include <fonts/Arial_Black_16.h>
#include <fonts/Droid_Sans_36.h>
#include <fonts/Droid_Sans_12.h>
#include <fonts/Arial_New_56.h>
//#include <fonts/Dmd13x20ClockX.h>
//DMD PIN
#define pin_A 16
#define pin_B 12
#define pin_sclk 0
#define pin_clk 14
#define pin_r 13
#define pin_noe 15

int respin = D2;
int btnstt = 0;

int wlcmgs = 1;
String ssid;

String dmdText = "0";
SPIDMD dmd(3, 3, pin_noe, pin_A, pin_B, pin_sclk);
// Number of P10 panels used X, Y
//DMD_TextBox box(dmd,0,0,32,5);
// Set Box (dmd, x, y, Height, Width)

//const char *MESSAGE = "iTrack LIVE InWard";

void setup(){
 Serial.begin(115200);
 EEPROM.begin(512);
 pinMode(respin, INPUT);

 //Reset Val
 String doResetWifi = "0";
 doResetWifi = readESP(257,1);

 if(doResetWifi == "1"){
  writeESP(257,1,"0");
  wifiManager.resetSettings();
 }

 Serial.println("\nReset Val "+doResetWifi);
 //wifiManager.resetSettings();
 countT = 0;
 wifiManager.autoConnect("LED-1");
 Serial.println("connected...yeey :)");

 //Read/Write EPROM
 if(wifiManager.svrURL != ""){
  svrHost = wifiManager.svrHost;
  svrPort = wifiManager.svrPort;
  svrURL = wifiManager.svrURL;
  //HOST
    writeESP(0,50,svrHost);

  //PORT
    writeESP(51,5,String(svrPort));

  //URL
  writeESP(56,200,svrURL);

 }else{
  //HOST
  svrHost = readESP(0,50);

  //PORT
  svrPort = readESP(51,25).toInt();

  //URL
  svrURL = readESP(56,200);
 }

 //DMD Setup
  dmd.setBrightness(255); // Set brightness 0 - 255
  //dmd.selectFont(Droid_Sans_36); // Font used
  dmd.begin();     // Start DMD
}

void loop(){

 btnstt = digitalRead(respin);
  if (btnstt == 1){
    flashESP();
    ESP.reset();
  }
  doRequest();

      //box.print(dmdText);
  if(wlcmgs==1){
    dmd.selectFont(Droid_Sans_12);
    dmd.drawString(0,0,"Connected");
    delay(5000);
    dmd.clearScreen();
    //scrlssid();
    delay(5000);
    wlcmgs=0;
  }

  dmd.clearScreen();
  dmd.selectFont(Arial_New_56);
  int padingTop = 2;

  dmd.drawString(round((96 - (dmdText.length() * 24)) / 2), padingTop, dmdText);

  delay(1000 * 5);

  //dmd.selectFont(Arial_Black_16);
  //scrtxt();
}

void doRequest(){
 Serial.print("[HTTP] begin: "+svrHost+" "+svrPort+" "+svrURL+"\n");
 String response;
 if (httpRequest(svrHost, svrPort, String("GET /") + svrURL, "", response)) {
  if (response.length() != 0) {

   response.trim();
   dmdText = response;
   Serial.println(response);
   Serial.println(countT);
   countT++;
  }
 }
}

bool httpRequest(const String svrHOST,
         unsigned int svrPORT,
         const String& method,
         const String& request,
         String&       response)
{
 WiFiClient client;

 if (client.connect(svrHOST, svrPORT)) {
  Serial.println("HTTP Connected");
 } else {
  Serial.println("failed");
  return false;
 }

 client.print(method);
 client.println(F(" HTTP/1.1"));
 client.print(F("Host: "));
 client.println(svrHOST);
 client.println(F("Connection: close"));
 if (request.length()) {
  client.println(F("Content-Type: application/json"));
  client.print(F("Content-Length: "));
  client.println(request.length());
  client.println();
  client.print(request);
 } else {
  client.println();
 }

 //Serial.println("Waiting response");
 int timeout = millis() + 5000;
 while (client.available() == 0) {
  if (timeout - millis() < 0) {
   Serial.println(">>> Client Timeout !");
   client.stop();
   return false;
  }
 }

 //Serial.println("Reading response");
 int contentLength = -1;
 while (client.available()) {
  String line = client.readStringUntil('\n');
  line.trim();
  line.toLowerCase();
  if (line.startsWith("content-length:")) {
   contentLength = line.substring(line.lastIndexOf(':') + 1).toInt();
  } else if (line.length() == 0) {
   break;
  }
 }

 //Serial.println("Reading response body");
 response = "";
 response.reserve(contentLength + 1);
 while (response.length() < contentLength && client.connected()) {
  while (client.available()) {
   char c = client.read();
   response += c;
  }
 }
 client.stop();
 return true;
}

void writeESP(int start, int len, String text){
 EEPROM.begin(512);
 int ind;
 for(ind = 0; ind < len; ind++){
   EEPROM.write(ind+start,text[ind]);
 }
 EEPROM.write(ind+start+text.length(),'\0');

 EEPROM.commit();
  EEPROM.end();
}

String readESP(int start, int len){
  EEPROM.begin(512);
 char dataS[len];
 int ind;
 for(ind = 0; ind < len; ind++){
  if(EEPROM.read(ind+start) != '\0'){
   dataS[ind] = EEPROM.read(ind+start);
  }else{
   break;
  }
 }
 dataS[ind]='\0';
  EEPROM.end();
 return String(dataS);
}

void flashESP(){
 Serial.print("\nResetting ESP\n");
 writeESP(257,1,"1");
  ESP.reset();
 delay(2000);
}

/*
void scrtxt(){
  const char *next = MESSAGE;
  while(*next) {
    Serial.print(*next);
    box.print(*next);
    delay(200);
    next++;
  }
}
*/
/*
void scrlssid(){
  dmd.drawString(5,0,"Connected With");
  DMD_TextBox box(dmd,0,20,96,16);
  ssid = WiFi.SSID();
  const char *ssidNext= ssid.c_str();
  int len = 0;
  while(ssidNext && len < ssid.length()){
    Serial.print(*ssidNext);
    box.print(*ssidNext);
    delay(200);
    ssidNext++;
    len++;
    }
  }
 */

title: NodeMcu 1.0 resets automatically after sometime

Answers: 1

body:
From your description it sounds like a Watchdog Timer reset.

The ESP8266 needs to regularly run internal householding tasks outside of your own code, such as Wifi/network related tasks. It will normally take some processing time for those tasks with every `loop()` iteration and with every `delay()` command.

If your code is doing things that take longer than about 3.2 seconds, the internal "watchdog timer" will time out and reset the ESP, which is what you observed.

To ensure this does not happen, you should put a `yield();` command inside pieces of your code that can potentially take longer than 3 seconds, like waiting loops (for example the "Waiting response" `while()` loop and similar pieces of your code). Try this and see if this solves your problem.


body:
I was trying to follow this tutorial and ran into a problem compiling on the Arduino IDE with an ESP32 board. [https://eloquentarduino.github.io/2019/12/how-to-do-gesture-identification-on-arduino/][1]

  [1]: https://eloquentarduino.github.io/2019/12/how-to-do-gesture-identification-on-arduino/

I end up getting multiple lines of error from Arduino saying:

    Error: operand 2 of 'l32r' has out of range value '4294704916'

The code that its struggling to compile is the converted SVM model generated from SciPy. The file is very long, but here is a snippet of what it looks like:

```
#include "model.h"
#include <cstdarg>

int SVM::predict(float *x) {
 float kernels[92] = { 0 };
 float decisions[21] = { 0 };
 int votes[7] = { 0 };
 kernels[0] = compute_kernel(x,   1.2  , -1.79  , -1.1  , 1.22  , -1.36  , 0.26  , 1.0  , -1.57  , -0.81  , 1.08  , -1.45  , -0.18  , 1.18  , -1.77  , -0.31  , 1.59  , -1.69  , 0.55  , 6.74  , 0.71  , -13.06  , 6.31  , 12.0  , -4.34  , 1.55  , -0.16  , 0.0  , 1.38  , 1.91  , 1.02  , 0.96  , -2.28  , -0.45  , 1.3  , -2.12  , -0.49  , 0.83  , -0.18  , -0.79  , 0.92  , -0.73  , 1.34  , 2.59  , -4.15  , -3.4  , 2.22  , -0.2  , 1.41  , 0.61  , -3.91  , -1.39  , 9.29  , 1.85  , -16.0  , 2.4  , -1.02  , -0.75  , 1.87  , 0.18  , 0.47  , 1.38  , -2.06  , 0.06  , 1.32  , -2.16  , 0.1  , 1.63  , -2.2  , -0.16  , 1.47  , -1.49  , -0.08  , 0.98  , -1.51  , -0.55  , 1.3  , -1.53  , -0.12  , 1.32  , -1.61  , -0.47  , 1.18  , -1.26  , -0.2  , 1.43  , -1.06  , 0.06  , 1.3  , -1.18  , -0.59  , 0.94  , -0.1  , 1.04  , 1.28  , -1.41  , -0.55  , 1.26  , -1.3  , -0.18  , 1.28  , -1.65  , -0.39  , 1.26  , -1.36  , 0.63  , 1.45  , -1.45  , -0.57  , 1.65  , -1.32  , -0.63  , 1.3  , -1.28  , -0.35  , 1.22  , -1.3  , -0.31  , 1.22  , -1.02  , 0.16  , 1.12  , -1.43  , -0.39  , 1.1  , -0.96  , 0.43  , 0.92  , -1.12  , -0.37  , 1.24  , -0.86  , 0.0  , 1.1  , -1.12  , -0.24  , 1.12  , -1.34  , -0.2  , 1.16  , -1.14  , -0.1  , 1.14  , -1.12  , -0.24  , 1.24  , -1.1  , -0.26  , 1.16  , -1.39  , -0.24 );
 kernels[1] = compute_kernel(x,   1.1  , 0.24  , 9.49  , -11.73  , -9.12  , 9.63  , -2.5  , -5.48  , 1.87  , 1.53  , -1.14  , 0.96  , 0.79  , -1.96  , -0.75  , 0.55  , -1.61  , -1.39  , 1.41  , -1.91  , -0.57  , 0.88  , -2.1  , 0.2  , 0.29  , -2.22  , 0.73  , 1.69  , 0.45  , -0.14  , 2.08  , -1.89  , 1.0  , 1.16  , 0.84  , 1.59  , 1.45  , -2.36  , -0.83  , 2.36  , -0.71  , 0.61  , -9.51  , -16.0  , 6.13  , 2.61  , 1.18  , 0.77  , 0.69  , 0.63  , -0.96  , 1.0  , -0.67  , -0.02  , 1.57  , -1.08  , 0.2  , 1.14  , -1.47  , -0.08  , 1.57  , -1.93  , -0.22  , 1.18  , -1.36  , -0.57  , 1.57  , -1.39  , 0.71  , 1.16  , -1.55  , -0.65  , 1.04  , -1.12  , -0.77  , 1.55  , -2.12  , 0.67  , 1.57  , -0.86  , -0.75  , 1.41  , -1.2  , 0.53  , 1.55  , -1.39  , -0.83  , 1.32  , -0.75  , 0.59  , 1.67  , -1.49  , -0.55  , 1.65  , -1.51  , -0.49  , 1.36  , -1.16  , -0.02  , 1.63  , -1.22  , -0.35  , 1.49  , -1.2  , -0.26  , 1.38  , -1.32  , -0.02  , 1.39  , -1.22  , -0.12  , 1.41  , -1.0  , -0.1  , 1.43  , -1.18  , -0.14  , 1.41  , -1.22  , -0.02  , 1.55  , -1.3  , -0.33  , 1.45  , -1.2  , -0.24  , 1.38  , -1.3  , -0.26  , 1.38  , -1.28  , -0.12  , 1.3  , -1.06  , -0.12  , 1.39  , -1.32  , -0.2  , 1.39  , -1.22  , -0.18  , 1.43  , -1.1  , -0.24  , 1.43  , -1.32  , -0.33  , 1.45  , -1.08  , -0.37 );
 kernels[2] = compute_kernel(x,   1.55  , -1.67  , -2.16  , 1.59  , -0.04  , 1.16  , 1.38  , -2.71  , -1.06  , 2.04  , 1.41  , 1.49  , 1.16  , -0.67  , 6.66  , 0.79  , -7.94  , 8.51  , 2.4  , -0.41  , 2.32  , 1.45  , -0.37  , 0.0  , 1.61  , -1.67  , -0.28  , 2.04  , -0.96  , -0.57  , 1.04  , -0.83  , 0.61  , 1.38  , -1.08  , -0.33  , 1.65  , -0.24  , -1.96  , 2.06  , -2.99  , -0.92  , 8.31  , 4.83  , 2.3  , 4.79  , -3.89  , -5.38  , 0.67  , -2.67  , 1.2  , 3.03  , 1.41  , -0.86  , 2.36  , -1.85  , -1.32  , 2.32  , -1.32  , 0.75  , 1.69  , -1.2  , -0.35  , 1.28  , -1.04  , 0.22  , 1.28  , -1.12  , -0.37  , 1.87  , -1.14  , 0.33  , 1.83  , -1.24  , -0.26  , 1.77  , -0.94  , -0.51  , 1.63  , -0.79  , 0.22  , 1.47
//and so on
decisions[0] = 1.245222806707
 + kernels[1] * 0.00090445776
 + kernels[2] * 0.000488112628
 + kernels[8] * 0.000123322494
//and so on
```
I have the following flags enabled on the compiler:

    compiler.c.extra_flags=-mlongcalls -mtext-section-literals

It just won't compile for some reason and gives me the same l32r message. Can someone please help? Much is appreciated.

title: Error compiling to ESP32 using Arduino: Operand 2 of 'l32r' has out of range value

Answers: 0


body:
So this is a bit weird, and I don't understand anything.
Basically, I'm just playing with my servo. I wrote a small program, which can be found at this link: https://pastebin.pl/view/8e9c9573 (Note: It's three files, I left some comments there, and the `idk` function is just my last resort, trying to separate myself from `loop`, I really don't know :/ ).

So I run `controller.Setup()` in the `setup` function, and then in loop I just move it to 180 and detach it, then I run into an infinite loop. Note: I know it's not very good code, but that's not what concerns me right now.

The problem is, when I add the call to detach (line 22), the previous move doesn't run! I think I'm going crazy, cause as soon as I remove the line and recompile, it actually moves.

I tried to remove the lock(`Controller::m_Attached`), and it still doesn't work. Please let me know if I didn't notice something, but I really don't understand.

Notes:
* I'm using `arduino-cli`, here's my not-very-perfect Makefile: https://pastebin.pl/view/daa852ff
* I use the Servo library: https://www.arduino.cc/reference/en/libraries/servo/
* I'm using an Arduino Uno

EDIT:
Someone told me to post the code in the question, so here I go:
```
//Main.ino
#include <Servo.h>
#include "Controller.h"

Controller controller(3);

void idk();

void setup() {
    Serial.begin(9600);
    controller.Setup();
}

void loop() {
    idk();
    while(true);
}

void idk() {
    controller.Move(180);
    controller.Unlock();
}

// Controller.h
#pragma once
#include <Servo.h>

class Controller
{
public:
    Controller(int servoPin)
        : m_ServoPin(servoPin), m_Attached(false) {}

    void Setup();
    void Move(int angle);

    void Lock();
    void Unlock();

private:
    Servo m_Servo;
    bool m_Attached;
    const int m_ServoPin = 3;
};

// Controller.ino
#include "Controller.h"

void Controller::Setup()
{
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
    Serial.print("[CONTROLLER] Attached Servo\n");
}

void Controller::Move(int angle)
{
    if (m_Attached)
        m_Servo.write(angle);
}

void Controller::Lock() {
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
}

void Controller::Unlock() {
    m_Servo.detach();
    m_Attached = false;
}
```

title: Servo doesn't move if I detach it AFER the write?

Answers: 1

body:
The detach() function probably stops the data pin from outputting the servo control signal.

Your code disables the control signal a few microseconds after it is enabled.

The cotrol signal is never generated.

Furthermore, a servo requires the signal to be present at all times for it to keep its position.

When your programming includes real-world events, you have to think about the time frame of the events, and about the time frame of the running program.

Think in the terms that the program can loop 100,000 times before the servo has finished moving.


body:
I saw in Arduino Mega's datasheet that the sum of currents out of all input/output pins combined should be maximum 200mA. But I want to make 16 vibration motors and 5 servos work together on the same time. I made the circuit(NMOS, flyback diode, etc.) for every coin vibration motor.Also I'm thinking to power the servos with an external power source.Are the circuits enough so i dont pass the 200mA limit? How can I make the whole thing work together?
im using the following components:
 1. [NMOS][1]
 2. [coin vibration motor][2]
 3. [servo motor][3]

  [1]: https://www.onsemi.com/pub/Collateral/2N7000-D.PDF
  [2]: https://www.sparkfun.com/datasheets/Robotics/310-101_datasheet.pdf
  [3]: https://components101.com/motors/mg90s-metal-gear-servo-motor

title: How to make 16 coin vibration motors and 5 servos work at the same time on a Arduino Mega?

Answers: 0


body:
I am seeing some very strange behavior with my ESP8266. When I connect it to the WiFi for the first couple of times I am not seeing any issues and the ESP8266 connects just fine.

But after an arbitrary amount of times (like when I restart the unit) it tries to connect for AGES (like multiple minutes). Eventually it says "Connected" but the IP is completely wrong and it is not connected to the internet (GET request fails).

Here are the odd things:

 - If I assign a static IP then it ALWAYS works and connects within seconds
 - If I factory reset my router then it works again for a few times
 - I have not seen this with any other device (like laptops or cellphones)

It is almost as if the DHCP is failing to assign an IP and then returns some random default.

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #include <WiFiClient.h>

    // Replace these with your WiFi network settings
    const char* ssid = "MYSSID"; //replace this with your WiFi network name
    const char* password = "MYPASSWORD"; //replace this with your WiFi network password

    void setup() {
      Serial.begin(115200);
      delay(1000);

      IPAddress ip(192,168,1,77);
      IPAddress gateway(192,168,1,1);
      IPAddress subnet(255,255,255,0);

    // If I uncomment this line then it works fine
    //  WiFi.config(ip, gateway, subnet);

      WiFi.begin(ssid, password);

      Serial.println();
      Serial.print("Connecting");

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      Serial.println("success!");
      Serial.print("IP Address is: ");
      Serial.println(WiFi.localIP());
    }

    void loop() {
      HTTPClient http;

      String serverPath = "http://www.google.com";
      http.begin(serverPath.c_str());

      // Send HTTP GET request
      int httpResponseCode = http.GET();
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      String payload = http.getString();
      Serial.println(payload);
      // Free resources
      http.end();

      delay(1000);
    }

When DHCP magically works it assigns: `192.168.1.159`

When DHCP does not work I get: `169.254.104.241`

When I use a static IP then the static IP is assigned.

**So the question is:** Has anyone seen this behavior and maybe give some hints about how I can get the internet connection to be consistent without needing a static IP?

**Update:**
If I run a ping to `169.254.104.241` I get a reply. But if I try to get anything from the internet I get HTTP Response Code = -1.

title: ESP8266 WiFi Not Connecting to Internet Without Static IP

Answers: 3

body:
This is normal behavior. well not really, that address is called a **apipa address**.

It's normal behavior for alot of O.S's to give itself an address in the 169.254.x.x range **when they fail to get DHCP responses**.

My guess is your library is doing this for you.

It's kind of like the ad-hoc of addressing, if all devices fail to get a dhcp response they will all be assigned to the same subnet, and can communicate with those **apipa addresses**.

My suspicion is that it may be your router.
You can verify this by downloading a free DHCP server application for your OS. Plug in via Ethernet for the PC that's running the DHCP App, Turn off DHCP in the router. If it stops happening you know it's the router.

Edit: Also, this may be a firmware caveat in the router. Check the router manufacturers website and see if any firmware updates are available. if it hangs with DHCP, most likely every customer with that firmware revision has had this problem. This sort of thing usually gets patched very quickly.

body:
Finally I figured out a solution. I downgraded the ESP8266 board version in Arduino Studio to 2.5.2 and it worked.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/fmftb.png

body:
Thanks for posting the question and the solution. I spent hours on google and reading message boards before coming across this. I am not sure if my root cause was the same, but to me the "strange" IP for my ESP8266 (nodemcu) came from them connecting through the Guest Network of my Asus router. This resulted in an identical problem to OP with complete random connecting and long duration of no connections to WiFi, Internet and Blynk

Reverting back to ESP8266 2.5.2 in Arduino Studio seems to have magically solved the issue. Someone should alert the makers of the library.


body:
it would seem that this would be a commonly sought-after topic, however I cannot find straightforward libraries for this and it's taking too long, so please allow me the question:

**Is there a good library for Arduino/ESP32 to run principal component analysis (PCA) on a 3D matrix?** Any links etc welcome, [EigenArduino][1] is the 'only' library I could find but it's not exactly straight forward (no example code etc). I want to extract the first component of some data sized `3x3000`.

Thanks

  [1]: https://github.com/vancegroup/EigenArduino

title: PCA on ESP32 - libraries and recommendations?

Answers: 0


body:
I bought one of those Home Depot halloween wolves that howl. You can control it with a push-button to be on, or off. It has its own power source via 3 AA batteries that power the howl sound, red eyes and move the jaw.

I'd like to make it motion sensing using the Arduino motion detector.

I thought that I could just cut and splice the wires connecting the button to the wolf to Arduino leads, then use digitalWrite to turn it on/off based on distance detection but it's not working.

The motion detection is working fine, as I set it up like the motion alarm demo. A red LED lights up at the correct distance as well.

Arduino Setup:
pin 10 to J14
J16 to negative

E14 to wolf
E16 to wolf

I'm not sure which wolf wire is +/- so I've tried both

Code:

```
const int trigPin = 11;           //connects to the trigger pin on the distance sensor
const int echoPin = 12;           //connects to the echo pin on the distance sensor

const int redPin = 3;             //pin to control the red LED inside the RGB LED
const int wolfPin = 10;         //pin that will turn on the wolf

float distance = 0;               //stores the distance measured by the distance sensor

void setup()
{
  Serial.begin (9600);        //set up a serial connection with the computer

  pinMode(trigPin, OUTPUT);   //the trigger pin will output pulses of electricity
  pinMode(echoPin, INPUT);    //the echo pin will measure the duration of pulses coming back from the distance sensor

  pinMode(redPin, OUTPUT);
  pinMode(wolfPin, OUTPUT);
}

void loop() {
  distance = getDistance();   //variable to store the distance measured by the sensor

  if (distance <= 24) {

    analogWrite(3, 255);
    digitalWrite(wolfPin, HIGH);
    delay(5000);

    digitalWrite(wolfPin, LOW);
    delay(1000);
  } else {
    analogWrite(3, 0);
  }

  delay(50);
}
```

I know there's possibility one/both of my spliced wires aren't working, but I don't think so - I'm new, so it's most likely I have so lack of understanding on something.

Please help, Halloween is approaching...

title: Wire Halloween Wolf to howl with Arduino motion detector

Answers: 0


body:
[![enter image description here][1]][1]I have been working on a 4WD robot for a while now. The parts I'm using are Arduino v4 shield, l298N driver motor, Hc 05 ultrasonic sensor, DHT 11, mq2, Bluetooth module, servo motor, ir transmitter and receiver module and an uno all powered by 2 18650 Li ion batteries and a power bank. when i tried using the Ir sensors only, ultrasonic only or both for obstacle detection and avoidance the code freezes and nothing works anymore until i move the obstacle away then the robot makes the decision it wanted to make. it also used to reset occasionally while frozen but i fixed that issue by powering the Arduino separately. i noticed this problem mostly occurs when all the IRs give a low signal. i think the problem is with my code but i don't really see what i typed wrong.

    #include <dht.h>
    #include <Servo.h>

    #define servoPin 11

    // Create a servo object
    Servo Servo1;

    //Ultrasonic Sensor
    #define trigPin 9
    #define echoPin 10
    // defines variables
    long duration;
    int distance;

    //sensor pins
    #define gasSens A4
    dht DHT;

    #define DHT11_PIN 2

    //motor driver pins
    #define in1 8
    #define in2 7
    #define in3 6
    #define in4 5

    //infared pins
    #define lftIr 12
    #define ctrIr 4
    #define rghIr 3

    #define buzzer 13

    int dist=1000;
    int lastVal=0;
    int degVal;
    int leftDist;
    int rightDist;
    int gasVal;
    int logicVal=49;
    int buzzerTrig=0;
    unsigned long curTime;

    void setup() {
      // put your setup code here, to run once:
      Servo1.attach(servoPin);
      Servo1.write(100);

      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);

      pinMode(lftIr,INPUT);
      pinMode(ctrIr,INPUT);
      pinMode(rghIr,INPUT);

      pinMode(buzzer, OUTPUT);

      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);

      curTime=millis();

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(Serial.available() > 0){ // Checks whether data is comming from the serial port
          logicVal = Serial.read(); // Reads the data from the serial port
       }

     if(millis()-curTime>=10000){
        int chk = DHT.read11(DHT11_PIN);
        gasVal=analogRead(gasSens);
        Serial.print(DHT.temperature);
        Serial.print(" C");
        Serial.print("|");
        Serial.print(DHT.humidity);
        Serial.print("%");
        Serial.print("|");
        Serial.print(gasVal);
        Serial.print("|");
        if(gasVal>500){Serial.println("Dangerous gas levels");buzzerTrig=1;}
        else{Serial.println("normal");buzzerTrig=0;}
        curTime=millis();
      }

     if(buzzerTrig==1){
      buzzerCall();
      logicVal==48;
      }

     if(logicVal=='1'){
          dist=distanceCall();

          int leftIr=digitalRead(lftIr);
          int centerIr=digitalRead(ctrIr);
          int rightIr=digitalRead(rghIr);

          if (leftIr==LOW && rightIr==HIGH){
            stopAll();
            while(leftIr==LOW){
              rightMov();
              leftIr=digitalRead(lftIr);
            }
            stopAll();
           }
           else if (leftIr==HIGH && rightIr==LOW){
            stopAll();
              while(rightIr==LOW){
                leftMov();
                rightIr=digitalRead(rghIr);
              }
            stopAll();
          }
          else if (leftIr==LOW && centerIr==LOW && rightIr==LOW){
              stopAll();
                  while(leftIr==LOW || centerIr==LOW || rightIr==LOW){
                    backMov;
                    leftIr=digitalRead(lftIr);
                    centerIr=digitalRead(ctrIr);
                    rightIr=digitalRead(rghIr);
                    }
                    stopAll();
              }

          else if (leftIr==HIGH && centerIr==LOW && rightIr==HIGH){
              stopAll();
              while(centerIr==LOW){
                backMov;
                centerIr=digitalRead(ctrIr);
              }
              stopAll();
              delay(10);
              leftMov();
              delay(500);
              stopAll();
            }
          else{
            fowardMov();
          }
        }
    }

    int distanceCall(){
      // Clears the trigPin
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        // Sets the trigPin on HIGH state for 10 micro seconds
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        // Reads the echoPin, returns the sound wave travel time in microseconds
        duration = pulseIn(echoPin, HIGH);
        // Calculating the distance
        distance= duration*0.034/2;
        return distance;
    }

    void fowardMov(){
      digitalWrite(in2,HIGH);
      digitalWrite(in4,HIGH);
      digitalWrite(in1, LOW);
      digitalWrite(in3, LOW);
    }

    void backMov(){
      digitalWrite(in1,HIGH);
      digitalWrite(in3,HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    }

    void rightMov(){
      digitalWrite(in1, HIGH);
      digitalWrite(in4, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
    }

    void leftMov(){
      digitalWrite(in2, HIGH);
      digitalWrite(in3, HIGH);
      digitalWrite(in1, LOW);
      digitalWrite(in4, LOW);
    }

    void stopAll(){
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }

    void buzzerCall(){
        tone(buzzer, 5000);
        delay(500);
        noTone(buzzer);
        tone(buzzer, 1000);
        delay(500);
        noTone(buzzer);
     }
The goal is for the robot to avoid obstacles and move autonomously using only the IR sensors.
I used to power everything with the batteries but sometimes it shakes and moves slowly so i decided to power them seperately.
Do you think the problem is with my code or it's a hardware problem? Thank you

  [1]: https://i.stack.imgur.com/IFqGM.png

title: 4WD Robot keeps freezing

Answers: 1

body:
I'm not surprised that you are having trouble, as you have a very complicated system.  When troubleshooting complicated systems it is important to break it down into very simple 'chunks' and make sure each simple piece works separately.

I would remove everything but the code for the three IR sensors from your system, and use a random number generator to generate a random number between 0 & 7. Then I would use the binary representation of that number to generate the return values for the digitalRead() calls to the sensors, with appropriate printouts to show you what values were generated and what effect those values produced.  I think you'll find that one or more of the 8 possible values causes problems, as you only have IF clauses for 4 (or 6 if you count the two 2-valued systems twice).


body:
I'm using two tb6600 to control two step motors. It's for letter writing cnc machine.
Moving single axis works fine.

I want to push 2 steppers in the same time along a diagonal.

I tried to calculate ratio x:y, so if x is making more steps than y for 1 y do n x steps. This worked, but machine was shaking no mater how i adjusted delays between step high and low. When i use PWM there is no shaking, but i can't figure out how to make it follow diagonal.

Second try was to use PWM with analogWrite.

    if(delayX > delayY){
          analogWrite(stepPinX, 128);
          analogWrite(stepPinY, 128);

          delay(delayY);
          analogWrite(stepPinY, 0);
          delay(delayX - delayY);
          analogWrite(stepPinX, 0);

        }else if(delayX <= delayY){
          analogWrite(stepPinX, 128);
          analogWrite(stepPinY, 128);

          delay(delayX);
          analogWrite(stepPinX, 0);
          delay(delayY - delayX);
          analogWrite(stepPinY, 0);
        }

This doesn't works obviously[![it follows blue][1]][1]. It reaches end point, but it doesn't follow diagonal.
If i set duty cycle to 2 or 128 it doesn't matter.
Isn't duty cycle supposed to change speed of stepper motor?

What am i missing here and how can this be done?

  [1]: https://i.stack.imgur.com/NaGoJ.png

title: 2 stepper drivers speed control

Answers: 1

body:
Changing the duty cycle does not change the frequency of the PWM signal.

The tb6000 needs a pulse to trigger a step of the motor. If the frequency does not change the pulses per second do not change too and thus the speed is constant.

If you control just one motor the method of using delays to control the frequency works.

But in the case of two motors with different speed you need counter variables to immetate two frequencies (speeds) you need to control each speed of the motors.

First you caculate the ration of the speeds (you said y=1 and x=n steps. Then, the ratio is n:1, i.e the X Motor is faster then the Y Motor by factor n).

The following is just an incomplete example to explain my idea.

    int cntX = 0;
    int cntY = 0;

    // I don't know you value n
    // Let's say n=5
    int ratioX = 5;
    int ratioY = 1;

    // One step per second at max speeed
    // choose whatever fits your needs
    int delayForMaxSpeed = 1000;

    const int stepPinX = 5;
    const int dirPinX = 2;
    const int stepPinY = 6;
    const int dirPinY = 3;
    const int enPin = 8;

    void setup()
    {

      pinMode(stepPinX,OUTPUT);
      pinMode(dirPinX,OUTPUT);
      pinMode( stepPinY, OUTPUT );
      pinMode( dirPinY, OUTPUT );

      pinMode( enPin, OUTPUT );
      digitalWrite( enPin, LOW );

    }

    void loop()
    {
      // Enables the motor to move in a particular direction
      digitalWrite( dirPin, HIGH );

      countx++;
      county++;

      if ( countX >= ratioX )
      {
         countX = 0;
         digitalWrite( stepPinX, HIGH );
      }

      if ( countY >= ratioY )
      {
        countY = 0;
        digitalWrite( stepPinY, HIGH );
      }

      delayMicroseconds( 500 );

      digitalWrite( stepPinX, LOW );
      digitalWrite( stepPinY, LOW );

      delay( delayForMaxSpeed );
    }


body:
I want to do a project where I gather data such as sunlight hours per day, as well as temperature highs/lows. Once I have gathered 24 hours worth of data, I want to hook it up to the computer to read off the values in Serial monitor.
When I try and open the Serial monitor, it restarts the program wiping all the memory.
I tried doing something with PROGMEM, but that didn't seem to help as it is only for constants.
I want to avoid using an LCD to display data if possible.

title: Is it possible to gather data while the Arduino is being powered with a battery, connect to comp, and then read off the values in Serial Monitor?

Answers: 1

body:
Yes, this is perfectly possible. You will need to write a routine that you can trigger via Serial. For example you will listen on Serial until you get the `dump` command. Then run a function that spits your variables out to Serial.

You just have to be careful where you save your 5 variables.

If stored in memory (RAM), you should avoid power loss. Therefore I'd suggest a FTDI USB-to-Serial adapter. There you just connect the TX, RX and GND wires and proceed with the Arduino IDE's Serial Monitor.

If stored in EEPROM, you can use the regular USB connector of Arduino.


body:
I am experimenting with streaming audio from servers using an ESP32 and [this][1] library. I have been able to stream audio from every http server which i have tried but have had mixed success with https servers. I had originally wanted to stream audio from an amazon S3 server but could not get this to work. I have managed to get it to work using the google cloud servers (Both of these are https servers). Any thoughts on what might be the problem would be much appreciated. thanks.
I'm not sure if this is an appropriate forum but im not qute sure where else to post my question. thanks.

  [1]: https://github.com/schreibfaul1/ESP32-audioI2S

title: Trouble streaming audio from amazon s3 servers

Answers: 0


body: I'm working on a project where I need to control the light of 5 buttons as well as listen when each button is switched on/off by the user. I would furthermore like to provide feedback on an OLED display. It looks like I'm running out of pins. This https://arduino.stackexchange.com/a/22689/69029 provides several options for that. I would specifically like to explore the option to have several arduinos connected to each other in a master/slave configuration. Where can I learn more about my option to build stuff using several Arduinos connected to each other? I can also forsee scenarios where I could use 3.3V devices as well as 5V devices.

title: Using several Arduinos simultaneously

Answers: 3

body:
I haven't seen this being done much. But that's probably because it isn't the best option in almost all cases.

Having multiple pieces of code, for different boards, that you have to work together. Constantly having to upload to different boards. This sound like a nightmare.

The only use-case I could see is to have each Arduino have a single function that shouldn't change (much) over time, and having it act like just any another sensor IC, or led driver IC.

The best example of this would be some of the SparkFun Qwiic [Twist](https://www.sparkfun.com/products/15083), [Quad Relay](https://www.sparkfun.com/products/16566), and [Button](https://www.sparkfun.com/products/16842) board. For these they use an Arduino compatible ATTiny84 IC with custom firmware to expose it's functionality over I2C.

But most of their Qwiic boards use custom ICs, since they are either cheaper, or less work to get working.

body: Instead of trying to use multiple Arduino boards, which would be hard, I'd suggest using a bigger Arduino. The mega 2560, for example, has **tons** of GPIO lines.

body:
Among all the options mentioned, using a master/slave should be the last resort, especially when you are new to embedded programming or Arduino, it is not only more complicate but also more expensive to implement.

One potential solution that could free up the precious digital i/o pins that were used by the 5 buttons is using analog input to detect the status of the buttons.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/jgpYG.png)

<!-- End schematic -->

When sw1 is pressed, the voltage at the A0 will be around 0.83v, and when sw5 is pressed, the voltage at the A0 will be 2.5v. You can write a simple `switch...case` to determine which switch has been pressed.

The only problem of this circuit is that it can't handle more than one button been pressed simultaneously, but that could be solved by double the value of each resistor like 10k, 20k, 30k...

This will free-up 5 digital pins that can be used for control (such as servo, relay, etc.).


body:
You can try the code on your arduino UNO to better understand what is hapening in serial monitor!

I want to calculate jacobian matrix from rotation matrix!

    float jakMATB[3][3] = {
    {0, 0, 0},
    {0, 0, 0},
    {0, 0, 0}
         };
    float POKUS = 0;
    float k = 0.000001;
    float dt = 0.001;
    float b = 90 * (PI / 180);
    float vnB[3] = {0, 1, 0}, vpB[3] = {0, 1, 1};
    float nB[3] = {0, 1, 0};
    float nBplus[3] = {0 , 1, 0};
    float nBminus[3] = {0, 1, 0};
    void setup() {
    Serial.begin(9600);
    Serial.print("init ok");
    cli();//stop interrupts
    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1hz increments
    OCR1A = (16000000) / ((1 / dt) * 1024) - 1; // 15624 = (16*10^6) / ((1)*1024) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS12 and CS10 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);
    sei();//allow interrupts
    }
when I call the function in loop everithing works fine and I get  1 2 1 in serial monitor

     void loop() {
     izracunJAKOB();
     for (int j = 0; j <= 2; j++) {
    for (int i = 0; i <= 2; i++) {
      Serial.print(jakMATB[j][i]);
      Serial.print(" ");
    }
    Serial.println("");
    }
    }
when I call izracunJAKOB() with timer interupt Serial monitor
stops working and doesent event write "init ok"

    ISR(TIMER1_COMPA_vect) {
      //izracunJAKOB();
     }
    void izracunJAKOB() {
    for (int j = 0; j <= 2; j++) {
    for (int i = 0; i <= 2; i++) {
      nBplus[j] = nB[j] + k;
      nBminus[j] = nB[j] - k;
      float matricaBplus[3][3] = {
        {cos(b) + nBplus[0]*nBplus[0]*(1 - cos(b)), nBplus[1]*nBplus[0]*(1 - cos(b)) - nBplus[2]*sin(b), nBplus[0]*nBplus[2]*(1 - cos(b)) + nBplus[1]*sin(b)},
        {nBplus[1]*nBplus[0]*(1 - cos(b)) + nBplus[2]*sin(b), cos(b) + nBplus[1]*nBplus[1]*(1 - cos(b)), nBplus[1]*nBplus[2]*(1 - cos(b)) - nBplus[0]*sin(b)},
        {nBplus[0]*nBplus[2]*(1 - cos(b)) - nBplus[1]*sin(b), nBplus[1]*nBplus[2]*(1 - cos(b)) + nBplus[0]*sin(b), nBplus[2]*nBplus[2]*(1 - cos(b)) + cos(b)}
      };
      float matricaBminus[3][3] = {
        {cos(b) + nBminus[0]*nBminus[0]*(1 - cos(b)), nBminus[1]*nBminus[0]*(1 - cos(b)) - nBminus[2]*sin(b), nBminus[0]*nBminus[2]*(1 - cos(b)) + nBminus[1]*sin(b)},
        {nBminus[1]*nBminus[0]*(1 - cos(b)) + nBminus[2]*sin(b), cos(b) + nBminus[1]*nBminus[1]*(1 - cos(b)), nBminus[1]*nBminus[2]*(1 - cos(b)) - nBminus[0]*sin(b)},
        {nBminus[0]*nBminus[2]*(1 - cos(b)) - nBminus[1]*sin(b), nBminus[1]*nBminus[2]*(1 - cos(b)) + nBminus[0]*sin(b), nBminus[2]*nBminus[2]*(1 - cos(b)) + cos(b)}
      };
      jakMATB[i][j] = (matricaBplus[i][j] - matricaBminus[i][j]) / (2 * k);
      nBplus[0] = 0;
      nBplus[1] = 1;
      nBplus[2] = 0;
      nBminus[0] = 0;
      nBminus[1] = 1;
      nBminus[2] = 0;
    }
    }
    }

//////////////////////////////
when I comennt out

       nBplus[j] = nB[j] + k;
       nBminus[j] = nB[j] - k;

and

       nBplus[0] = 0;
       nBplus[1] = 1;
       nBplus[2] = 0;
       nBminus[0] = 0;
       nBminus[1] = 1;
       nBminus[2] = 0;

Serial works just fine

when I coment out only  matricaBminus and  matricaBplus serial works fine

Please help! It surely is a stupid solution!

title: Serial doesent work when calling function from timer

Answers: 1

body: Timer was to fast! When I decreased frequency everithing worked fine.


body:
I hope it's not a sci-fi for arduino. But I saw that dual system with two MCU can program each other via radio connection. It has been done in experimental space cube projects.

It is theoretically possible? I'm thinking about two arduino MCU first of them will be main MCU and second will be like programming device via serial link.I want to program mcu via wifi without cable connection. Somehow send hex file via wifi to eeprom and upload to second device flash memory.

How do you see this issue? Is that a big nonsense?

title: How to program Esp8266 remotly via wifi?

Answers: 1

body:
The firmware update over WiFi is called OTA update. OTA stands for "over the air".

The esp8266 can OTA update itself. The Arduino library for this is called ArduinoOTA and it is bundled with the ESP8266 Arduino boards support package.

See the example for ArduinoOTA library in IDE Examples menu.

Other MCU have the self update option too. ESP32 has it of course, then for SAMD boards Arduino made WiFi101OTA library. For ATmega I made the ArduinoOTA library based on the WiFi101OTA library so it supports SAMD too. And it doesn't have to be WiFi. Cable works too.

The OTA update stores the uploaded firmware in free part of the flash and after successful upload it moves the firmware to target location and resets the MCU.

For any Arduino with SD bootloader OTA update is possible, because the library only has to store the uploaded firmware to the SD card and reset the MCU.

For small ATmega ftp bootloaders exists. Here the bootloader waits for network upload.

Update over a second MCU solutions are for MCU with less flash, mostly for the ATmega328p. The ESPLink firmware and the WiFiLink firmware for ESP8266 can flash attached ATmega328p over RX/TX. The ESP8266AVRISP can flash ATmega wired over SPI.

ArduinoIDE supports OTA upload. It creates a network port based on MDNS record propagated by the ArduinoOTA library or firmware with OTA support.

[![enter image description here][1]][1]

Other update way is to download the new firmware from a server or upload it over a web page. ESP8266 has for this ESP8266httpUpdate and ESP8266HTTPUpdateServer libraries. For SAMD, ATmega and other boards my ArduinoOTA library has examples on how to store and apply the update received as download or upload.

  [1]: https://i.stack.imgur.com/umIwp.png


body:
I was reading the data Sheet of AMIS-30543 stepper motor driver and I was not able to understand how to combine the result of the Micro step position status register MSP[8:0]. I know that its a 9 bit value . Help me understand how to get the value.

In the data sheet it is given like

[![dataSheet][1]][1]

in SR3 -> MSP[8:2], and in SR4 -> MSP[6:0]. How I am I suppose to get the 9 bit out of these.

***
In the library I have seen that , ```(sr3<<2) | (sr4 & 3) ``` . I don't understand why they are doing and `&` here.

Please explain . also If there was no library how am I suppose to know how to combine these registers from the dataSheet .

Link to [DataSheet][2]

  [1]: https://i.stack.imgur.com/rHgg0.png
  [2]: https://www.onsemi.com/pub/Collateral/AMIS-30543-D.PDF

title: AMIS30543 | Data-Sheet understanding Status register

Answers: 1

body:
Most of the data is duplicated between the registers. Both registers contain MSP[6:2].

If MSP contains `111001001` the registers (ignoring the MSB "PAR" bit) would look like:

```
SR3: 1110010
SR4: 1001001
```

If we line those up it's then like:

```
SR3: 1110010
SR4    1001001
```

You can now see the overlap.

So taking SR3 and shifting it left two places (`sr3 << 2`) gives you:

```
SR3:   1110010
<<2: 111001000
```

Taking the lowest two bits of SR4 with `& 3` gives you:

```
SR4:   1001001
& 3:   0000001
```

Then ORing the two results together:

```
SR3<<2: 111001000
SR4 &3: 000000001
-----------------
MSP   : 111001001
```


body:
[![enter image description here][1]][1]I have a fairly simple code to turn a relay on-off every 2 seconds
When i attach the USB of the arduino Uno to the laptop, it goes into a frenzy and the relay triggers on off for 6 times within 3-4 seconds and then it settles down.
This however doesnt happen when connecting directly to the power output.

Is there something that needs to be wired to stop this happening ?

I am using an arduino Uno with a relay JQC-3FF-S-Z connected directly to the arduino pins.

    const int ONOFF_TRIGGER_PIN = 2;

    void setup() {
      // put your setup code here, to run once:
      pinMode(ONOFF_TRIGGER_PIN, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(ONOFF_TRIGGER_PIN, LOW);
      delay(2000);
      digitalWrite(ONOFF_TRIGGER_PIN, HIGH);
      delay(2000);
    }

  [1]: https://i.stack.imgur.com/WLSyB.jpg

title: Relay starts trigger about 6 times when connecting arduino to laptop

Answers: 1

body: The markings on your relay suggest the coil is for 5VDC. But you have the coil supply wired to 3V3. Move the coil supply to 5V, and try again.


body:
I was reading the data sheet of AMIS-30543 stepper motor and I didn't understand fully what does this Circular Translator Table means, I have a couple of doubts

 1. What does Circular Translator table Stands for.? How to read it .? pg:13
 2. What does the current pairs can be projected approximately on a circle in Ix, Iy plane means.? pg:25

[![TranslatorTable][1]][1]

 3. In the data Sheet it is given that **Changes on the NXT input will move the motor current one step up/down in the translator table (even when the motor is disabled: <MOTEN> = 0)**. So the changes happened in the table while the motor was disabled will reflect as soon as the motor become active.? Like if I give say 5 step input while the motor was disabled and when I make the motor enable , will the motor will move by itself to reach that position in the translator table.? pg:25

[Link to datasheet][2]

  [1]: https://i.stack.imgur.com/Hm2es.png
  [2]: https://www.onsemi.com/pub/Collateral/AMIS-30543-D.PDF

title: AMIS30543 | DataSheet Understanding CIRCULAR TRANSLATOR TABLE

Answers: 1

body:
1. It describes the current going through the two coils of the stepper motor at each `step`.

2. I'm not quite sure, as I would think the last two diagrams should actually be squares. But for example, in the first image, you can see that the current in the X coil will steadily increase, while the current in the Y coil will steadily decrease. This will make the stepper rotate more slowly.

   In the second image, you can see that only the Y coil driver is at 100% in step 0. In step 1 both coils are at 100%. In step 2 coil Y is turned off. I think this is profile produces more torque, but is less smooth.

3. No. I you are, for example using full step mode, and the motor is in step 0. If you give it 3 steps forward  (while the motor is disabled) it would drive the coils (once you re-enable to motors) as described in the lookup table for step 3. Which in practice would mean the motor would rotate backward one step (instead of 3 steps forward).

In other cases, it could result in undefined behavior. Going from step 0 to step 2 could mean it would rotate clockwise, anticlockwise, or even not rotate at all.

Though in practice I don't think this would even be an issue, and disabling the motor, but still sending it step pulses is kind of silly.


body:
I'm trying to make a prosthetic hand that can play rock, paper, scissors with a human. It is based on the premise that you push a button and it randomly selects a move to play. After each move, I'd like for it to return to a normal state after a few seconds delay, the human can then decide whom is victorious.

Code I have so far. It doesn't even stop after the degrees I've set, it just keeps turning. I have a cardboard prototype and it has come close to breaking because the servos just keep turning.

```
#include <Servo.h> //servo library

//Define servos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int pos = 0;

void setup()
//define servo signal inputs [digital PWM 2, 3, 4, 5]
{
  servo1.attach(2);
  servo2.attach(3);
  servo3.attach(4);
  servo4.attach(5);

}

void loop()
{
  void rEADY();
  //void rock();
  //void scissors();
  //void paper();
}

void rEADY()
{
  servo1.write(20);
  servo2.write(20);
  servo3.write(20);
  servo4.write(20);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);

}

void rock()
{
  servo1.write(180);
  servo2.write(180);
  servo3.write(180);
  servo4.write(180);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
}

void scissors()
{
  servo1.write(180);
  servo2.write(180);
  servo3.write(0);
  servo4.write(0);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
}

void paper()
{
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
  servo1.write(20);
  servo2.write(20);
  servo3.write(20);
  servo4.write(20);

}
```

title: How do I reset to servo position everytime I excecute a particular sequence

Answers: 0


body: I'm building a person following shopping cart with Arduino for my final year project. The cart is supposed to be able to follow its user while shopping use of Bluetooth module or wifi module will be feasible or not?or I should use IR sensors ?

title: Selection of module for person following shopping cart

Answers: 1

body:
Bluetooth beacon. Use "bluetooth positioning arduino" as search terms.

Bluetooth beacon is a way to achieve the same as a GPS can do outdoor. By placing beacons around the room you can find your position in 3D space.

So a beacon locator on the shopping cart (Arduino with BLE module or a ESP32) and one on you (mobile phone) and then some central unit that can coordinate the two positions.

Just as a concept it would be feasible.


body:
When I write code like this:

    int a = 7
    int b = 2
    int c = a/b
    int r = a%b

Does the chip use the remainder while calculating c or does it redo the entire calculation?

title: Can the atmega328 return remainder during integer division?

Answers: 2

body:
If using optimization, the compiler is smart enough to recognize this.

Since your example is so short, it could be optimized away entirely.
To ensure that doesn't happen, the results in `c` and `r` have to be used in some way.
Also, if `a` and `b` could *never* change, the values of `c` and `r` would be calculated during compilation.
Therefore, I put the calculation in its own function.

From [godbolt.com][1], using AVR-GCC 9.2.0:

    #include<stdint.h>
    #include<stdio.h>

    uint8_t a = 0;
    uint8_t b = 2;
    uint8_t c = 0;
    uint8_t r = 0;

    void calculate() {
        c = a / b;
        r = a % b;
    }

    int main() {
        a = 7;
        b = 2;

        calculate();

        printf("%d %d", c, r);
    }

compiles the `calculate()` function into

    calculate():
            lds r24,a
            lds r22,b
            rcall __udivmodqi4
            sts c,r24
            sts r,r25
            ret

The results, stored in `r24` and `r25` respectively, are re-used from the same division operation.

  [1]: https://godbolt.org/z/bG4cG6

body:
The compiler is only as smart as you provide it the necessary information.

1. It is good to examine code on godbolt.com. But use it wisely.
Noone should ever compile without optimizations. In the example above the code is not optimized and thus would never been used as such on a board.
2. The example is so artificial that the compiler optimizes it away into just 2 instructions. So the code should be representative for the intended usage.
A better godbolt would be:

```
#include<stdint.h>
#include<stdlib.h>

void myDiv(uint8_t * c, uint8_t * r, const uint8_t a, const uint8_t b) {
    *c = a/b;
    *r = a%b;
}
```
So the input is not predetermined and also the resulting numbers are returned and not thrown away. Which translates with `-Os` to:
```
myDiv(unsigned char*, unsigned char*, unsigned char, unsigned char):
        mov r27,r25
        mov r26,r24
        mov r31,r23
        mov r30,r22
        mov r24,r20
        mov r22,r18
        rcall __udivmodqi4
        st X,r24
        st Z,r25
        ret
```
 3. There is the `div(numerator, denominator)` function in `stdlib.h`. This function performs a division and returns both the dividend and the remainder. It is optimized for each platform and uses the best available method to get both. In Godbolt it would look like this:
```
#include<stdint.h>
#include<stdlib.h>

void myDiv2(uint8_t * c, uint8_t * r, const uint8_t a, const uint8_t b) {
    div_t d = div(a, b);
    *c = d.quot;
    *r = d.rem;
}

```
But what surprise, with `-Os` the resulting assembly looks exactly the same! (I leave it to the reader to try it on godbolt).

That means, the compiler is smart enough to:

a. recognise the intention when calling division and modulo an the same operands successively.
b. will use the best available method to achieve the intended calculation for you.

- - -

**EDIT after Edgar Bonet's comment:**
While playing around in godbolt I made a copy-paste mistake. `div` only applies to `int` values. That makes the resulting assembly code larger as there has twice the data to be shoveld around. After changing both examples to `int` they look almost similar. The only difference is:

The result is stored in `d` first and then copied to `c` and `r`.
So the division/modulo code is more efficient in that regard as the resulting values are copied directly from the registers used in the calling convention.

https://godbolt.org/z/61exz7


body: I need 48 sg90 servos to move to a specific position each minute. Now I am using two arduino mega boards to power everything through 6 bread boards but it seems I need more power because some servos are ticking and are delayed. I cant get the external power supply to work independently of the computer. Once I unplug from my computer the servos jitter. Any help would be greatly appreciated.

title: Servos jitter when powered by power module

Answers: 1

body:
Most servos [use an analog signal (width of a pulse) for positioning][1].  Any perturbation in that signal will cause unexpected behavior.  Activating 48 servos simultaneously will likely indirectly or directly affect the analog signal.

[![enter image description here][2]][2]

The unexpected behavior might be mitigated through changes in software or hardware.  These mitigation efforts may include:

 1. Staggering the servo changes so that only 1 servo moves at a time.
 2. Perhaps less effective but worth trying, staggering the servo changes so only 1 servo starts moving at a time.  In this scenario more than 1 servos may be moving at a time.
 3. Using a power supply which maintains the expected voltage even during events such as all servos starting simultaneously.

These are only 3 options to consider.  Many more exist but may not be pertinent to your situation.  More information is needed.

  [1]: https://en.wikipedia.org/wiki/Servo_control#Pulse_duration
  [2]: https://i.stack.imgur.com/L4XjR.jpg


body:
I have a 512 pulses encoder with four wires: +5V, ChannelA, ChannelB, GND and I'm using it as feedback for my motor position (max 80 RPM) on Arduino UNO. Everything works fine, but I need also to generate a +5V signal everytime ChannelA is HIGH since I need to use it to trigger further actions.

I was thinking to read ChannelA by using an optocoupler in order to split the signal and use it both for feedback and for the +5V signal. Is it possible?

Is there any other easier solution to do that?

**EDIT**: I try to explain better what the additional device must do.

The device is a video camera system that takes a +5V signal from the encoder to trigger some actions by software (create key frames or more) and we need it for our computer vision system. I just need to use the encoders both for the motor feedback and to trigger the video camera. The signal is always +5V so I do not have problems with voltage levels. What do you suggest? I do not have to drive loads from channelA output, I just need the +5V signal to trigger the video camera.
Can I split the channelA output and use it both for the motor controller and the video camera inputs?

EDIT2:
Following the useful suggestions of @st2000 I tried to think to a solution like this:

[![enter image description here][1]][1]

Do you think it can work?

EDIT3: I changed swapped the motor controller and the video system positions in the circuit and I changed the voltage source from +12VDC to +5VDC for the motor controller since it accepts only +5V signals as input.

[![enter image description here][2]][2]

EDIT4: Following the suggestions of @st2000, I changed the circuit design by placing in parallel both devices (motor controller and video system) by using the optocoupler (6N136) only for the video output to isolate it from the whole system.

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/09l8K.png
  [2]: https://i.stack.imgur.com/FrSCW.png
  [3]: https://i.stack.imgur.com/qSjn7.png

title: Read encoder output by using an optocoupler

Answers: 2

body:
People sometimes use optical couplers when anticipating large voltage differences or the potential for large voltage differences.  This may always be the case as in a [light dimmer][1].  Or may preventative as in [ground loop mitigation for MIDI connections][2].  If you anticipate these types of situations then an optical coupler may be a good design choice.

Alternatively if the [signal is changing between 0 volts and 5 volts][3] and the [fan out][4] of the signal is larger then the existing load and the new load combined and the new load is [5 volt tolerant][5] then the signal might be able to drive both loads.

You might seek out the specifications of the 3 connected devices in question.  At the very least, discover the current the encoder output will support.  Then measure the resistance to ground of the input to the motor controller and the resistance to ground of the input to the video equipment.  Find the parallel resistance of these two resistance and calculate the current at 5 volts.  If the current is substantially less then the specified capacity of the encoder, the encoder might be able to drive the 2 loads.  This assumes many things such as no ground loops being present.  There are so many variable it is difficult to be predict the outcome.

  [1]: https://www.instructables.com/Arduino-controlled-light-dimmer-The-circuit/
  [2]: https://learn.sparkfun.com/tutorials/midi-tutorial/hardware--electronic-implementation
  [3]: https://en.wikipedia.org/wiki/Logic_level#Logic_voltage_levels
  [4]: https://en.wikipedia.org/wiki/Fan-out
  [5]: http://techwww.in.tu-clausthal.de/site/Dokumentation/IC_digital/Xilinx-FPGA/Virtex2/5V_tolerant_IO_bei_Virtex.pdf

body: A simple cheat is to place the LEDs of the two opto couplers in series and then modify the current limit resistor to bring the current back to where it should be.


body:
        void loop()
        {
        if ( Serial.available() > 0 )
          {
        static char input[inputLength];

        static uint16_t i;

        char c = Serial.read();

        if ( c != '\n')
          input[i++] = c;

        else
        {
          input[i] = '\0';
          i = 0;

          uint16_t array[80];
          uint16_t j = 0;

          if ( !strncmp(input, "SEND", 4) )
          {
            char* p = input + 4;

            while ( (p = strchr(p, ' ')) != NULL )
              array[j++] = strtol(p, &p, 16);

            ir_start(array);
            Serial.println("WURKS");
          }
        }
      }
    }

Hello I can't seem to figure out what this code is doing. I know the main goal but I can't figure out the proccess. If someone could please make the code dumber for me I would appreciate it :). Full code is here since its hard to copy code: https://anonfiles.com/z6ldWff0pf/no_lib_ino

title: Can't understand this codes process

Answers: 2

body:
It's easier to follow if you indent it properly. I'll do that, and add comments as I go:

```c++
void loop() {
    if ( Serial.available() > 0 ) { // If there is something in the serial RX buffer

        static char input[inputLength]; // Create a working string to store data in
        static uint16_t i; // This is the current index in that working string

        char c = Serial.read(); // Read the next character from serial

        if ( c != '\n') // If it's not a "line feed" character...
            input[i++] = c; // then store it in the input string and increment i

        else { // Otherwise...

            input[i] = '\0'; // Terminate the string with a NULL to make it valid C
            i = 0; // Reset the index to 0 ready for next time

            uint16_t array[80]; // Create an 80-int array (temporary)
            uint16_t j = 0; // And an index variable

            if ( !strncmp(input, "SEND", 4) ) { // If the string starts with SEND
                char* p = input + 4; // create a "pointer" to the string that starts 4 characters in

                while ( (p = strchr(p, ' ')) != NULL ) // While there is a space somewhere in the string
                    array[j++] = strtol(p, &p, 16); // convert the first portion to a number, store it in the array, and advance the pointer to the next space.

                ir_start(array); // Send the array through IR
                Serial.println("WURKS"); // Tell us it worked
            }
        }
    }
}
```

So you see it receives data through serial and stores it, byte by byte, in `input` until it receives `\n` at which point it looks to see if it starts with `SEND`, then effectively "cuts off" the SEND by only considering everything after the SEND. Then it slices the remainder of the string up by looking for the next space each time and convert each portion to an integer which it stores in an array.

It then sends that array.

body: I was dumb, turns out it was converting the hex into a int. I sent the array through serial and looked at it.


body:
I am trying to interface [sele EM2M][1], I am using Arduino Mega with [RS 485 module][2]. I want to read the internal registers I am using [ModbusMaster library][3]. The data which I want to receive is in the internal registers but I am not getting how can I read Internal registers. When I use other software to read data I am getting the out [![enter image description here][4]][4]

I also wanted to know the difference between Internal Registers and Holding Registers

Another questions how are the frames formed for communication in rs485 from the above image I can understand 01 04 but from where do they get 00 1A please explain the same.

  [1]: https://gofile.io/d/qeQd1B
  [2]: https://robu.in/product/max485-ttl-rs485/
  [3]: https://github.com/4-20ma/ModbusMaster
  [4]: https://i.stack.imgur.com/3D0Pb.png

title: Read Internal Registers of RS485

Answers: 2

body: The RS485 has no internal registers, all of that is in your target unit. Hopefully the instructions for that will tell you how to do it.  Start by getting simple communications working then slowly progress from there.

body:
The issue is been resolved.
I was reading the holding registers and also I tried to read the Input registers but I didn't received any output it was because the register address entered by me was wrong when I referred to a Simply Modbus Master software from where I was able to receive the data when I send a command, from the same software I came to know about the frame structure and how they were formed. So when I tried to enter those register address they were working fine.

Thank you everyone for your help


body:
i'm not sure if this is the right address, but maybe you know about it.
I currently integrate bluetooth to my car's radio using a esp32. First i wanted to insert the signal at the d2b cd player, but since i don't know the right communication between the occ and the processor i don't see a solution here (and i don't have a cd player to get the reference signals)

But there is a CC player that i can use. There is a detailed documentation about the radio, too:
https://www.motor-talk.de/forum/aktion/Attachment.html?attachmentId=753560
Page 12 (or 16 of the pdf)

TRK1R, TRK1L, TRK2R TRK2L and PBREF are used for the signals.
CCINS will be GND if there is no CC in the slot and otherwise 5V
CCEJT will be 5V if you press the eject button, otherwise it's GND

But this is not enough, there is a tape monitoring circuit that needs to be tricked.
Can you see from the documentation how to do so?

CCPSE is connected from the processor to the tapedeck, but i don't know what it is good for
CCMOD is connected to the latch 2, UG5V and the tapedeck. It's on 5V while the radio is on.
RELL_R and RELL_F are 5V while idle and otherwise they change their value continuously.

CCMET is connected to the CPU, CC Amplifier and the Tapedeck. It's on 5V if the tapedeck is removed and otherwise always 0V. So i short circuit it with GND to simulate there is a tape deck.

CCLDG is connected to the shiftregister and the tapedeck and i have no idea what it is good for. it's always 0V

CCMOT and LED look like they are both the same from the datasheet. They are 0 in general but when the CC is running they turn 5V.

Maybe some can point me out how to trick the tape monitor

Thanks

title: Signal names HiFi

Answers: 1

body: They make adapters that fit into the Tape socket (if you have one) and will play when you select the audio tape. That is no longer an option on the newer car radios. Mine has an audio input I can use, and it is a 2009 Flex.


body:
Simple spec question I couldn't figure out, what is, practically speaking and ballpark, the maximum wattage of LED you can drive with an ESP32 (I guess about the same as an arduino?).

Conditions:

 - using a boost converter for higher voltage: Yes
 - using ESP32 pin as output and power: Yes
 - use mosfets/external power circuit: no
 - no other load is connected to the ESP32 board

My silly calculation:
 - GPIO allows for 12mA output ([source][1])
 - cheap and small voltage boost elements go to about 9-12V

i.e. (12 milliamperes) * 12 volts = max 0.144 watts.

Is that about right (orders of magnitude)?

  [1]: https://community.blynk.cc/t/esp8266-gpio-pins-info-restrictions-and-features/22872

title: max wattage LED for esp32

Answers: 2

body:
No. You're way off.

If the output can provide 12mA at 3.3V that equates to (P=VI) 39.6mW.  Boosting the voltages does not increase the power. Assuming a 100% efficient boost circuit (which does not exist) you would just be boosting to 12V at 39.6mW - which means (I=P/V) 3.3mA.

You can't magic more power out of thin air - if you could we'd all have "free energy" devices powering everything. Instead we have power supplies or batteries.

And that is what you will need. A source for that extra power to come from.

body: Technically the maximum power is unlimited however it depends on the driving circuit. With a simple MOSFET a few hundred watts is very feasible however the leds need to be in a series parallel configuration to keep the current reasonable. If you use the higher wattage LEDs you also have to supply a heat sink for them.  As you get further into electronics and the associated circuits this will become more apparent. Another way to look at it is a simple spark can burn down a forest if the conditions are correct.


body:
I wrote a simple multiplication function for matrices. Originally my matrices are stored in a single array in format (row, column):

(row0, col0), (row0, col1), (row0, colN), (row1, col0), ... (rowN, col0).

so a 2x2 identity matrix would look like
```
float eye[4] = {1, 0, 0, 1};
```

In the actual function I put the 2 array matrices being multiplied into 2d arrays (easy human readable) and then do the multiplication to get the new matrix output. Then convert back to single array. I am only dealing with 3x3, 3x1, and 1x3 matrices. So my code is not be 100% compatible with every matrix possibility. I have global arrays temp3 for my 3x1 and 1x3 matrices, and temp3x3 to hold 3x3 matrices. I use a global bool squared to determine which one the new output will go to.

I get that my code is not perfect, but my question is, why do I get overflow for simple operations? My code is as follows:

```
#include <math.h>
#include <WString.h>

#define FLOAT sizeof(float)
void multiplyMatrixAxB(const uint8_t rows1, const uint8_t cols1, const uint8_t size1, float matrix1[], const uint8_t rows2, const uint8_t cols2, const uint8_t size2, float matrix2[]);

float K[3]; // 3x1
float dgdn[3]; // 1x3

bool squared = false;
// Temp Variable to hold matrixes
float temp3x3[9];
float temp3[3];

void setup()
{
  Serial.begin(115200);
  Serial.println(F("Starting Matrix Test Program\n"));

  uint8_t i;
  K[0] = 1.0;
  K[1] = 2.0;
  K[2] = 3.0;

  dgdn[0] = 0.0;
  dgdn[1] = 0.0;
  dgdn[2] = 1.0;

  Serial.println(F("Matrix K setup as:"));
  for(i = 0; i < sizeof(K)/FLOAT; i++)
  {
    Serial.print(K[i]);
    Serial.print(F("\n"));
  }

  Serial.println(F("Matrix dgdn setup as:"));
  for(i = 0; i < sizeof(dgdn)/FLOAT; i++)
  {
    Serial.print(dgdn[i]);
    Serial.print(F("\t"));
  }
}

void loop()
{
  squared = true;
  Serial.println(F("\n\nA 3x1 times a 1x3 should give 3x3"));
  multiplyMatrixAxB(3,1, sizeof(K)/FLOAT, K, 1, 3, sizeof(dgdn)/FLOAT, dgdn);
  for(i = 0; i < 9; i++)
  {
    Serial.print(*(temp3x3 + i), 6);
    if(!((i+1)%3))
    {
      Serial.println();
    }
    else
    {
      Serial.print(F("\t"));
    }
  }

  Serial.print(F("\n\n"));
  Serial.println(F("End of Test"));
  while(1){delay(1000);}
}

void multiplyMatrixAxB(const uint8_t rows1, const uint8_t cols1, const uint8_t size1, float matrix1[], const uint8_t rows2, const uint8_t cols2, const uint8_t size2, float matrix2[])
{
  if(cols1 != rows2)
  {
    Serial.println(F("Multiplying Invalid Matrixes. Check ColsA and RowsB"));
    while(1){delay(1000);}
  }

  if(size1 != rows1*cols1)
  {
    Serial.println(F("rows and columns do not match size of matrix A"));
    while(1){delay(1000);}
  }

  if(size2 != rows2*cols2)
  {
    Serial.println(F("rows and columns do not match size of matrix B"));
    while(1){delay(1000);}
  }

  uint8_t row, column, k, i;
  double mat1[rows1][cols1];
  double mat2[rows2][cols2];
  double newMat[rows1][cols2];

  // place matrix1 into 2d array
  row = 0;
  for(row = 0; row < rows1; row++)
  {
    column = 0;
    for(column = 0; column < cols1; column++)
    {
      mat1[row][column] = matrix1[row*cols1 + column];
    }
  }

  // place matrix2 into 2d array
  row = 0;
  for(row = 0; row < rows2; row++)
  {
    column = 0;
    for(column = 0; column < cols2; column++)
    {
      mat2[row][column] = matrix2[row*cols2 + column];
    }
  }

  // get new array with multiplied values
  row = 0;
  for(row = 0; row < rows1; row++)
  {
    column = 0;
    for(column = 0; column < cols2; column++)
    {
      k = 0;
      for(k = 0; k < cols1; k++)
      {
        newMat[row][column] += mat1[row][k]*mat2[k][column];
      }
    }
  }

  row = 0;
  i = 0;
  // Place new matrix into single array format
  for(row = 0; row < rows1; row++)
  {
    column = 0;
    for(column = 0; column < cols2; column++)
    {
      if(squared)
      {
        temp3x3[i] = newMat[row][column];
      }
      else
      {
        temp3[i] = newMat[row][column];
      }
      i++;
    }
  }
}
```

Hopefully that covered everything. I have more code, but it is all mostly commented out. At worst I missed a variable declaration here, but I will mention that in the IDE it compiles fine and runs. My output looks like this:

```
Starting Matrix Test Program

Matrix K setup as:
1.00
2.00
3.00
Matrix dgdn setup as:
0.00 0.00 1.00

A 3x1 times a 1x3 should give 3x3
0.000000 0.000000 1.000000
ovf 0.000000 2.000000
0.000000 0.000000 3.000000

End of Test
```

Where does this ovf come from? I have tried printing out in the multiplication statement in the for loop the index of mat1 x the index of mat2 = "result". This will actually print out exactly what I expect to see and then my output in the main loop will be ok. What is going on? I tried some delays to see if that was the issue between calculations as well. No good.

what I mean is placing in the inner most for loop (k loop):

'''
Serial.print(mat1[row][k]); Serial.print(" x "); Serial.print(mat2[k][column]); Serial.print(" + ");
'''
 And then just outside it,

'''
Serial.print(" = "); Serial.println(newMat[row][column]);
'''

I will not get any overflow in this scenario.

title: Float mulitplication Returns ovf or -0.0 for small whole float numbers

Answers: 1

body:
`newMat` is first declared:

```c++
double newMat[rows1][cols2];
```

and then updated:

```c++
newMat[row][column] += mat1[row][k]*mat2[k][column];
```

However, it has never been initialized. Non-static local variables are
not implicitly initialized: `newMat` starts its life containing whatever
garbage was in RAM at this location. You should initialize every
element to zero before you start accumulating the sum of products.

------------------------------------------------------------------------

**Edit**: Regarding the initialization as

```c++
float newMat[rows1][cols2] = {{0},{0}};
```

I would expect that to initialize the whole matrix to all zeros, but my
experiment shows that it only initializes the first element of the first
two rows, and the entire third row. Initializing an array with a list
shorter than that array is supposed to initialize the other elements to
zero. However, this appears to not work recursively with the inner
arrays. I do not know whether it is a compiler bug or normal behavior.
The following, however, does work:

```c++
float newMat[rows1][cols2] = {};  // zero-initialize
```

Regarding the copies within `multiplyMatrixAxB()`, you can completely
avoid them by using pointers. For example,

```c++
double (*mat1)[cols1];
```

declares `mat1` as a pointer to arrays of length `cols1` of `double`.
This would be equivalent to `double mat1[][cols1]` within a parameter
list, and is compatible with a 2D array of width `cols1` and unspecified
height. If you make this point to `matrix1`:

```c++
double (*mat1)[cols1] = (double (*)[cols1]) matrix1;
```

you can then use `mat1` as a different _view_ of `matrix1`: you view it
as an array of arrays of numbers, rather than a 1D array of numbers. You
can then use `mat1` as you do now, and it will work by accessing the
original data, without needing an extra copy.

Using this trick, the body of `multiplyMatrixAxB()` can be reduced to
the following (skipping error checking):

```c++
// View the vectors as matrices.
double (*mat1)[cols1] = (double (*)[cols1]) matrix1;
double (*mat2)[cols2] = (double (*)[cols2]) matrix2;;
double (*newMat)[cols2];
if (squared)
  newMat = (double (*)[cols2]) temp3x3;
else
  newMat = (double (*)[cols2]) temp3;

// Matrix multiplication.
for (int i = 0; i < rows1; i++)
  for (int j = 0; j < cols2; j++) {
    newMat[i][j] = 0;
    for (int k = 0; k < cols1; k++)
      newMat[i][j] += mat1[i][k] * mat2[k][j];
  }
```


body:
Below is the code that I have done on ```Lolin Wemos D1 R2 and mini``` it works fine but it throws exceptions every time, I tried understanding my problem by reading this: https://arduino.stackexchange.com/q/67442/11957 but couldn't!

```#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <SoftwareSerial.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
//#include "FS.h"

//---------firebase creds---------
#define FIREBASE_HOST "homeauto-3130d.firebaseio.com"
#define FIREBASE_AUTH ""

//--------wifi creds--------
#define WIFI_SSID "********"
#define WIFI_PASSWORD "***************"

SoftwareSerial esp(D2,D8); //rx tx

//--------data from arduino to esp-------
float temp_fb;
float gas_fb;
float hum_fb;

//-------checking time elapsed b4 printing ------
unsigned long last_chk = 0 ;
unsigned long time_elapsed;

//-----ctrlling sending rate to firebase----
bool t_ar , h_ar , g_ar = false ; //chk arrival of all data b4 sending
char r;
int found = 1;

//-----setting feeder pos from firebase
String feed_load = "0" ;

//-----getting time stamp from ntp server
char time_stamp[12];
int len;
const long utcOffsetInSeconds = 19800; //gmt+5hrs:30mins => 19800 sec
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

//------------------------schedule vars----------------------------

void setup()
{
  Serial.begin(9600);
  esp.begin(4800);

  SPIFFS.begin();

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("connected: ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  if(Firebase.failed())
     {
      Serial.print("failed...");
      Serial.println(Firebase.error());
     }
  timeClient.begin();
}

void loop()
{
  time_elapsed = millis();
  if(time_elapsed - last_chk > 5000)
  {
    Serial.println("checking for data from arduino...");

    last_chk = time_elapsed;
    time_elapsed = millis();
  }
   while(esp.available()>0)
  {

     if(found == 1)
     {
      Serial.println("................found data...............") ;
      timeClient.update();
      len = sprintf(time_stamp , "%d:%d:%d" , timeClient.getHours() , timeClient.getMinutes() , timeClient.getSeconds() ) ;
      Serial.print("Time stamp:\t");
      Serial.println(time_stamp);
      found = 0;
     }
     r = esp.read();

     switch(r)
     {

      case 't':
      {
        Serial.print("got t...") ;
        t_ar = true;
        temp_fb = esp.parseFloat();
        Serial.println(temp_fb);
        break ;
      }

      case 'g':
      {
          Serial.print("got g...") ;
          g_ar = true;
          gas_fb = esp.parseFloat();
          Serial.println(gas_fb);
          break ;
      }

      case 'h':
      {
        Serial.print("got h...") ;
        h_ar = true;
        hum_fb = esp.parseFloat();
        Serial.println(hum_fb);
        break ;
      }
      default: break;

     }

  }

  found = 1 ;

  if(g_ar and t_ar and h_ar)
  {
     //writing to firebase
     Serial.println("got the set.. to fb now");
     Firebase.pushString("Time stamp" , time_stamp);
     Firebase.setFloat("GAS SENSORinst" ,gas_fb);
     Firebase.setFloat("HUMIDITY SENSORinst" ,hum_fb);
     Firebase.setFloat("TEMP SENSORinst" ,temp_fb);
     Firebase.pushFloat("GAS SENSOR" ,gas_fb);
     Firebase.pushFloat("HUMIDITY SENSOR" ,hum_fb);
     Firebase.pushFloat("TEMP SENSOR" ,temp_fb);

  }

  t_ar , h_ar , g_ar = false ;

  feed_load = Firebase.getString("feeder");

  if (feed_load != "0")
   {
    Serial.println("\trecd req to feed");
      esp.print('w');
      esp.print(feed_load);
      feed_load = "0";
      Serial.println("\tsetting feeder to close in firebase");
      Firebase.setString("feeder" , "0");

   }

}
```
Here's the error log:(I've only pasted the exceptions, they just repeat over and over again)
```
Exception (28):
epc1=0x4020cda0 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000034 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffc50 end: 3fffffc0 offset: 01a0
3ffffdf0:  0000000b 3ffeeb28 3fff0e18 40206e5c
3ffffe00:  3ffe8857 000001bb 3fff0e18 40207d34
3ffffe10:  3ffe890b 0000003b 3fff0e18 4020817c
3ffffe20:  0000003b 3fffff00 3ffeec64 40203eb0
3ffffe30:  3ffffe78 0000003b 3ffffe60 40209018
3ffffe40:  3ffeeb24 3ffffe60 3ffe890b 3ffffee0
3ffffe50:  3ffeeb24 3ffffea4 3fff0e14 402057ab
3ffffe60:  3fff10bc 003b003f 00fffea4 3fff0f4c
3ffffe70:  000c000f 00ffff5c 3fff0ef4 001d001f
3ffffe80:  00fe876b 3ffeeb20 3fffff62 3ffffee0
3ffffe90:  3ffeeb24 3ffe8888 3fff0ca4 402034ec
3ffffea0:  3ffe876b 3fff0f38 3fff0ec4 3ffeea78
3ffffeb0:  3fffff5c 3ffffee0 3ffe876b 40203e74
3ffffec0:  3ffffee8 3fffff00 3fffff00 3ffeea78
3ffffed0:  3fffff5c 3fff0ca4 3ffeeb20 40204765
3ffffee0:  3ffeeb60 3fff0ed0 05e353f7 40205fef
3ffffef0:  3ffeeb20 3ffeeb20 3fffff50 402047a6
3fffff00:  00220000 3fff0174 3ffeea78 402068ca
3fffff10:  00000006 00000002 40205fbc 402067ac
3fffff20:  00c3c10e 00000006 3fffff5c 40209018
3fffff30:  3ffeeb20 3fffff5c 3ffe8804 4020904e
3fffff40:  3ffeeb20 3ffe851c 3ffeea61 40201438
3fffff50:  3ffe0000 3fffff80 80feeb84 64656566
3fffff60:  00007265 86595cc2 3ffeeb00 4020113a
3fffff70:  00000000 00000000 feefeffe feefeffe
3fffff80:  00000000 00000000 00000001 40100580
3fffff90:  3fffdad0 00000000 3ffeec74 3ffeecb4
3fffffa0:  3fffdad0 00000000 3ffeec74 40209f08
3fffffb0:  feefeffe feefeffe 3ffe8584 401012d1
<<<stack<<<

Exception (9):
epc1=0x4020cda0 epc2=0x00000000 epc3=0x00000000 excvaddr=0x65656663 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffc50 end: 3fffffc0 offset: 01a0
3ffffdf0:  0000000b 3ffeeb28 3fff0e18 40206e5c
3ffffe00:  3ffe8857 000001bb 3fff0e18 40207d34
3ffffe10:  3ffe890b 0000003b 3fff0e18 4020817c
3ffffe20:  0000003b 3fffff00 3ffeec64 40203eb0
3ffffe30:  3ffffe78 0000003b 3ffffe60 40209018
3ffffe40:  3ffeeb24 3ffffe60 3ffe890b 3ffffee0
3ffffe50:  3ffeeb24 3ffffea4 3fff0e14 402057ab
3ffffe60:  3fff0f1c 003b003f 00fffea4 3fff0f04
3ffffe70:  000c000f 00ffff5c 3fff0eac 001d001f
3ffffe80:  00fe876b 3ffeeb20 3fffff62 3ffffee0
3ffffe90:  3ffeeb24 3ffe8888 3fff0c7c 402034ec
3ffffea0:  3ffe876b 3fff0ef0 3fff0cbc 3ffeea78
3ffffeb0:  3fffff5c 3ffffee0 3ffe876b 40203e74
3ffffec0:  3ffffee8 3fffff00 3fffff00 3ffeea78
3ffffed0:  3fffff5c 3fff0c7c 3ffeeb20 40204765
3ffffee0:  3ffeeb60 3fff0cc8 a7ae147a 40205fef
3ffffef0:  3ffeeb20 3ffeeb20 3fffff50 402047a6
3fffff00:  00220000 3fff0174 3ffeea78 402068ca
3fffff10:  00000006 00000002 40205fbc 402067ac
3fffff20:  00c15609 00000006 3fffff5c 40209018
3fffff30:  3ffeeb20 3fffff5c 3ffe8804 4020904e
3fffff40:  3ffeeb20 3ffe851c 3ffeea61 40201438
3fffff50:  3ffe0000 3fffff80 80feeb84 64656566
3fffff60:  00007265 86461819 3ffeeb00 4020113a
3fffff70:  00000000 00000000 feefeffe feefeffe
3fffff80:  00000000 00000000 00000001 40100580
3fffff90:  3fffdad0 00000000 3ffeec74 3ffeecb4
3fffffa0:  3fffdad0 00000000 3ffeec74 40209f08
3fffffb0:  feefeffe feefeffe 3ffe8584 401012d1
<<<stack<<<
```
**edit1** decoding error stack, this is what i get...

```
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads
PC: 0x402141d4: HTTPClient::connected() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 472
EXCVADDR: 0x00000040

Decoding stack results
0x40206e64: HTTPClient::disconnect(bool) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 435
0x40207d3c: HTTPClient::end() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x40208184: HTTPClient::begin(String, unsigned short, String, String) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 379
0x40203eb8: std::string::_Rep::_M_destroy(std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 452
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x402057b3: FirebaseHttpClientEsp8266::begin(std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient_Esp8266.cpp line 51
0x402034f4: FirebaseRequest::sendRequest(std::string const&, std::string const&, char*, std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\Firebase.cpp line 73
0x40203e7c: std::basic_string  , std::allocator  >::basic_string(char const*, std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 218
0x4020476d: FirebaseArduino::getRequest(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 101
0x40205ff7: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1954
0x402047ae: FirebaseArduino::getString(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 132
0x402068d2: SoftwareSerial::rxBits() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 394
0x40205fc4: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1931
0x402067b4: std::_Function_handler ::_M_invoke(const std::_Any_data &, unsigned int &&) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 393
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x4020919a: String::String(char const*) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 36
0x40201440: loop() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 151
0x40201142: setup() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 72
0x40100580: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020a054: loop_wrapper() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

Exception 9: LoadStoreAlignmentCause: Load or store to an unaligned address
PC: 0x402141d4: HTTPClient::connected() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 472
EXCVADDR: 0x65656663

Decoding stack results
0x40206e64: HTTPClient::disconnect(bool) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 435
0x40207d3c: HTTPClient::end() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x40208184: HTTPClient::begin(String, unsigned short, String, String) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 379
0x40203eb8: std::string::_Rep::_M_destroy(std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 452
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x402057b3: FirebaseHttpClientEsp8266::begin(std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient_Esp8266.cpp line 51
0x402034f4: FirebaseRequest::sendRequest(std::string const&, std::string const&, char*, std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\Firebase.cpp line 73
0x40203e7c: std::basic_string  , std::allocator  >::basic_string(char const*, std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 218
0x4020476d: FirebaseArduino::getRequest(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 101
0x40205ff7: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1954
0x402047ae: FirebaseArduino::getString(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 132
0x402068d2: SoftwareSerial::rxBits() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 394
0x40205fc4: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1931
0x402067b4: std::_Function_handler ::_M_invoke(const std::_Any_data &, unsigned int &&) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 393
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x4020919a: String::String(char const*) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 36
0x40201440: loop() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 151
0x40201142: setup() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 72
0x40100580: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020a054: loop_wrapper() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

```
Read from here: https://arduino.stackexchange.com/questions/67544/nodemcu-exception-28-intermitent-problem that ```exception 28``` maybe because of some functions not returning values and I can take that because, i just connected the ESP without arduino just to check what happens, but during other times I only recall ```exception 9``` being repeated

The var ```String feed_load``` is read from firebase , which gets the value from a app made from MIT app inventor , I store 0 or value of load in it (a float) ; but app inventor stores it as a string, so i am reading it as a string , i tried putting ```char feed_load[5]``` but it gave a error saying string cannot be stored in char[5]

kindly help in fixing this problem , there's some more code to be written for scheduling activities , so i don't want the board to be constantly resetting or restarting

title: Programming ESP8266 to avoid random exceptions?

Answers: 1

body:
I don't know if this is the actual fix for the problem ,but instead of FirebaseArduino library i used FirebaseESP8266 library and the random exceptions did not come up (yet)

FirebaseESP8266 [https://github.com/mobizt/Firebase-ESP8266/][1]

P.S. sorry for not reverting back quicker !!

  [1]: https://github.com/mobizt/Firebase-ESP8266/


body:
```c++
float get_volt() {
  rawVolt = analogRead(voltageSensor);
  vOUT = (rawVolt * 4.6) / 1024.0;
  vIN = vOUT / (R2/(R1+R2));
  //if(vIN>12.0){vIN=12;}
  //if(vIN<11.12){vIN=11.12;}
  //return (vIN - 10.18) * (100 - 0) / (12.0 - 10.18) + 0;
  return vIN;
}
```

I am using a voltage sensor module which has a voltage divider with R1=30K Ohms and R2=7.5K Ohms and can measure up to 0-25V by using 10-bit Analog pin of arduino. the battery voltage comes as 11.4 volts when measured with a multimeter but I am getting an inaccurate reading from arduino ranging from 10.8 to 11.4. the Arduino voltage reference is stable at 4.6 V. Please help me to fix this, you can see the voltage reading in the image
PS: the battery and arduino are connected to the same ground.

[![enter image description here][1]][1]

edit1: adding 0.1uf capacitor helped to improve from this
[![enter image description here][2]][2]

to this!
[![enter image description here][3]][3]

the data is taken for over a period of 1 hr at every 5 seconds, its a 12V 4000 mAh battery

  [1]: https://i.stack.imgur.com/jLnxl.png
  [2]: https://i.stack.imgur.com/0CrLE.png
  [3]: https://i.stack.imgur.com/ZtpHs.png

title: Inaccurate and non-precise voltage reading from Arduino Analog pin

Answers: 1

body: This should be a lot of fun but you might consider doing some research on analog circuits and A/D circuits. You have way too many digits to the right of the decimal, the accuracy is not there. The best you can get is 0.0044 volts per count with a 4.6v reference. What are you using to make your measurements, you need at 5 1/2 digit meter to have the decade better accuracy then what you are calibrating to. Your reference you state is 4.6 volts, something is not correct is should be 5.000V. You know any load placed on the on board regulator will have an effect on your A/D readings. The tolerance of the resistors you are using will have an impact on your reading. They generate noise that could be affecting your readings. 100nF should be enough capacitance,this will lower the input impedance. Increasing capacitance beyond this will slow the settling time of the circuit. If you are powering this from a computer USB expect noise from that power source, That would also explain the lower reference voltage on the A/D. With what you indicate you have, you are actually doing very well.