text:
Streaming integer data from Arduino to Java, integer greater than 0xFF
I need to send how many milliseconds elapsed since the beginning of the time the arduino runs to java using Serial.write(). However, the largest integer that I can throw in there is 255, naturally since the largest 1 byte value we can send is 0xFF.
But if we have an integer like 6000 miliseconds that I want to send into java, how can I do this? I was initially thinking of just checking if the number is greater than 255 then bit shift it by 4 to the left then doing number<<4 & 0xFF00 and also writing (number<<4)>>8 &0xFF
But

that doesn't work for numbers really large and
I believe when I stream these int values into Java they get read as characters...

how do I fix this?
EDIT
I've created a second version as the following
void sendData(int a ){
  while(a>0){
    Serial.write(a&255);
    a = a>>8;
  }
}

on the java side I have to somehow multiply the correct x for 16^(x) to the value that we receive since everything is received backwards I'm not sure if this is the best way to go since we don't necessarily know how many bytes that we'll receive

I'm assuming you will be using the Arduino millis() function for keeping time. The output of the millis() function in the Arduino environment is a 32-bit unsigned integer*.
A 32-bit integer can be split into 4 x 8-bit bytes. To keep things simple you could program the Java receiving side to always expect 4 bytes (or whatever amount you need, see *). Assuming 32 bits is enough, you could use the following:
void sendData (uint32_t uptime) {
    int i;
    for (i = 0; i < 4; i++) {
        Serial.write (uptime & 255);
        uptime = uptime >> 8;
    }
}

On the Java side, you would receive the lowest order byte first, and you could reconstruct the 32-bit value by taking the first received 8-bit value, adding the second value shifted left by 8 bits (=multiplied by 256), adding the third value shifted left by 16 bits (=multiplied by 65536) and adding the fourth value shifted left by 24 bits (=multiplied by 16777216). Java is not my strong point so I will leave that to you.
BTW, is there a particular reason you have to use Serial.write()? It would be much easier to just write the value as a string with Serial.println().
*After 2^32 milliseconds (a little under 50 days of uptime) the 32-bit counter that feeds the millis() function will wrap around to 0. You could keep the amount of times that the timer has overflowed in a separate (integer) variable and make that (i.e. bytes 5 and onward) part of your output.


text:
How to get an angle from two ultrasonic sensors
I am building a chair for a special 4 year-old with cerebral palsy, I thought it would be a good idea to add two distance sensors on each arm of the chair to measure the angle at which he presses buttons(a gaming chair).  Normally I would figure this out on my own but I don't have much time to finish so I thought i'd ask the experts.  What's the best way to use to ultrasonic sensors data to produce an angle?

angle at which he presses buttons ... please explain what this means

ultrasonic sensors measure distance ... the angle would have to be converted to distance mechanically

this question is not really about an arduino ... it is about an unspecified electro-mechanical device

Your question is unclear. You say you want "...to measure the angle at which he presses buttons". I don't know what that means.
If you're using ultrasonic sensors those measure distance. buttons tend to be fixed in place. Maybe you're  talking about having a joystick on the gaming chair? Two-axis joysticks should let you input an X and a y value.
If you're trying to calculate the angle between a pair of ultrasonic sensors and something that is in their "line of sight" (line of sound?) then you'd use trig.
You would have your sensors at a known distance from each other. You'd measure the distance to each sensor, form a triangle out of all 3 distances, and use the law of cosines to calculate the angles.
The formulas from that page are:
cos(C) =  a² + b² − c²/2ab
cos(A) =  b² + c² − a²/2bc
cos(B) =  c² + a² − b²/2ca
(Where upper case letters denote the angles of the triangle at a vertex, and lower-case letters denote the legs of the triangle. See the illustration on that page.)
 SensorA
    \
     \      SensorB
      \       /
       \     /
        \   /
         \ /
          V
        object

(one leg would be the SensorA-to-SensorB distance. Another leg would be the SensorA-to-object distance, and the 3rd leg would be the SensorB-to-object distance.)
However, all of that will only work if the object you are detecting is in the range of angles in which your sensors are able to detect objects, and in the range of distances they provide accurate readings.
Edit:
When I copied the formulas from the source site, the superscripts were lost. I've edited them back so the formulas are more readable.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Clock Problem when Migrating from Arduino IDE Mighty Core to Atmel Studio
I've been programming an ATMega1284 using the Arduino IDE with the MightyCore package.
I'm now trying to migrate to Atmel Studio.
Atmel Studio (7.0) will now compile the sketch and all required libraries (that took some time) and upload the output via USBAsp to the ATMega (Essentially just calling avrdude). However...
The uploaded sketch is running differently. It seems slower. For example, the Tone() function seems to output a lower pitch. My best guess is that Atmel Studio has the xtal/clock setting wrong, but I can't find where to inspect/change it?
I'm using a 12mhz external xtal, and can only communicate with the chip via UART. If I upload the sketch from Arduino IDE then it reverts back to normal.

Do you have correct F_CPU in project?

Thanks KIIV, where would I find that? (Apologies, new to Atmel Studio)

First result of Google showed where to find it. That fixed the problem, Thank you @KIIV

For anybody else who comes across this: In the Solution Explorer, Click on ArduinoCore, click on the spanner icon, go to Toolchain, and for both C and C++ compilers, go to Symbols, and have a look at F_CPU. Repeat the above for the sketch.

Or Alt-F7 (Project - 'projectname' properties), click on Toolchain, then Symbols under AVR/GNU C compiler. Also don't forget to set the correct fuses, under Device Programming (Ctrl-Shift-P)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Read encoder output by using an optocoupler
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:

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.

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.

Possible, yes. But you may get it easier. For what do you need that 5V signal from channel A?

Can't you just split the channelA encoder output, to go to both the Arduino and your other mystery device? Please tell us more about what it is you are trying to do, and what the actual problem is.

Thank you for all your assistance! The mistery 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?

A few things, people don't usually design circuits here, this site is designed to build a database of clear questions and concise answers.  It needs to be searchable so questions are encouraged to be specific.  For instance it would be better if you spread these questions out in individual posts. In general, if other people can not use your question and any ensuing answer, it is not a good fit for the many stackexchange sites.

That said, I would clean your post of unnecessary schematics leaving only the last one.  We can work off that one.  But keep in mind my answers are going to be general to keep within the guide lines of stackexchange sites and may not work for your particular case.  In other words by no means should you assume we will create a working circuit.  The intent is to suggest some methods used my some to help design a circuit.

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.  Or may preventative as in ground loop mitigation for MIDI connections.  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 and the fan out of the signal is larger then the existing load and the new load combined and the new load is 5 volt tolerant 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.

The fan out is very limited, I just need to catch the +5V signal to trigger some events on my video camera system so I do not have to drive high loads. The video camera system is 5V tolerant.

Thank you for making your question more complete.  It is still a mystery what is inside the video equipment.  It may be a high impedance device like a MOSFET with a load resistor to ground to mitigate noise problems.  But that is just a guess.  Also, your video equipment may be only inches away.  Or may be across the lab.  Logic level signals can be adversely affected by long wires.  This is turning into a complex problem.

I can't check what's inside the video system unfortunately. For sure, the maximum distance between the encoder and the video system is 100 cm. In case it has a high impedance, what would be a possible solution? I think we have to check the worst case..

Hi @MarcusBarnet, we are getting into a situation where we can not assure success. It is at these point I start to consider what risks I am willing to take verses the effort to discover everything about everything involved.  For example I would ask myself how much would a new encoder cost if the current one failed. Keep in mind you are asking this question in the Arduino forum where parts very rarely cost more then $50. That said, 1 meter isn't that long in a quiet environment.  Did have a prof w/a pulsing ruby laser in a lab once. That didn't go well. Hi impedance isn't a bad thing ...

... unless there's a lot of noise. Guessing, what I would do is to make sure there are no ground loops.  That can blow out connected devices quickly.  Make sure the input impedance to ground is high for both loads.  Scope the output of the encoder w/no load.  Scope it w/the motor controller only.  Scope it w/the video equipment only.  If both look good then connect them both and verify the signal from the encoder still looks good.  If you are iffy about doing this, then I would suggest you find a tech or eng that is more familiar w/your setup who can do this for you.

Thank you for your support! Can't I just use an opto coupler to pick up the signal from the encoder output? I'm asking this because I think this should be very safe. My only doubt is if the optocoupler is faster enough to catch the encoder output..

It is likely the optical coupler will be fast enough.  The challenge is using an optical coupler.  You likely need a series resistance between the output of the encoder and the LED inside the optical coupler.  Then, you likely need to arrange the output of the optical coupler similar to an open collector output and pull the output high through another resistor. Possibly something like this.

I already have several 6N136 optocouplers (https://www.enovatera.com/5471-thickbox_default/enovatera-6n136-opto-isolator-with-transistor-output-discount-price-buy-6n136.jpg) in my laboratory, can I use one of them? I thought to use it in this way: http://www.robo-dyne.com/pics/circuit-encoder.png can it be correct?

As this isn't a forum we'll eventually pass a threshold and the web site will ask us to move this discussion to a different page.  Looking at the optical coupler specifications here I see where pin 3 is connected to ground. It is more likely the motor controller should be connected to the encoder output instead.

Thank you @st2000 for your support! as you suggested, I swapped the motor controller position with the video system output and I changed the voltage source for the motor controller to +5VDC instead of +12VDC (http://www.robo-dyne.com/pics/circuit-encoder1.png). Do you think the 10K resistor and the 320R are correct? I used this same circuit to drive a MOSFET and it worked fine.

I wasn't clear.  And sorry for all the qualifiers but with out knowledge of all connected devices this is just guess work.  It may be the best approach is to split the signal from the encoder to both the motor driver and video equipment. in parallel not in series.  R15: Look at the 6N136 spec for normal input voltage & current and calculate R.   270 ohms looks a bit high.  R14: 10K ohms may work but only if the input of the video equipment is many times that resistance.  No where in  your descriptions do you mention a 12 volt signal.  So likely you shouldn't have one in your schematic.

Thank you again for your support! The 12V was a type related to my old design, the main voltage is 5V. If I split the signal to both motor driver and video system I do not have to use the optocoupler, is it correct? I was thinking to change the previous circuit by placing both devices in parallel, but using the optocoupler for the video output. Do you think it can make sense? http://www.robo-dyne.com/pics/circuit-encoder2.png (I'll check the datasheet for the correct value of 270R resistor)

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.


text:
Can't understand this codes process
    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

Sorry, I don't want to download some random file from a random site. Please include all relevant code into your question. Where did you get that code? I stumble across the while loop. I currently don't see how this would work, as `p = strchr(p, ' ') will set the pointer p to the next occurrence of a space character. Then the code tries to convert that space character as a hexadecimal string to an integer. Are you sure, that is code actually works?

Yes im sure it works :)

It's easier to follow if you indent it properly. I'll do that, and add comments as I go:
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.

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


text:
Read Internal Registers of RS485
I am trying to interface sele EM2M, I am using Arduino Mega with RS 485 module. I want to read the internal registers I am using ModbusMaster library. 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
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.

I can't open the datasheet.

Ahh I am also having problems with the same sorry I will ask the manufacturer and then upload the datasheet

@Juraj now you can download the datasheet

it is an image, but looking at it I didn't see "internal registers"

https://gofile.io/d/qeQd1B link for datasheet I have added the same on selec EM2M
Yes internal registers are not present I forgot where I saw internal register but I guess internal and Input registers are one and the same

maybe read about Modbus on Wikipedia

@Juraj thank you for the time the issue is been resolved

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

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.


text:
Signal names HiFi
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

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.

do you have a link?

No  but you can google it


text:
max wattage LED for esp32
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)
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)?

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.

That cleared it up for me, thx. The only way to get more light out of an LED with the same power is to get a more energy sufficient LED in the first place (or get more power)

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.

I think you're answering to "practically speaking and ballpark, the maximum wattage of LED you can drive" and are missing the "with an ESP32". If I understand your answer right this is not very relevant for this question, it's specific for ESP32 (or arduino's). Nevertheless, interesting!

Depends if the ESP32 is the driver or controlling device, that was not clear to me. Another part of the equation is what is the loading on the other pins and how closer is it to the chip max current rating. There is a lot of information missing.

I updated the question with the missing information, please mention more, then I improve the question

As I understand it you have about 3.5V from the ESP32 and 10mA (I would stay under 10) you then have to select a color, for example they have a forward voltage drop,  Red 1.6 - 2.1  Violet 2.8 - 4.0; Depending on your color the answer will change. At the high end Violet will draw nothing as your voltage is below threshold.  Assuming a Red at 1.6Vf, a 190 Ohm Resistor you will draw 10mA. This gives you answer at 0.01448 watts. Try this calculator: https://ohmslawcalculator.com/led-resistor-calculator


text:
Float mulitplication Returns ovf or -0.0 for small whole float numbers
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.

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

What, precisely, at the low-level of the MCU, is that line really doing?

This covers the rowxcolumn multiplication for each new element index. The rowXcolumn needs added up to get the correct new index value for the new 3x3 matrix. First for loop iterates the number of rows that will go in the new matrix (which is rows1) , second for loop iterates the number of columns for the new matrix (which is cols2), and the last loop is what I just covered. The addition of the row by column multiplication. to go into the new indexed element.

Think of it as the summed total for the new index. I just skipped the extra variable step.

What are you asking the value to?

newMat is first declared:
double newMat[rows1][cols2];

and then updated:
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
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:
float newMat[rows1][cols2] = {};  // zero-initialize

Regarding the copies within multiplyMatrixAxB(), you can completely
avoid them by using pointers. For example,
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:
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):
// 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];
  }

Absolutely it. I changed the newMat declaration to "float newMat[rows1][cols2] = {{0},{0}};". No issues now. Sometimes forget the little things.

I still sometimes get the -0.0. Any idea where that comes from? I should just have 0 * 0 or 0* a number in the places I'm getting it. Should just be zero. The ovf stopped though.

I placed "newMat[row][column] = 0;" above where k = 0 is. That seemed to fix it. I saw that if you just initialize one element of the multi-dimensional array, the rest that are not given a value are assigned to zero. So I did not think I needed to explicitly assign a value to each individual index.


text:
Programming ESP8266 to avoid random exceptions?
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: NodeMCU 1.0 - Exception 9 `Fatal exception 9(LoadStoreAlignmentCause):` but couldn't!
#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: 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

decode the stack

Are you sure your code can compile properly? if(g_ar and t_ar and h_ar) is not even a valid c++ syntax.

@hcheung code compiles and has been working for days :)

@Juraj i've added the decoded error stack now !

Do you get compiler warnings?

@SimSon No warnings , only thing i noticed was , that there were multiple files for ESPin Arduino and ArduinoData files (i don't know how this one came into existence, but i didn't bother deleting it, as something else might crop up!!)

it is a known problem. use HttoClient as local variable

@Juraj you mean instead of Firebase.function() , i hv to use Firebase HttpClient and use HttpClient.function() or do i have to use a different library altogether?

Does this answer your question? ESP8266 always resetting after 65 second of running

@Juraj I have to try that library(ESP8266HTTPClient) , since the one i'm using(FirebaseArduino) is still using ArduinoJson 5.13.5 , I thought of using the library from here: https://github.com/mobizt/Firebase-ESP8266 , but generally the former looks like a good library to use for this kind of applications ! I'll see if either of these fixes the problem, thanks!

sorry, I was on a small display of a phone. the FirebaseArduino uses HttpClient. check if there is a fix for FirebaseArduino to workaround the problem

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/
P.S. sorry for not reverting back quicker !!


text:
Inaccurate and non-precise voltage reading from Arduino Analog pin
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.

edit1: adding 0.1uf capacitor helped to improve from this

to this!

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

Are you measuring also something else on ADC? Recommended maximum input impedance is 10K, and it looks like yours might be bit weak, so charging sampling capacitor from different levels (= previously measured value) may result in huge differences in measured values

nope, I am only measuring the voltage  on A1, the current is being measured using A2.  So it can be a problem with the uC?

Try adding capacitor between GND and A1 first (about 1uF should be fine).

There is only one ADC in the Arduino, which can be used for several pins. If you are also measuring current inbetween voltage measurements, @KIIV's comment applies; the pins used don't matter. You would have to reduce the voltage divider's impedance, give the ADC more cycles per sample, or measure the voltage twice and discard the first measurement.

what's the difference between inaccurate and non-precise?

Does the accuracy improve when you only measure voltage and not current?

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.

Are you saying resistors make noise? I.e packed carbon tubes?

Very definitely as do all other components.  At 10 digits to the right of the decimal point it can become a big problem. For more background try this link: https://www.allaboutcircuits.com/technical-articles/electrical-noise-what-causes-noise-in-electrical-circuits/  This is based on the numbers he printed out. In reality it should not be a problem until you get mayne 14 bits or more depending on the design.

Thanks a lot !! adding a 0.1uF capacitor did solve the problem but still there is a noise of 0.1 V, checking out if averaging the readings solves the problem, if you all have any other suggestions please do let me know!


text:
AT Commands ESP8266 Arduino IDE serial monitor not print any data from server. It say 408 request timeout
i am new in arduino and ESP8266 module. I am still learning about AT command. But i found this problem:
1.My website code (index.html)-http://nyalalampu.atwebpages.com:

<?php
        ECHO $_GET['subject'];
?>

2.My AT commands (In Arduino IDE Serial Monitor)
AT+CIPSTART="TCP","nyalalampu.atwebpages.com",80

CONNECT

OK
AT+CIPSEND=29

OK
>
Recv 29 bytes

SEND OK

+IPD,391:HTTP/1.1 408 Request Timeout
Date: Sat, 10 Oct 2020 17:00:24 GMT
Server: Apache
Content-Length: 221
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>408 Request Timeout</title>

Request Timeout

Server timeout waiting for the HTTP request from the client.

CLOSED

After > i put
GET /?subject=anis HTTP/1.0

My question is why it not print anis in Arduino IDE Serial Monitor? It just show 408 Request Timeout
I hope someone can tell me what's wrong with my code.TQ

you must end the GET request with \r\n. how do you send it?

Does this answer your question? ESP8266 ESP-01 not show data from server in Arduino IDE serial monitor

I just send like you say sir...but it send back Bad Request when i put \r\n like this GET /?subject=anis HTTP/1.0 \r\n

@Juraj I just send like you say sir...but it send back Bad Request when i put \r\n like this GET /?subject=anis HTTP/1.0 \r\n

@Juraj Yes...i have learn something new...tq sir...what i know is AT+CIPSEND value should same the count of character plus 2

/?subject=anis HTTP/1.0 \r\n the space before \r\n shouldn't be there

@Juraj still get Bad Request after i remove space

you have the GET line in the sketch or you try to send it from Serial Monitor?

@Juraj in Serial Monitor sir

then remove \r\n and after sending the GET line, try to press Enter immediately one more time. does the server accept insecure http? does it accept HTTP 1.0?

you need "host" header


text:
Error message - Need help
I found this Haptic Headband project on YouTube (link below) and I am trying to verify the code that was given in the instructions with the Arduino IDE. However, I keep getting the message below and am not too sure what I need to do to fix it. I'd appreciate any help I could get to solve this issue.
I have also attached a pdf of the instructions with the code to use for the headband.
PDF: https://cdn-learn.adafruit.com/downloads/pdf/haptic-headband.pdf?timestamp=1602887165
https://www.youtube.com/watch?v=xD7bfBx5D9M&ab_channel=AdafruitIndustries

libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::setRealtimeValue(unsigned char)'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::useERM()'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::useLRA()'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Uno.

you asked for help with nonexistent code

It would help if you could put the code inside the question. Did you install the DRV2605 library correctly?

“Multiple definition” means that you have something defined more than
once. According to the error message, some methods are defined both in
libraries\Adafruit_DRV2605_Library and in your sketch folder.
It looks to me like you are trying to use two copies of the
Adafruit_DRV2605 library. One of them is properly installed as a
library, and the other is within your sketch folder. You don't need two
copies. If the library is properly installed, there is no point in
copying its source files to your sketch folder. Get rid of that extra
copy and try recompiling.

Thank you for your help! I got it!


text:
Is 1MB flash enough for OTA upload in ESP-01?
I'am asking this question, because in my ESP-01 OTA upload always fail. In fact update won't even start. When update was triggered esp wifi led(build in blue) indicates "working" , but after cca one second esp reset itself. And The original program remains and starts again...

what Flash size did you select in Tools menu?

1MB(FS:none, OTA:~502KB).... according as I read in tutorial, that OTA has to be at least half of memory for propper running...

try to turn off firewall on PC

I tried, but with no effect...

Yes, 1MB is fine for OTA. There are, though, a few caveats when working with OTA that you must observe regardless of the flash size:

The maximum OTA program size is less than half the available flash size. Typically it is about 500kB. Two copies need to be stored in flash, plus the partition table and NVRAM. The rest of the flash on larger chips is most often dedicated to FS storage.
The device must first be programmed through USB with an OTA-compatible partition layout.
After programming through USB it must be manually reset or power cycled to set the boot mode correctly.
You can not change the partition layout over OTA programming. You need to make sure you have the same partition layout selected as when you originally programmed through USB.
ArduinoOTA.handle(); has to be called very regularly to handle the programming request. You can't have any blocking code in your sketch that might stop that from being called.

Observe all those and you should be able to program over WiFi with no problems.

I programmed it via USB, program works, OTA was shown in Tools>port options. Program still running... LED blinking... But when I press Upload code to device via OTA port ESP freeze and after few second IDE report error: No Answer, but very strange thing is that original program crashes and esp is unprogrammed... Than i have to upload code again with USB

And have you taken point 5 into account?

every point of your advice is fulfilled... My code is about 210 KB

In my void loop is only ArduinoOTA.handle(); no more rows...

@Sahasrar, point 3.?

For OTA uploads, the size of the compiled (old sketch + new sketch) should not exceed the flash size.
Due to this, large sketches (more than 500KB with 1MB flash) cannot be OTA uploaded directly if the sketch size exceeds half of the flash size.
However, this restriction can be circumvented by first uploading a sketch only with OTA features as given below:

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

char ssid[] = "xxxxxxxx"; //WiFI user id
char pass[] = "yyyyyy";   //WiFi password

#define OTA_Host_Name "ESP01S-EMPTY-OTA"

void setup()  {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    delay(5000);
    ESP.restart();
  }
  ArduinoOTA.setHostname(OTA_Host_Name);
  ArduinoOTA.begin();
}

void loop() {
  ArduinoOTA.handle();
}

This script will compile to around 300KB. Once this script is uploaded in flash, a script with upto 700KB can be uploaded through OTA to a 1MB flash!
Upload this script first. Then restart the controller and choose "ESP01S-EMPTY-OTA" as the port and upload the new updated script that you wish to upload!
IMPORTANT: Firewall must be turned OFF during OTA uploads.

are you sure? the partitions are selected in Tools menu. can it be changed with OTA?


text:
ESP-12e - RX/TX pins flickering on boot when used as GPIO pins
I am using ESP-12e as a controller for my garden lights. I am using pins 1 (TX), 3 (RX) and 5 as an analog output (PWM signal with mosfets) for three separate light sets. ESP is powered on when wall switch is turned on (wall switch turns on power adapter). When I turn the switch on, for short period of time lights connected to pin 1 and 3 work at full power and after that they are set according to PWM signal. Lights on pin 5 works just as expected. I am not using Serial communication, just elegantOTA library for OTA updates and async web server. Is it possible to somehow disable RX/TX functionality at all/before they are set to high, or I am forced to solder lights on pins 1 and 3 to another ones? I tried some software tricks I found online, but without success.

I am not using Serial communication,

You might not be, but the bootloader sure is.

Is it possible to somehow disable RX/TX functionality at all/before they are set to high

No. It's hard coded in ROM. There's nothing you can do.

or I am forced to solder lights on pins 1 and 3 to another ones?

You could use one IO pin to control a buffer the other IO pins. Something like an AND gate (74HC08) would do the job:

simulate this circuit – Schematic created using CircuitLab
Only when CTL is HIGH will the L0-L2 signals be mirrored on the outputs to the LEDs. That way you ignore whatever is going on with those pins until you actively drive the CTL signal high. Choose one pin that has no boot noise for CTL and the other pins then don't matter.
For more detail on what pins do what at boot time read this.

Thanks. I was hoping I could solve this problem only with software because of difficult access to esp-12. I understand the way with AND gate, but probably simpler way for me is to cut off cables from RX/TX and solder to more appropriate pins.

After some digging I realized, that esp-12 has only two pins (4 and 5) which are perfectly suitable for my job (no high state on boot), so as I need three pins, your AND buffer technique is  best option.

This is why most WiFi lights that use the ESP8266 (or ESP8285 most commonly) use a PWM LED driver chip, like the MY9231. Offload the LED control to something else and don't worry about what happens at boot on the ESP8266.

According to this reference, GPIOs 1 and 3 have dedicated behaviour during boot (debug output or pulled high) which can not be disabled in your sketch.
You have to either choose different pins or implement an additional circuitry.

Thanks. I was hoping I could solve this problem only with software because of difficult access to esp-12. I did not give enough time to the selection of pins, but at least, I learned something new.


text:
Arduino to AtTiny change of pin interrupt behaviour?
I have a project which, to save on battery, is put to sleep until an interrupt pin is rising from LOW to HIGH.
This works well on Arduino Nano, however the translation doesn't on the ATTiny.
#include <avr/sleep.h>
void setup(){
    pinMode(2,INPUT);
    noInterrupts();
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    attachInterrupt(INT0,wakeUp,RISING);
    //Yadada
    Interrupts();
}
void wakeUp(){
   //Something Something
   sleep_mode();
}

Both on the Arduino Nano and the AtTiny, the interrupt Pin 0 is equivalent to Pin 2.

The Arduino is set to ISP
I have run the Bootloader (with internal clock as 8MHz if that makes a difference)
The program loads on the AtTiny45.

Yet, the interrupt pin does not interrupt.
Does the INT0 act differently on a ATTiny than on the Arduino, and if so, how can I wake up my AtTiny?

attachInterrupt(digitalPinToInterrupt(pin), ...

The INT0 value is 0 for Atmega328 and it's 6 for the Attiny45... It was working just by accident on the other Arduino. It's not even supposed to be used with attachInterrupt (it's used by attachInterrupt to setup registers correctly)

Aaaaah so that's why it's not recommended. I will give it a try and come back with corrections! Thank you both!

@Juraj, For some reason my version of Arduino IDE does not recognize the digitalPinToInterrupt? Looks like a usual thing so will see how else I can do this. Currently diving in the GIMSK etc. :S

it is possible that the Arduino core in this boards support package doesn't have the function

After going through a lot of documentation, it seemed best and more efficient to attach the interrupt without functions.
EIMSK  |=  (1<< INT0);//Attaches the interrupt
MCUCR  |=  (1<< SM1)  //Power-down mode
         | (1<<ISC01) //The rising edge of INT0
         | (1<<ISC00);// generates an interrupt request

I think it's great that you came back and answered your own question.  But, this answer seems weirdly mismatched with the question "Does the INT0 act differently on a ATTiny than on the Arduino, and if so, how can I wake up my AtTiny?"


text:
Button to stop a stopwatch not working correctly!
I'm trying to implement a stopwatch with an LCD display, and I'm supposed to be using the attachInterrupt command to catch the button press. The clock runs perfectly, but the button input isn't caught or acted upon at all.
In void setup(), I have set it up this way: attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, RISING);.
And the buttonInterrupt function only does start = !start, so in a sense just flipping the start variable.
This is the updated version of the code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = 7;
volatile int buttonState;
int lastButtonState;
long sec;
long startTime;

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT_PULLUP);
  lcd.setCursor(0,0);
  lcd.print("Push the button!");
  attachInterrupt(digitalPinToInterrupt(buttonPin),buttonInterrupt,HIGH);
}

void loop() {

  buttonState = digitalRead(buttonPin);
  if(buttonState == LOW){
    startTime = millis();
  }

  while(buttonState == HIGH){
    long time = millis();
    long z = (time - startTime);
    sec = (z/1000);
    long ms = z%1000;
    lcd.setCursor(0,1);
    lcd.print(sec);
    lcd.print(".");
    lcd.print(ms);
    lcd.setCursor(8,1);
    lcd.print("Secs");

    if(buttonState == LOW){
      break;
    }
  }
}

void buttonInterrupt() {
  if(buttonState == LOW){
    buttonState = HIGH;
  }else{
    buttonState = LOW;
  }
}

The loop function works as far as time counting is concerned, but doesn't work to stop the time with the button. Any help is appreciated, I'm extremely new to Arduino (literally started yesterday). My circuit looks like this: https://i.stack.imgur.com/XHHy5.png
If there is any other way to print the numbers other than printString, more than happy to hear them!
Thanks!

In your wiring diagram the button has a pullup resistor? Are you sure, that this resistor is not connected to ground instead? Also I cannot see anything for debouncing the button. You won't get good results without debouncing

@chrisl you are right, it is supposed to be connected to GND, but fixing that doesn't solve my issue either! And unfortunately I do not know what debouncing means! Will have to look that up now. Thanks!

is variable start volatile?

@Juraj, no it was not. But even I switch to volatile, it does not seem to help.

You need to set msStart to the current millis() value after the while loop. A better way would be to make the code non-blocking like in the BlinkWithoutDelay example. Also don't expect the stopwatch to be too precise because the code in your while loop will take some time and therefore sec=sec+1; will not be executed exactly every 1000 ms

Another tip: be consistent with the datatype of start. If it is a boolean, you better use true\false. If it is an integer, you better don't use the NOT-operator (!). If start becomes 1 at one point, start=!start will make it toggle between 1 and 254, which probably is not what you intended

You better post the whole, compilable code, so things like the datatype of start are clear to people reading the question.

@Sim Son thanks for your answer! I have tried a different way of flipping the start variable, now that you mentioned boolean, it's clear to me my way didn't make any sense to flip 0 to 1. That being said, this solution did not fix the issue, and I'm not sure how to set msAtStart to millis() as this causes the stopwatch to tick to 0.1s and then tick back to 0.0. Thanks for your help! I have posted the whole, compilable code in my question body now.

Does it start when you press the button, though?

@ocrdu nope, it does not! if i set start = 0; it doesn't start at all, and if i put it to 1, the timer starts as soon as I start the program.

Nothing at all from the button then. With the answer you got you from Edgar Bonet you should be able to get it to work. Get that button wired up properly first, and see what happens. Or I could post working code, but where's the fun in that?

@ocrdu I wired it up correctly and tried a different method now. The button input works now - at the click of the button, the timer starts, but a second click doesn't stop it. So now the problem is with debouncing maybe or just my interrupt function. I still don't quite get debouncing so will have to read a bit about that, but atleast the button and the clock are working sort of OK.

@ocrdu now I just cannot figure out how to get an "updated" button state that will kill the while loop and let the output stay there. that is what the Interrupt is supposed to do, but the state switch in the interrupt funct from LOW to HIGH / HIGH to LOW doesn't seem to reach the while loop. Quite confused...

Loop() already loops. Lose the while. If buttonState == HIGH, calculate and display time passed. Otherwise, do nothing.

Oh, I see you changed the code. Don't set buttonState in the loop(), leave that to the interrupt. You can worry about resetting the startTime later. And don't use INPUT-PULLUP unless the switch connects the input pin to LOW.

There are several issues here. First and foremost, your button is wired
incorrectly. If you connect one end of the button to +5V, then the other
end should have a pushdown to GND, like here:

(Image from the Arduino Button example).
The second issue is the lack of debouncing. You should ignore the rising
edges you sense for a few milliseconds after you record one.
The third issue is the timekeeping. As explained by Sim Son, your
seconds will not be very accurate. It's better to just count the
milliseconds elapsed since the button press, and then break the count
into full seconds and remaining milliseconds.

Hi @edgar bonet - thanks so much for the answer! I have fixed a couple of things you talked about here. the stopwatch now starts upon the press of a button, but a second button press doesn't stop it. I assume that's because of the interrupt function, but I don't see where exactly the problem is. Any help is appreciated! Thanks. I have posted the updated code in the main body of the question. The debouncing I have not quite understood and haven't implemented yet.

@Raighley: The code now is a mess, and I can't quite understand what it is trying to do. If you use INPUT_PULLUP, you don't need a pulldown, and the button is active when LOW. attachInterrupt() doesn't support a HIGH mode. There is no point in using both digitalRead() and attachInterrupt(). buttonState seems to serve two unrelated purposes. lastButtonState is never used... I suggest to restart from scratch: forget about interrupts, read about “button bounce”, and use a debouncing library.


text:
ST7920 and u8g2 only using some of a 128x64 display
I am trying to use the u8g2 library and an Arduino Mega to control an LCD display. Adapting HelloWorld from the examples included in the library to use the SPI ports of the Mega (50-52), I have the code below.
This gives a bit of a disappointing greeting as in the picture below. It seems that the Arduino is not accessing all the pixels, and only able to change the states of three blocks (the top one with "Hello V", and the two darker regions at the bottom).

The display is a 128X64ZW-10 salvaged from a 3D printer which was working when connected to the printer's motherboard. Pin-out deduced by some kind folk here and here (translation). I briefly saw random Pinyin characters flash across the whole display while I was switching wires. These two facts, and the fact that the regions of pixels that are working are not arranged at random, makes me suspect it is a wiring or coding issue, and that the pixels are not dead.
Here is the code:
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int LCD_CLK_PIN = 52; //Clock (white)
int LCD_RW_PIN = 50; //Read-Write (blue)
int LCD_RS_PIN = 51;  //Register Select (green)
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

void setup(void) {

  /* U8g2 Project: SSD1306 Test Board */
  //pinMode(10, OUTPUT);
  //pinMode(9, OUTPUT);
  //digitalWrite(10, 0);
  //digitalWrite(9, 0);

  /* U8g2 Project: T6963 Test Board */
  //pinMode(18, OUTPUT);
  //digitalWrite(18, 1);

  /* U8g2 Project: KS0108 Test Board */
  //pinMode(16, OUTPUT);
  //digitalWrite(16, 0);

  /* U8g2 Project: LC7981 Test Board, connect RW to GND */
  //pinMode(17, OUTPUT);
  //digitalWrite(17, 0);

  /* U8g2 Project: Pax Instruments Shield: Enable Backlight */
  //pinMode(6, OUTPUT);
  //digitalWrite(6, 0);

  u8g2.begin();
}

void loop(void) {
  u8g2.firstPage();
  do {
    u8g2.setFont(u8g2_font_ncenB10_tr);
    u8g2.drawStr(1,18,"Hello World!");
  } while ( u8g2.nextPage() );
  //delay(1000);
}

I have spent a couple of days on this, but no luck. Any ideas?

Many thanks for your photos.
Test carried out with the motherboard of an Ender3 V1.1.3
PIN configuration: U8g2lib library
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int LCD_CLK_PIN = 30; //Clock (white)
int LCD_RW_PIN = 17; //Read-Write (blue)
int LCD_RS_PIN = 28;  //Register Select (green)
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

configuration PIN: library U8glib
#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(30, 17, 28);  // SPI Com: SCK = en = 18, MOSI = rw = 16, CS = di = 17

Your program is working properly.

Welcome to Arduino Stack Exchange. In future please post answers in English. I have translated your post for you. Also please format your code in future by selecting it and pressing Ctrl+K.


text:
XH-M131 Photoresistor Relay Module NC position
I have purchased XH-M131 Photoresistor Relay Module to automatically light my outdoor yard at sunset and turn it off at sunrise. I'ts working as it is supposed to, However, if I power off the relay, the light goes off.
I want this to be a closed circuit in such way if the relay malfunction or loose power, the outdoor light stays on which I can manually switch off if I want to.
BTW, I tried connecting the light wires to the otherside, but the whole thing reversed, light goes on when light detected which defies the purpose. Any suggestion or modifications.

It is correct to connect the light wires to the other side (aka normally closed / NC), but then of course you also need to invert your program logic (turning the light off by activating the relay, turning it on by deactivating the relay). Have you tried that?

@chrisl the relay is self controlled by Light Dependent Resistor. Is there a way to reprogram it or reverse the trigger mechanism?

Oh, then only if you analyse the used circuit on that module and hack it. But where is the Arduino in your setup? If there is no Arduino, you are at the wrong site. This is Arduino SE

If you put an additional relay (Relay B) between the XH-M131 and the light and connect the light to the mains via the Normally Closed pole of Relay B, the light will be ON unless Relay B is activated or you turn off the light switch.
Then, connect the coil of Relay B (instead of the light) to the "other side" as you say, of the XH-M131, the logic will be such that when the sensor is exposed to light (daytime) the XH-M131 turns on. That will activate Relay B, switching it from Closed to Open and turn the light OFF.
If the XH-M131 fails, the light will be ON.


text:
Value keeps incrementing even though loop has terminated, why?
I use a double called delta and use that to turn off an LCD if delta is larger than the timeout threshold. Once that happens, delta is supposed to set to 0 and then other parts of the program run. However, delta continues to increment and I'm not sure why.
This is causing a problem because delta is used to determine if the device should "sleep". So when I try to wake up the device via button click, delta is always way past the timeout threshold and the device immediately goes back to sleep.
Any thoughts as to why? Thanks in advance.
#include <M5StickC.h>

double BUTTON_PRESS_NEXT_PRESS_TIME= .5; //Time in seconds
double MINIMUM_BUTTON_PRESS_TIME = .05; //Time in seconds
int BUTTON_PRESS_SLEEP = 3; //Time in seconds
int SCREEN_TIMEOUT = 5;
int count;

static int pressCount = 1;
static int nextPress= 1;

static bool buttonIsPressed;

void setup(void) {
  buttonIsPressed = false;
  M5.begin();
  M5.Lcd.setRotation(0);
  M5.Lcd.fillScreen(TFT_BLACK);
  M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Axp.ScreenBreath(100);

  updateScreen();
}

void updateScreen() {
   char tmp[12];

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Lcd.drawString(dtostrf(pressCount,4,0,tmp), 80,60,6);
  M5.Lcd.drawString(dtostrf(nextPress,3,0,tmp), 80,100,6);
}

static void evaluatePress(double d) {
   // Evaluate press
  if (d >= BUTTON_PRESS_NEXT_PRESS_TIME) {
    nextPress++;
    pressCount = 1;

    if (nextPress == 19) {
      nextPress= 1;
    }
  }
  else if (d >= MINIMUM_BUTTON_PRESS_TIME && d < BUTTON_PRESS_NEXT_PRESS_TIME) {
    pressCount++;
  }

  updateScreen();
}

void sleepLoop() {
  bool bIsPressed = false;
  Serial.println("Sleep 1");
  while(1) {
    Serial.println("Sleep 2");
    if (digitalRead(M5_BUTTON_HOME) == LOW && !bIsPressed) {
      bIsPressed = true;
    }

    if (digitalRead(M5_BUTTON_HOME) == HIGH && bIsPressed){
      Serial.println("BREAKY BREAKY");
      M5.Axp.ScreenBreath(100);

      break;
    }
  }
}

void awakeLoop() {
  double delta;
  double old_time;
  double current_time;

  Serial.println("Awake 1");

  while(1) {
    Serial.println("Awake 2");
     //Calculate delta time
    old_time = current_time;
    current_time =  millis();
    delta = delta + (current_time - old_time)/1000;

    if (digitalRead(M5_BUTTON_HOME) == LOW && !buttonIsPressed) {
      buttonIsPressed = true;
      delta = 0;
    }

    if(digitalRead(M5_BUTTON_HOME) == HIGH && buttonIsPressed) {
      buttonIsPressed = false;
      evaluatePress(delta);
      delta=0;
    }

    if(delta > SCREEN_TIMEOUT && !buttonIsPressed) {
      Serial.println(delta);
      Serial.print("BREAK AWAKE");
      Serial.println(M5.Axp.ScreenBreath(0));
      count = 0;
      break;
    }
    else {
      count++;
    }
  }

  delta = 0;
}

void loop() {
  awakeLoop();
  sleepLoop();
}

Sorry, but that's a crazy way of doing a screen timeout. You don't need delta and you certainly don't want it to be a double...  Just record current_time = millis() when an action happens and break when (millis() - current_time) > 5000.

Thanks @Majenko. I've stripped out some code so that the question focuses more directly on the problem. I think I can do what you suggested though and will give it a try. What's wrong with a double?

@Kyle double needs floating point operations for every calculation, which the Arduino does not support in its hardware. Thus this has to be done in software, which is very computation expensive. So a general rule is, to only use a floating point type (float or double), when it is really necessary. millis() uses unsigned long, so why not using the same for the variables?

Here:
void awakeLoop(){
  double delta;
  // The rest of the function body...
  delta = 0;
}

delta is being defined as a variable local to the function awakeLoop()
and with automatic storage. This means the variable is created whenever
the program enters the function, is not implicitly initialized, and is
destroyed when the function returns.
The last statement delta = 0; has no effect, as it is setting a
variable that is going to be destroyed right away. The compiler most
likely got rid of it.
You most likely want the variable to retain its value across invocations
of the function. For this to be the case, it has to be either global
(defined outside the function) or local with the static qualifier. In
both cases, it will have static storage, i.e. its lifetime will be the
whole program run. Also, if you fail to explicitly initialize it, the
compiler will implicitly initialize it to zero.

Thanks @Edgar Bonet. The problem that I'm having is that delta does not actually get set to 0 or destroyed. I know that I shouldn't/don't need to set delta to 0 at the end of the loop, but I added that line because the program is not acting as I'd expect. The line that prints out delta, right below "Brake awake" always prints out a value that I would expect if the loop were to run continually.

@Kyle: That value is meaningless, as delta has not been initialized. Whether it matches your expectations or not is just chance, and you should not count on it.


text:
Not getting input from sensor using timer
I wrote a code to move linear actuator and lights up and down using timer. But its not getting Sensor input please help me in this.
#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
#define interruptPin 2 //Pin we are going to use to wake up the Arduino
int uv1 = 7; //light
int uv2 = 8; // light
int mot1 = 5; //motion down
int mot2 = 6; // motion up
int buzz=39;
const int speaker = 27;
int led = 9;
int ledState = LOW;
int inputPin = 10;               // choose the input pin (for PIR sensor)
int pirState = 0;            // variable for reading the pin status, we start, assuming no motion detected
long previousMillis = 0;
long interval = 2000;
long OnTime = 30000;
long SenseDel = 8000;           // milliseconds of on-time
long OffTime = 8000;
unsigned long timestart = 0;
const int ply = 23; // relay to reset the sound
const int stp = 35; //relay to puase sound
bool sound = false;
long time_taken = 0;
int start_delay = 3000;
int audio_time = 8000;
int audio_time1 = 8000;
int audio_time3 = 8000;
void setup()
{
pinMode(led, OUTPUT);
pinMode(uv1, OUTPUT);
pinMode(uv2, OUTPUT);
pinMode(mot1, OUTPUT);
pinMode(mot2, OUTPUT);
pinMode(led, OUTPUT);      // declare LED as output
pinMode(inputPin, INPUT);     // declare sensor as input
digitalWrite(mot1, HIGH);
digitalWrite(mot2, LOW);
digitalWrite(led, LOW);
pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
Serial.begin(9600);
pinMode(ply, OUTPUT);
pinMode(stp, OUTPUT);
pinMode(speaker, OUTPUT);
// TIMER 1 for interrupt frequency 300.0018750117188 Hz:
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 300.0018750117188 Hz increments
OCR1A = 53332; // = 16000000 / (1 * 300.0018750117188) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 1 prescaler
TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
digitalWrite(speaker,LOW);
audio_message();
delay(200);
}
ISR(TIMER1_COMPA_vect)
{ //interrupt commands for TIMER 1 here
pirState = digitalRead(inputPin);
}
void loop()
{
unsigned long currentMillis = millis();
while ((pirState == HIGH) && (currentMillis-previousMillis >=SenseDel))
{
//previousMillis = currentMillis;
Serial.println("Motion detected!");
digitalWrite(mot2, LOW);
digitalWrite(mot1, LOW);
digitalWrite(uv1, HIGH);
digitalWrite(uv2, HIGH);
//delay(SenseDel);
//Go_To_Sleep();
}
// We only want to print on the output change, not state
//pirState = HIGH;
while ((pirState == LOW) && (currentMillis-previousMillis >= OnTime))
{
previousMillis = currentMillis;
Serial.println("Moving Down");
digitalWrite(mot2, HIGH);
digitalWrite(mot1, HIGH);
digitalWrite(uv1, LOW);
digitalWrite(uv2, LOW);
pirState = HIGH;

}
while ((pirState == LOW) && (currentMillis-previousMillis >=  OffTime))
{
//previousMillis = currentMillis;
Serial.println("Stay There!");
digitalWrite(mot2, HIGH);
digitalWrite(mot1, LOW);
digitalWrite(uv1, LOW);
digitalWrite(uv2, LOW);
pirState = HIGH;

}
while ((pirState == LOW) && (currentMillis-previousMillis >=  OnTime))
{
//previousMillis = currentMillis;
Serial.println("Moving Up!");
digitalWrite(mot2, LOW);
digitalWrite(mot1, LOW);
digitalWrite(uv1, LOW);
digitalWrite(uv2, LOW);
tone(buzz,2000);
delay(1000);
noTone(buzz);
delay(1000);
 pirState = HIGH;

}
}
void Go_To_Sleep()
{
sleep_enable();//Enabling sleep mode
attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
sleep_cpu();//activating sleep mode
Serial.println("just woke up!");//next line of code executed after the interrupt
audio_message();
}
void wakeUp()
{
Serial.println("Interrrupt Fired");//Print message to serial monitor
sleep_disable();//Disable sleep mode
detachInterrupt(0); //Removes the interrupt from pin 2;
}
void stop_button()    // func to act as stop sound
{
digitalWrite(stp, LOW);
delay(200); //100
digitalWrite(stp, HIGH);
}
void play_button()  // // func to act as play sound
{
digitalWrite(ply, LOW);
delay(140);//100
digitalWrite(ply, HIGH);
}
void audio_message()
{
digitalWrite(speaker, HIGH);
play_button();
sound = true;
delay(100);
//digitalWrite(speaker, LOW);
Serial.println("Speaker On");
play_button();
//time_taken = millis();
delay(audio_time1);
delay(audio_time);
//delay(audio_time3);
//Do something.....
play_button();
stop_button();
sound = false;
digitalWrite(speaker, HIGH);
Serial.println("Speaker Closed");
delay(1000);
}

First, please format your code properly (standard Markdown rules apply). Secondly, what sensor isn't it receiving the input from? What hardware do you have, how is it wired up, and how do you expect it to behave?

reduce your code to only read the sensor and print its value ... your sketch has a lot of code that is unrelated to the sensor

pirState needs to be declared volatile


text:
continuous print of button Pushed
When pushing a button I want to read the value...once.
If I push(hold) the button I get a continuous print of button1Pushed
    if(button1State == LOW) {
     Serial.println("button1Pushed");
  }

But if I try to solve it like this, nothing happens, not a single print. What am I missing?
 int button1State = digitalRead(button1);
  int lastButton1State;

  if(button1State != lastButton1State){
      if(button1State == LOW){
        Serial.println("button1Pushed");
               }
        }

  lastButton1State = button1State;

lastButton1State is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of 0 (which is random, it's not due to implicit initialization, which is only done for global variables). The condition if(button1State != lastButton1State) becomes true only if the button is released.
You can check that by changing
if(button1State == LOW){
  Serial.println("button1Pushed");
}

to
if(button1State == HIGH){
  Serial.println("button1 released");
}

The following should work:
int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
void setup () {
  // whatever you want to do here
}
void loop() {
  int button_state=digitalRead(button1);
  if (button_state!=last_button_state && button_state==LOW) {
    Serial.println("button pressed");
  }
  else if (button_state!=last_button_state && button_state==HIGH) {
    Serial.println("button released");
  }
  last_button_state=button_state;
}

your suggestion gives me the same result, still an endless repeat of the serial.print

Did you see the change I made? I forgot to add last_button_state=button_state;... if it still doesn't work, please post the entire code

I tried your suggestion in a blank sketch and it works!
There is probably something buggy in the rest of my code (its pretty huge..for me..as a amateur)

Found it! I put int last_button_state=HIGH; in the loop.....pff..time for bed

@Niles please see my comment


text:
ESP32 servo runs continuous
I have ESP32 connected to TZT servo SG90.
This is the code
#include <ESP32Servo.h>
#define TURN_TIME 175

Servo myservo;  // create servo object to control a servo
// 16 servo objects can be created on the ESP32

int pos = 0;    // variable to store the servo position
// Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33
#define servoPin  17
#define MOTOR_1_PIN 22

void setup() {
  pinMode(servoPin, OUTPUT);
  Serial.begin(9600);
    // Allow allocation of all timers
    ESP32PWM::allocateTimer(0);
    ESP32PWM::allocateTimer(1);
    ESP32PWM::allocateTimer(2);
    ESP32PWM::allocateTimer(3);
    myservo.setPeriodHertz(50);    // standard 50 hz servo
    // using default min/max of 1000us and 2000us
    // different servos may require different min/max settings
    // for an accurate 0 to 180 sweep
}

void loop() {

  myservo.attach(servoPin, 700, 2500); // attaches the servo on pin 18 to the servo object
  myservo.write(0);
  delay(TURN_TIME);
  for(int i =0; i<180; i++)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  delay(3000);
  for(int i =180; i>0; i--)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  myservo.detach();
  delay(3000);

}

My servo starts rotating one way and reverse for few degrees, then after 5 seconds the servo starts rotating at one way forever..
I had no problems with arduino and nodemcu board. What should I change in the code?
EDIT: I have connected the servo with battery, they have common ground.
The pin on esp32 that I am using is G17. "#define servoPin 17" in the code

There is no need to detach the servo in the loop. Just attach it in setup and never detach it. Detaching will stop the pwm signal, but a servo needs a continuous pwm signal even when stationary.

Without detach() the result is the same.

I didn't expect it to be the root cause... rotating at one way forever - is it actually an angle-controlled servo that you are using and do you use the exact same hard- and software like you did on the arduino/nodeMCU?

It's servo which can be rotated in 360 degrees. But when I control it with other microcontroller I can control it only 0-180. Here I have random moves and at some point rotation to infinity..

Can you figure out, at which point in your code the servo behaves unexpectedly?

I used other servo library and it worked.. Then i changed the pulse width with this line of code.
The default is 1000-2000. But it rotates only 95 degrees. When it's pushed to around ~2850us the servo rotates up to 181-185 degrees.
servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);
#include <Servo_ESP32.h>

static const int servoPin = 16; //printed G14 on the board
int delayTime = 20;
Servo_ESP32 servo1;

int angle =0;
int angleStep = 5;

int angleMin =0;
int angleMax = 180;
#define CHANNEL_NOT_ATTACHED -1
void setup() {
    Serial.begin(115200);
    servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);

}

void loop() {
    for(int angle = 0; angle <= angleMax; angle +=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }

    for(int angle = 180; angle >= angleMin; angle -=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }
}


text:
915Mhz vs Wifi (speed impact of duty cycle limitations)
I am currently using an esp32 with Wifi. I need at least 15kByte/s constant throughout. This works fine but I am not happy with the range.
I came across the RFM69HCW 915MHz module. It is stated with 300 kbps.
Now what is confusing me are duty cycle regulations. Various countries have a 1% limit.
Is this limit considered in the 300 kbps? Or do I effectively only get 3 kbps because I cannot constantly send?

300kbps is the data transmission rate. Not the throughput rate.
That means that yes, if you only transmit for 1% of the time then for 1% of the time you are getting 300kbps - i.e., 3kbps as you correctly surmised.