text:
Extract Static Acceleration from MPU6050 using Formula
I am trying to implement a research paper for my project and there is a formula which I am failing to interpret:

According to the research paper, we extract the static acceleration component for each axis µ, (i=X, Y, Z) by using a running mean filter (the formula), where t is time index, win_size is the window size, and ,∗ is the acceleration data, respectively.
The research paper using MPU6050 to implement this formula. My question is how do I calculate these values using MPU6050. I am currently using MPU6050_Light.h library to calculate acceleration values and I have no idea where to move from here.
Help would be greatly appreciated.

You could change the limits to 0 to win_size - 1 so that they are compatible with C arrays. Then cycle around the array putting a new float into it at the current index while updating the sum and rolling average. Then update the index.

Are you asking about how to read the acceleration from the MPU6050? Or are you asking about how to compute a running average?

@EdgarBonet, Thank You for your reply. You have nudged me in the right direction by telling me about running average. I didn't know that this formula was of calculating running average since nothing was mentioned in the research paper.


text:
How to control Shift registers output individually bitwise
so i am working on a project which needs a lots of bit manipulation and shifting out the bits to control the pins of shift registers individually.
So i am using 2 shift registers daisy chained with 16 LEDS. Now, what i want is that, i want to control the LEDs individually just by shifting out the bits
here is what i tried
first Attempt
int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

byte leds=0b1000000000000001; // byte has 16 bits

void setup()
{

  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{

  updateShiftRegister();

}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);

   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

Does not work! the 2nd shift register seems to be copying the first shift register which i don't want
In second attempt, i tried the masking method with HEX data type.
Here is it.
int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

byte leds=0xFFFF & 0x8001; // used hex masking method

// 0xFFFF = 1111111111111111
// 0x8001 = 1000000000000001
// After & it should be 1000000000000001

void setup()
{

  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{

  updateShiftRegister();

}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);

   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

This too makes same effect like the attempt 1 above.
Now here is what i want and need...
byte leds = 0b1000000000000001

/* As you can see the index 0 and index 15 of the byte led
  is set 1 or high which should produce +ve to the 15th pin of first register and 8th pin of second register.

but whenever i try this, it seems that one of the register is copying another one.
So, is there any way to shift out bits to control the shift register outputs individually?
if yes then please give a clear example code with a clear explanation.
if no then, please suggest me some alternative ways which can be used in the same way i want , of course with example code and explanation.
Schematic: arduino.cc/en/Tutorial/Foundations/ShiftOut
Thank You so much for your precious time.
Looking forward to your replies .
:)

Please show how you connected the shift registers. If you really have two of them daisy-chained they can’t be copying each other. Also, you seem to shift out just 1 byte (8 bits). For 16 LEDs connected to two 8-bit shift registers, you need to shift out 2 bytes.

https://www.arduino.cc/en/Tutorial/Foundations/ShiftOut/ here you may find the schematic

Could you add that link to the question?

Ok added the link to the question through my mobile.

You have two problems with your code:

byte is equal to unsigned char and can only hold exactly one byte, aka 8 bits (not 16 bits like your comment says). But you are trying to assign a 16bit number to it. The upper 8 bits are cut out in that process. They are lost. If you want to hold a 16bit number, you need to use a data type, that is at least 16 bits in its size, for example uint16_t (or you can use unsigned int, though in such situations it is often better to use a type, which has the same size on all platforms).
  uint16_t leds = 0b1000000000000001;

The shiftOut() function has this declaration in wiring_shift.c:
  void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)

You can see, that val (which is the data, that should be shifted out) is of type uint8_t, the same as byte, which also can only hold 8 bits. The upper 8 bits of a 16bit value would be cut off and the function also just transmits 8 bits, nothing more (When you look at its implemention in the mentioned file, you will see a for loop with 8 as limit).
Instead you should call that function for every byte, that you want to transmit in a single transmission; 2 times in your case  because you have 2 shift registers.

So the resulting program would look something like this:
int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

uint16_t leds=0b1000000000000001; // uint16_t has 16 bits

void setup()
{

  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{

  updateShiftRegister();

}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);

   // Shiftout lower byte by masking the other byte with bitwise AND (&)
   shiftOut(dataPin, clockPin, LSBFIRST, leds & 0xFF);
   // Shiftout higher byte by shifting the bit pattern 8 bits to the right
   // resulting in the high byte getting to the position of the low byte
   // and then masking away anything else than the new position of the high
   // byte data
   shiftOut(dataPin, clockPin, LSBFIRST, (leds >> 8) & 0xFF);
   digitalWrite(latchPin, HIGH);
}

Note, that the masking with the bitwise AND operator is not really necessary here, but I like to do such things explicitly to make it more clear.

So I need to store almost 50 bits in the variable to control the columns so can 'uint' method be useful in this case ?

In that case I would use a byte array to hold the data. With 50 bits you are at 6.25 or 7 bytes (since you cannot have sub bytes). The declaration would be something like this:
byte leds[] = {0b00011001, ... }; // list the byte data here

And then you can shift that out with a for loop:
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
       shiftOut(dataPin, clockPin, LSBFIRST, leds[i]);
   }
   digitalWrite(latchPin, HIGH);
}

Note that sizeof(leds) will return the size of the leds array in bytes. I also divided through the size of a single element of the array to get the number of elements in the array instead of bytes. In this case this is the same, but since datatypes might change while the code progresses it is better to be save than sorry.

i tried the masking method with HEX data type.

The data, that comes out is the same. The Arduino only knows of binary data. It doesn't know of different representions (like binary, HEX or decimal). The compiler will already convert that to the target value. So for the Arduino both ways are equivalent.

Actually, i am working on a 50x8 dot matrix project and writing up the library on my own instead of copying anyone's code. So I need to store almost 50 bits in the variable to control the columns so can 'uint' method be useful in this case ?

Those 16 bits in the datatype byte is just a small example that I used to explain my problem

@SubhaJeetSikdar I added a paragraph about that at the end of the answer.

The function shiftOut() only works for 8-bit values, as its documentation says.
Additionally, a byte can only store 8 bits. It doesn't matter how many bits you try to assign. (The compiler should have given you a warning, but the IDE likes to hide this.)
You need to write your own output function to shift out 16 bits, AFAIK.

source: Stack Exchange

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

sort: votes


text:
Relay not triggering from loop function. Variable "volume" not updating after encoder is turned to value?
I am reading a value from an encoder "volume knob" and I have a function called void fn_on were I am having sum int to zero and counting until it reaches the set value of volume. I tried posting to serial but my sum counter does not work. I want my relay to run "volume" number of times until sum > volume in my function "fn_on" I believe I am not storing or updating my volume correctly. Thank you for taking the time to look through this.
#include <LiquidCrystal_I2C.h>
#include <Rotary.h>
#include <LCD_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

/* Rotary Encoder - Polling Example

The circuit:
  encoder pin A to Arduino pin 2
  encoder pin B to Arduino pin 3
  encoder ground pin to ground (GND)
*/
#define PINA 2
#define PINB 3
#define RelayPin 8

const char PUSHB = 5;
bool pressed = false;
long volume = 0; // this may not set the volumue

Rotary r = Rotary(2, 3);

void setup()
{
    Serial.begin(115200); // setup Pin modes
    pinMode(PUSHB, INPUT);
    r.begin(true);
    lcd.init();
    lcd.backlight();
    lcd.setCursor(0, 3);
    lcd.print(volume);
    digitalWrite(PINA, HIGH); // enable pull-ups
    digitalWrite(PINB, HIGH);
    // digitalWrite (PUSHB, HIGH);
    pinMode(RelayPin, OUTPUT); // Relay Pin ini
}

void loop()
{
    bool currentState = digitalRead(PUSHB);

    if (currentState == pressed)
    {
        Serial.println("Pressed");

        while (digitalRead(PUSHB) == pressed)
        {
            // do nothing
        }
    }

    unsigned char result = r.process();

    if (result)
    {
        // Serial.println(result == DIR_CW ? "Right" : "Left");
        if (result == DIR_CCW)
        {
            volume = volume - 1000; // change ++ to mulpes of 1000
            Serial.println(volume);
            lcd.setCursor(0, 3);
            lcd.print(volume);
            lcd.print("                                ");

            int sum = 0;
            for (sum = 1; sum < volume; sum++ && currentState = true)
            {
                lcd.setCursor(0, 2);
                lcd.print(sum);
                digitalWrite(RelayPin, LOW); // run test
                delay(3000);
                digitalWrite(RelayPin, HIGH); // run test
                delay(3000);
                digitalWrite(RelayPin, LOW); // run test
                delay(3000);
            }
        }
        else
        {
            volume = volume + 1000; // change volume++ to mulpes of 1000
            // initialize display_menu to 1st line
            lcd.setCursor(0, 3);
            lcd.print(volume);
            lcd.print("                                 ");
        }
    }
}

Where are you calling fn_on() in your code? And do you know you have two variables called “sum”: one as a const int in your global scope and one as an int within the fn_on() function?

your code is quite messy ... please fix the indentation so that the code is easier to read and easier to understand

I changed some of the logic
Okay I am trying to read a value from a rotary encoder, the value that I am reading is "volume (cycles)". I want to dial the encoder to a number and set it with a push button and run a relay N number of cycles. I am using a "for loop" to run my relay once the push button is pressed and when volume is greater than one

Does the LCD display the correct volume? What do you get if you serial print the volume? The whole relay thing isn't relevant until that part works correctly

I believe the issue is that you're setting your encoder pins high with digitalWrite().  Those pins need to be configured as inputs for the interrupts to work correctly.  This will be handled by the encoder library when you call r.begin(true).  In fact, true in that call tells the library to enable the pullups for you.
Removing those lines should fix your issue.

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


text:
How do you handle sensor drift?
I have a pair of potentiometers, on the Arduino, the output seems to drift, by one or 2 digits, back and forth. I would prefer they were read as one fixed value, without variation when their knobs are not turning. You can see in the image, the first and second values are shifting back and forth slightly. How should I address this?
I'm thinking of making a standard deviation function, but then I thought that might be unnecessarily complex.

My code is that the 2 sensor values are setting points in an SVG polyline. Variance means extra points will get plotted, while the device waits for valid input.
How should I deal with the variance in potentiometer readings to avoid outputting noise?
Here's my source:
/**Fucntion Defs**/
void svgHeader();
void svgFooter();
void polyLineBegin();
void polyLineEnd();

int Reset = 4;     //programmatically reset the arduino
int potX = A0;
int potY = A1;

int sensorValX = 0;
int sensorValY = 0;
int oldX = 0;
int oldY = 0;

int del = 2;       //a button on pin 2 for deleting drawn content
int delbutton = 0;
void setup() {
  Serial.begin(9600);
  pinMode(del, INPUT);
  svgHeader();
  polyLineBegin();
  delay(1000);
}

void loop() {
  // close the svg and start over
  if (digitalRead(del) == LOW ) {
    delbutton = 1;
    polyLineEnd();
    svgFooter();
    delay(5000);
    digitalWrite(Reset, LOW);
    digitalWrite(Reset, HIGH);
    svgHeader();
    polyLineBegin();
  } else {
    delbutton = 0;
    //Serial.println(delbutton);

  }

  //dont draw if its not changing
  sensorValX = analogRead(potX);
  sensorValY = analogRead(potY);
  if (sensorValX == oldX && sensorValY == oldY) {
    ; //dont do shi.
  } else {
    Serial.print(sensorValX);
    Serial.print(",");
    Serial.print(sensorValY);
    Serial.print(",");
    oldX = sensorValX;
    oldY = sensorValY;
    // Serial.println(delbutton);
    delay(1000);
  }
}
/**Functions**/

void polyLineBegin() {
  Serial.println ("<polyline points=\""); //x,y points go here

}

void polyLineEnd() {
  Serial.println ("0, 0\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");  //a dirty hack to avoid dealing with 1 last trailing comma.

}

void svgHeader() {
  Serial.println("<svg width=\"1023\" height=\"1023\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">");
};

void svgFooter() {
  Serial.println ("</svg>");
};

That's quantisation noise and is normal. You can't get rid of it, only deal with it. You could take an average, or you could discard some resolution, or you could write your code to work in a range of values not one single value.

Thats not drifting, just electrical noise in the analog input. You cannot really avoid that. But since your code isn't time critical, why not measuring multiple times, a erafing the values and then using the result. That would drastically reduce the noise in the used values

so Ill have to write some code to deal with it. I'm currently looking at calculating variance, standard deviation, normalization, and some other math terms I'm not exactly familiar with. I think I can make a simple statement to ignore values +/-1 of the read values,  but im not sure what to do if the variance where any more than that.

Before you do a analogRead(potX) ... do a "calibration" of your Vcc supply (through internal reference) if it is used as "reference" voltage with some "mean". This can help.

ok, once I got the idea I would need to do it in code, it became simpler to solve. In looking around the terms of quantization, the term thresh-holding came up, and I realized how to solve the problem.
I created a threshold value, and compared the difference between old and new variables.
int threshold =3;
int xVariance = abs(sensorValX-oldX);
int yVariance = abs(sensorValY-oldY);
if (xVariance >=threshold && yVariance >= threshold ||xVariance >=threshold || yVariance >=threshold){
  Serial.print(sensorValX);
  Serial.print(",");
  Serial.print(sensorValY);
  Serial.print(",");
 oldX=sensorValX;
 oldY=sensorValY;

}else{
; //dont do shi.
 // Serial.println(delbutton);
delay(1000);
    }

now, when I turn either potentiometer, I get a response, and output I desire, but not while the device is just sitting there.

Note, that you can leave out the xVariance >=threshold && yVariance >= threshold part in your if statement. It is redundant. The OR operator || will also evaluate to true, if both conditions are met.

This approach introduces hysteresis, which is indeed a common and effective approach against this kind of problems.

@chrisl, is it redundant? in the event one or both potentiometers are +/- threshold value? one value may change, while the other is constant, or both may change.

Yes, it is redundant. The OR operator || also evaluates to true, if both operants are true. You can refer to the truth table of that operator. What you were thinking of is called exclusive OR, or shortly XOR.

Remove the analog component from your device.
Use a rotary encoder.
It will sense the knob rotation digitally.
One huge advantage is that you can easily select the sensitivity of the input. One click can advance the counter by .001 just as easily as advancing by a 1000.
https://duckduckgo.com/?q=rotary+encoder&iar=images&iax=images&ia=images

you're not wrong, once I get this project functionally operable, its going to a children's museum, and you cant have knobs with limits, they break when you get 1000 kids a week cramming them all the way to one side or the other. but I still have some work to do, and I don't have the encoders yet.

@j0h then you may be interested in this ... uses a stepping motor as an encoder ... it makes a tough encoder ... https://create.arduino.cc/projecthub/andrewf1/using-stepper-motor-as-rotary-encoder-3f5de4

Right on! @jsotola I saw some things like this while working in a paper mill, but forgot all about it. I'm definitely going to look into this more, as steeper motors are harder to break than tiny little knobs.

Some methods for "dealing" with the noise:

Take multiple samples. Calculate the average ("mean"). Discard the decimal. This is "oversampling" along with resolution reduction (but reduction of the now increased oversampled resolution).
Take multiple samples. Find the most common value ("mode").
Divide the value by 2 (or 4 if needed). This reduces the range of values and the sampled resolution but discards the noise portion.

The problem you are suffering from is "quantisation noise". This is because an analog signal and a digital signal are not completely compatible. The ADC converts the analog signal into a digital value by successively comparing it to smaller and smaller voltages in steps ("quanta"). There is a limit to how small the steps can get (the resolution), but an analog voltage doesn't adhere to those steps, it will always be somewhere between the final two steps. Sometimes it will be detected as the lower step, sometimes the upper step. By taking multiple samples and averaging them you are estimating how close to one step or the other the value is and "refining" the result. This is "oversampling" and is used to increase the resolution of the ADC at the cost of sample speed.
With those extra samples you can either say "It's this much closer to the upper step" (take the "mean"), or say "It's more likely to be nearer the upper step" (take the "mode") to try and "fix" the value to one of the steps.

I appreciate the new words, and concepts, I will look into these methods further. I was concerned that calculating standard deviation on the Arduino may reduce performance, by being computationally intensive.

I think you should handle the trailing comma within the Arduino by using leading commas instead, but omit the first leading comma using a flag to indicate the first coordinate:
bool firstCoordinate;

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        if (!firstCoordinate)
        {
            Serial.print(",");
            firstCoordinate = false;
        }
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    firstCoordinate = true;
}

void polyLineEnd()
{
    // Clean line ending.
    Serial.println("\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");
}

Alternatively, the first coordinate could be added to the line when it begins, then there is no need for a flag:
void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    Serial.println(sensorValX);
    Serial.println(",");
    Serial.println(sensorValY);
}

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        Serial.print(",");
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

The thresholding technique is great, but, as an aside, I recently discovered this excellent statistics library by Majenko while working on a non-blocking averaging function for Arduino and looking at converting it into a class. I found that that library already does what I want.

thanks @tim, this is valid, constructive criticism, related to the code. It might not address the question, but it does represent meaningful feedback.


text:
Four temperature SHT31 sensors on ESP32
I have to read out the teperature and humidity of four independent SHT31 sensors with the help of an ESP32. Is there any prefered way to do this, since the only examples I can find online are only with one sensor. I have no access to the address pins of the sensors.
Thank you in advance for any help!

Have you found a solution for your problem ... I am trying to use four SHT31 sensors in a ESP32. I have tried to use the multiplexer with those, but because I am using an I2C extender I could not connected. Thanks for your help and guideline.

Try using TS3A5018, part from TI.
You can then connect 4 independent I2C devices (SHT31).
There are also dedicated I2C channel multiplexers such as these.
Below is the example for I2C multiplexer from TI

Yes, reading 4 SHT31 is possible with an ESP32.
If you have the analog version, readout is quite trivial: you simply use 8 analog inputs (2 for each) to read the signal.
If you have the digital version, which has an I2C interface, you need to control each sensor's address pin separately to select the specific sensor you want to read. Otherwise, there will be an address collision on the bus.

Thank you! The problem is, that I have no access to the address pins

@zet0 Then you need to get I2C bus multiplexers, to get each chip on its own bus lines


text:
Cannot pair HM10 BLE 4.0 module from Android phone
I am currently learning Arduino Bluetooth connectivity with a HM-10S module.
I did some sample tutorial code and it works only with LightBlue app.
However, when I use the default Bluetooth pairing function from the android phone(samsung S10 plus), it seems failed to pair or connect.
So here is the cases I tried:
Android App(LightBlue and also Arduino Bluetooth Controller) :
Success connection without entering password.
Windows 10 PC:
Success pairing only by entering password: "123456", but no com port added
Android phone(S10 plus) Default pairing method from setting
Entered "123456" as password to pair, then no response.
So, what puzzles me is:

I can connect with some apps and do my work, without pairing using Android's setting utility; Is that implies establishing a connection for further action does not necessary to firstly getting things paired?

There are no com port installed after I paired the bt module, so it probably mean the module does not provide my desired feature. If that's the case, which BT module is recommended?

Great thanks if somebody could give me some ideas.

I tried a while ago to connect my HC-06 bluetooth module zo my andriod smartphone. The imortant bit, which I couldnt find anywhere described is, that the pairing doesn't really build up the connection. It sets the settings for the connection and then closes it. I always needed an app (either a bluetooth serial terminal app  or my own self written app) initiating and holding the actual connection. And that makes kind of sense. Where should Andriod send the data, when you don't use it anywhere? Why would it hild the connection then?

On Windows I guess it just creates a serial COM port, which is independent there, even if you don't read it.

I'm not sure, if this also applies to the HM-10S, but it might very well. What are you actually trying, that you want to connect without an app running the connection?

While I did compare the HM10 to HC-06, they are still different technologies and they don't need to behave the same. The HM10 is Bluetooth 4 BLE. It seems it can have different characteristics, also depending on the firmware. When the serial com port characteristic is not active, no com port will show up. Unfortunately I don't have enough experience with the HM10 to guide you there. I have just googled for "HM10 serial bridge" and found this blog entry. Maybe it helps. Otherwise you should try similar searches.


text:
Why do I need to use latin-1 instead of utf-8 when using python with arduino?
When reading and writing with a python serial port connection to arduino, if I don't use latin-1 ('ISO-8859-1'), the results are not as expected. Like if I have
int outP = 5;
//...
int outV = Serial.read();
analogWrite(outP, outV);

While with python I have
serial_port.write(chr(255).encode())

I read 3.78 V from the pin, whereas if I use
serial_port.write(chr(255).encode(encoding = 'latin-1'))

I get 5.04 V. I have read latin-1 and utf-8 don't always match, but is there something about arduino that requires using latin-1? Of course, these return different values when testing each encoding, using 255 gives b'\xc3\xbf' (from 'Ã¿') with utf-8 or b'\xff' from ('ÿ') with latin-1, but why does arduino work with latin-1?
FYI other options that work are
v = 255

serial_port.write(v.to_bytes(1, byteorder = 'big'))

serial_port.write(bytes[v])

but is there something about arduino that requires using latin-1?

No, not really.
What it comes down to is that Serial.read() reads bytes, irrespective of whatever encoding they may be being used with.  ISO-8859 only encodes character code points in the 0-255 range, so when you choose a 0-255 code point and send it as ISO-8859, it gets sent as 1 byte, which is how you're code has been written to receive it.
A 255 code point as utf-8 would require multiple bytes to encode and so would result in multiple Serial.read() calls for a given value.
If you open a python3 REPL and put chr(255).encode() or more explicitly chr(255).encode('utf-8') you will see it results in b'\xc3\xbf'.  So on the Arduino side you will see this as two separate Serial.read() results, 0xC3 and 0xBF.
When you're just taking in strings and UTF-8 and splatting them out via Serial.println(), the Arduino is blissfully unaware of that they're UTF-8 and not ISO-8859.  Really you could use any encoding you wanted, the the caveat being that if you're using c-strings to store them, the encoding would need to be one that doens't allow for a single null byte to be in the middle of the string.

You may want to look into using struct.pack rather than cobbling together python bytestrings with sequences of chr() and .encode(whatever). struct.pack will also result in a bytestring, but it's more purpose built for doing this.
You can import struct and then struct.pack('B', 255) will result in b'\xff same as chr(255).encode('iso8859-1'), but at least expresses intent.  'B' here signifies an unsigned char range, you'll find the format specifiers in the documentation. You'll get a greater benefit when you begin using multiple fields where struct.pack will be a lot less unwieldy than the chr and encode and string concatenation.

Yes, len(chr(255).encode(encoding = 'latin-1')) returns 1, while len(chr(255).encode()) returns 2

ok thanks, what format should be used with struct.pack?

I have migrated my previous comment into the answer and addressed your question there.


text:
Change arduino output from input
I'm trying to change values such that the arduino uno outputs comes from what is input, with the code,
int PinOutput = 11;
int PinInput = A0;
int inph;
int inpl;
int input;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(PinInput, INPUT);
pinMode(PinOutput, OUTPUT);
delay(100);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available())

  {

    input = Serial.read();

  }

 else
{

    input = 255;

}
    inpl = analogRead(PinInput)/4;
    Serial.println(inpl);
    analogWrite(PinOutput,input);
    delay(10);
    inph = analogRead(PinInput)/4;
    Serial.println(inph);
    analogWrite(PinOutput,input/2);
    delay(10);

}

Where pin 11 is connected with an RC circuit to pin A0. Will this code take a value through pin 11 and output it to pin A0? I'm checking if this should work right, so I can then check the python code that goes with it. As of now it mostly stalls, but maybe it's a problem with the python code. I'm trying to make it sustain the number put in. Python code I've tried with is,
import serial
import time

ser = serial.Serial('COM3', baudrate = 9600, timeout = 1)
time.sleep(1)

while 1:

    userInput = input('Get data point? ')

    ser.write(userInput.encode())

    for i in range(5):
        arduinooutput = float(str(ser.readline().decode().split('\r\n')[0].strip('\x00')))
        print(arduinooutput)
        time.sleep(0.01)

The numbers printed out are somewhat random, around 100, it seems, no matter the value put in.

pin 13 is not a PWM pin on Uno. https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

@Juraj ok I switched it to 11

PWM is fast switching between 0 V and HIGH. so analogRead will read only 0 or 1023.

You will need a filter between the PWM output and he analog input. Use your favorite web search engine and look for "R/C filter". Since you are waiting for a second already, a long time constant will be fine, without calculating you might like to start with 100 kOhm and 1000 µFarad.

@the busybee ok I can make an rc circuit. So is there no way to send a signal through one pin and receive it through another with a range of values (with just a wire connection)? Only 0 V or HIGH?

Correct. The AVR in the Arduino does not have a DAC (digital analog converter). If you want some, you will need to add another IC.

Well, it's a pity, but the name of analogWrite() is kind of misleading. :-} If you connect the PWM to anything observable by humans like an LED, it will look like being analog.

@the busybee yes I guess an LED and a photodiode could work to transmit an analog signal also.

@user14094230: an LED and a photodiode may be too fast for that. An LDR, on the other hand, may be slow enough to provide the required low-pass filtering.

Ok, I added an RC circuit that outputs DC, the question now is whether the code should work.


text:
What is the difference when an arduino has been unplugged vs when a serial port connection was closed?
Using python code for a serial port connection to an arduino, it sends a value to the arduino, which then starts printing values to serial. The python code will print the value on the first or second run (if run soon enough after), but after that it won't read what's from Serial.println again. To get it to read again (whether I wait some time or not, like for the while loop to finish), the arduino has to be unplugged and plugged in again, why is that different than the serial port connection being closed by python? Here is the arduino code used,
int measured;
int counter = 0;
int maxnum = 10;

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

void loop()
{
  if(Serial.available() > 0)
  {
    while(counter < maxnum)
    {

        Serial.println("V");
        counter++;
        delay(100);

    }
  }
}

I know the value sent from python can be read because I added in code that reads from serial after checking if it's available and changed an output pin value, which works, even if the serial println is not read.
Edit: Since the answer is there shouldn't be a significant difference and the arduino script should be reset if the serial port was closed, the issue should be with the python code.

We cannot know, if your python code also has a problem. But your Arduino code will send the series of "V" only once.
You are using this while loop:
while(counter < maxnum)

in there you are incrementing the variable counter. But after you left the while loop, you are never resetting counter to zero. So the next time, counter is still equal to maxnum. Thus the while loop will not run again. To solve that, insert
counter = 0;

directly after your while loop. Though, for such loops its normally easier to just use a for loop.

Also you might have a second problem. Currently the code waits for Serial data to be received. When something is received, the code will enter the
if(Serial.available() > 0)

statement. But this will stay true, unless you are actually reading the data. Currently the code inside the if statement will be executed on every loop() interation forever. So if you are applying the above fix to the first problem, the code will send "V" forever after you send the first byte to the Arduino. To actually only react to data being received, you need to read the data from the buffer - even if you are throwing the data away:
Serial.read();

What is the difference when an arduino has been unplugged vs when a serial port connection was closed?

For the Arduino itself? Nearly none. Reopening the serial connection will cause the Arduino to reset. The code then starts again from its beginning. Thats also what happens, when you power cycle (replugging) the Arduino. I think there are some little details, where both differ, but that certainly is not the problem here.
For the computer, replugging means, that the USB device (the USB-to-Serial chip on the Arduino to be precise) gets disconnected and again connected. That can lead to the OS allocating a different com-port/device-file for it, than before. Though that doesn't directly do something with the Arduino code (apart from the mentioned power cycle with reset).
For resetting (preserved from comment of OP):

I found that by setting DTR to 0 then 1, then 0 again, right before closing the port, the arduino resets.

Ok, yes I had taken out some code to make the simplest example, but in either case, it should read 'V' at least once when starting. When I use pyserial it would read again after rerunning the script, but with pyqt5 it would not read again. So maybe it's an issue with certain python code not closing the serial port properly, if unplugging and closing the serial port should give the same results. Here is the pyqt5 python version that won't read again.

Though yes, when I put if(Serial.available() > 0)   {     int counter = 0; instead of having the counter initialized at the start, it does read each time. So again, it sounds like the python code was not resetting the arduino code with a new serial port connection.

I'm no expert in pyqt5 serial, but wouldn't that code just exit, when it received one (or a few) line? And the program just exits without reopening the serial port. So when exactly did you think, that the port should be reopened?

It would be reopened when I run the script again. Yes it just reads one line, but if have the python code read 10 lines like the arduino prints, it still doesn't seem to reset the arduino code when restarting the script. I was just trying to have the simplest script here.

Mhh, as written above, we are no experts in pyqt5 serial. The Arduino will reset on signals on the DTR or RTS lines (reference question). Maybe the pyqt5 implementation does not do this by default. You can look into the options of pyqt5 serial. For us that is out of scope. If you need help with that, you can try asking at stackoverflow. That might get you better results, than here.

Yes I have altered the stack overflow question to ask about how pyqt5 opens and closes. Maybe it is an issue with that, pyqt5 has options to set DTR and RTS. Thanks.

Do you know if this would be related to why the python code would sometimes receive and print out a bytes object b'V' instead of a string object V? This could be for another question and could be an issue with the python code again though.

Thats totally on the python side. The serial interface doesn't know the difference between the string V and the byte object b'V'. I would consider it normal, if the python code gave me a byte object as serial data (since serial data isn't necessarily string data; could also be real binary)

I found that by setting DTR to 0 then 1, then 0 again, right before closing the port, the arduino resets.

@user14094230 Great! I have preserved that at the end of my answer, since the comments are temporary and this might help others with the same problem.


text:
circuit breaker/fuse necessary for IoT home monitor?
In most 12v CCTV power supplies, each power cable is behind a glass fuse.  I haven't seen fuses or circuit breakers used when distributing 5v power used in IoT projects.  Is there a reason overcurrent protection is not needed in these projects?
edit:
I'm thinking specifically about fire safety.  e.g. the risk of a short circuit overheating 22awg wire run through the house?

Is there a reason overcurrent protection is not needed in these projects?

You're comparing apples and oranges.
The two systems are completely different and have different concerns.
Case in point:

You want to burgle somewhere with CCTV installed. You can creep up on one camera unobserved.
You know a little about electronics and figure if you cut the feed to the camera you can short out the power and blow the whole system, thus letting you wander in unobserved.

But there's fuses on each feed, so all you do is disable the one camera and everything else is fine, catching you red handed.
Go directly to jail. Do not pass go. Do not collect £200.
Now... do you really care that much if all your home temperature sensors lose power because of a fault in one? Probably not. And the chances of there being a fault other than from human negligence is slim. Sure, you could add fuses, but why add the expense? It's really not needed for such a non-critical system.

edit: I'm thinking specifically about fire safety. e.g. the risk of a short circuit overheating 22awg wire run through the house?

22AWG wire has a resistance of about 53Ω per km. Say you have a loop of cable 20m long (10m there and 10m back again) and it shorted out at the far end. That's round about 1Ω.
At 5V you'd be drawing 5A of current.
If you have a really powerful power supply then it would try and supply that, and the wire would warm up - giving off about 25W of heat over the entire length. You might feel a bit of warmth from it.
Of course, most people would be using a smaller power supply than that for simple IoT things, so the power supply would just go "No. You're not having that!" and would die, or its internal fuse would blow. Or it would drop the voltage and get hot itself.
The chance of being able to start a fire from 5V over 22AWG from a normal power supply is pretty much zero. You're more likely going to start a fire from using a low quality power supply that itself melts and catches fire (i.e., a counterfeit Chinese phone charger).
With a very powerful power supply (tens of amps or more) and a short circuit close to the source (so low resistance) the wire will melt. Just that. It'll melt. Once melted there's no circuit, so nothing else happens. There's your fuse right there.
Once a wire has melted it doesn't continue to burn. And you don't get arcs at low voltages. It takes a lot of work to start a fire from low voltages. A lot of work and a lot of current.

thanks for the response.  I didn't even think about that aspect of it.  I'm wondering more about fire-safety (please see edit).  Thanks!

@zwiebelspaetzle See my edit too.

interesting, thanks!


text:
Failed to boot VL53L0X: VL53L0X Error: -6
I am using a VL53L0X sensor in my project.
It was working fine when suddenly it started to show failed to boot error.
I tried debugging but of no use. I ran I2C scanner sketch and it detected the sensor at 0x29.
I get the following error -
23:38:27.797 -> Adafruit VL53L0X test
23:38:27.830 -> VL53L0X Info:
23:38:27.830 -> Device Name: VL53L0X ES1 or later, Type: VL53L0X, ID: VL53L0CBV0DH/1$1
23:38:27.830 -> Rev Major: 1, Minor: 1
23:38:27.864 -> VL53L0X: StaticInit
23:38:27.932 -> VL53L0X: PerformRefSpadManagement
23:38:27.932 -> refSpadCount = 2226323456, isApertureSpads = 92
23:38:27.932 -> VL53L0X Error: -6
23:38:27.932 -> Failed to boot VL53L0X

This is the code I used (its the example code with just 0x29 and true passed in begin function for verbose output):
#include "Adafruit_VL53L0X.h"

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

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

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin(0x29,true)) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}

I am using an Arduino nano -
following are the connections
ARDUINO->VL53L0X
3v3->Vin
GND->GND
A4->SDA
A5->SCL
I have rechecked the connection and voltages the sensor does receive 3v3 and gnd.
I need help with this asap.
Thanks in advance :)

what is the actual error description? ... the Serial.println(F("Failed to boot VL53L0X")); could just as easily be Serial.println(F("the sky is blue"));

This is the entire error message, could you let me know what you are looking for?

I was facing same issue, now my problem is solved here.
This problem mostly occurs when we apply a power supply to the MCU that has capacitors at its output. This type of power supply's rising voltage is like you can see the image:

If you look at the data sheets of MCUs, you see that most MCUs can work at 1.8V to 5.5V. Here the rising voltage is slow; the MCU starts working at 1.8V and send signals to VL53L0x, but the sensor doesn't work at 1.8V.
So, what you need to do is add some delay (first power supply gets stable then start communication with sensor) in your code to avoid this issue. Do not add delay in the loop; it will affect the working of the MCU, where exactly you need to add delay. Code modifications are in the video below:
https://youtu.be/QEiNbTB8nNE
or you just can search on Youtube: How to fix VL53L0X error

Since it sort of worked before I am assuming it is connected correctly. However you failed to mention pull up resistors on the I2C bus. If they are not there or to weak that could cause what you are seeing.

I tried the same code with another sensor, without any pull ups, it works fine with it.
However, it is this particular sensor which throws an error which i am unable to resolve.

IIRC, the VL53L0X modules have 10K pullups on SDA/SCL already - no need to add

I found a new possible solution to this problem, as I spent 2 days to solve it, I feel that I need to share it with you guys. I also could find the sensor through i2C scanner, but could not initialize it.
Here is the summary of solutions:

Powering problem 1: add a 50ms delay in the setup function (before the sensor init, obviously). This way, the Vin will have time enough to reach the level needed by the sensor, as explained in a previous message (ocrdu)
Powering problem 2: This sensor demands more than others, normally the 5V pin of your board will do it better than the 3v3. If there are many sensors connected at the same time, disconnect all of them to check whether they are using the power our vl53l0x needs.
Powering problem 3: If you feed it with an external source, unify grounds with the board, don't forget it
SCL - SDA weak signals: add a pullup (2k2 - 4k7 from each channel to vin), this way the signals will perform better, that could be the problem
Soldering problem: Make sure that each header pin is well soldered. I've found many cases of poor soldering. The tiny pads don't help. It is advisable to check continuity with a multimeter between the headers and the pads where they should be connected
XSHUT not pulled up: My problem, this was that AZDelivery board says that it has a pull up in XSHUT (which works like an enable). But it could either be false, or badly implemented. Xshut needs to be high, 3v3/5v, otherwise, the sensor won't work. Bridge the XSHUT to Vin or implement a pull up and the problem will be solved.

I am using adafruit's library 1.1.2, and it works, with pullups, without pullups, connected to 5V and also connected to 3V3, with the
50ms delay, and connecting XSHUT to high (3V3 / Vin)
My board is vl53l0x from AZDelivery (5€ amazon)
I have tested the sensor with arduino nano and with ESP32, both work fine

Hope you guys find this useful <3
[esp32] [sensor] [i2c] [boot] [error]

From the VL53L0X API documentation The error shows up as
#define VL53L0X_ERROR_RANGE_ERROR   ((VL53L0X_Error) -6)

Not very helpful, but maybe you still have the factory protective cover installed?
Also, IMHO the Adafruit library is a bit buggy.  I now use the Pololu library (among other things, the Pololu library allows usage of the WIRE1, WIRE2, & WIRE3 hardware I2C busses.
27 September 2020 Update: On the Adafruit technical support forum, I did a search for 'VL53L0X ERROR'.  There were several thread mentioning ERROR -6 issues, but most of them were due to poor or missing solder on the VL53L0X header pins.  Could that be your problem?

I have removed the factory protective cover.
I understand that the error message is not very helpful, I do not know what else I can deduce from it.
I will try to use the Pololu library as suggested.


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:
Stepper motor turns unexpectedly slowly
I want to control a stepper motor using my esp32 and an USB connection. I seem to have some issue understanding why the stepper motor runs very slowly - I suspect it's because power to the motor is somehow provided through the ESP32 board?

Using this setup, and cautiously using very conservative current settings on the TMC2209 (ca 50-100mA), the stepper motor only turns very slowly.
Oberservations:

Using an external power supply, the motor spins according to expectation, pretty fast.
When I dis/reconnect the 20v supply from the pd power board to the TMC2209, it spins again, according to speed of external power supply, after initially turning slowly
providing power/ground to MS1/MS2 pins has no effect on this

Hardware)

Standard ESP32 devkit board with cp2101
the tmc2209 is V3 (with silly wrong labels) from here
the power is a pd trigger board from Aliexpress (seems to provide steady 20v)
the variable step down converter is this one

Software) For the TMC2209 library I'm using this example sketch using one UART cable.
Questions)

Why is the motor spinning faster with an external powersupply (directly attached to the TMC2209)?
What would be a better design / or what can be improved in this setup?
How do I not burn more ESP32 boards / Stepper drivers?

The code is this, from the examples
#include <TMC2209.h>

// This example will not work on Arduino boards without HardwareSerial ports,
// such as the Uno, Nano, and Mini.
//
// See this reference for more details:
// https://www.arduino.cc/reference/en/language/functions/communication/serial/
//
// To make this library work with those boards, refer to this library example:
// examples/UnidirectionalCommunication/SoftwareSerial

HardwareSerial & serial_stream = Serial2;
const int TX_PIN = 17;
const int RX_PIN = 16;
const long SERIAL_BAUD_RATE = 115200;

const int32_t RUN_VELOCITY = 10000;
const int32_t STOP_VELOCITY = 0;
const int RUN_DURATION = 2000;
const int STOP_DURATION = 1000;
// current values may need to be reduced to prevent overheating depending on
// specific motor and power supply voltage
const uint8_t RUN_CURRENT_PERCENT = 100;

// Instantiate TMC2209
TMC2209 stepper_driver;
bool invert_direction = false;

void setup()
{
//  stepper_driver.setup(serial_stream);
  stepper_driver.setup(serial_stream, SERIAL_BAUD_RATE, TMC2209::SERIAL_ADDRESS_0, RX_PIN, TX_PIN);
  stepper_driver.setRunCurrent(RUN_CURRENT_PERCENT);
  stepper_driver.enableCoolStep();
  stepper_driver.enable();
}

void loop()
{
  stepper_driver.moveAtVelocity(STOP_VELOCITY);
  delay(STOP_DURATION);
  if (invert_direction)
  {
    stepper_driver.enableInverseMotorDirection();
  }
  else
  {
    stepper_driver.disableInverseMotorDirection();
  }
  invert_direction = not invert_direction;

  stepper_driver.moveAtVelocity(RUN_VELOCITY);

  delay(RUN_DURATION);
}

to be honest, it is likely that it has something to do with the default values of the library, since if you initialize it properly, it turns slowly. But if you reset the power, then it works. It doesn't explain why it would work with an external power supply with same voltage that is provided at start though...

indeed this was a default value issue.
    stepper_driver.setMicrostepsPerStep(1);

or
    stepper_driver.setMicrostepsPerStep(8);

solved the issue. Unsure where to exact line of code is in the library that initializes the MicrostepsPerStep at 256, which gives extremely precise, yet slow movement - maybe this is also the tmc2209 or tmc2209 version I'm using.


text:
Setup/Debug affordable 9DOF IMU
I bought a 9 DOF IMU from AliExpress (pictures below), asking because this seems to be somewhat of a common issue (and I'm a bleeding noob). I tried setting up this board using example codes from Adafruit - presuming this would work and it's a compatible board (and it just looked exactly the same). However, surprise - several errors.

Using this guide I attempted to run the pitchrollheading example - it reports LSM303 not found. The wiring is according to this guide, A4 (SDA) and A5 (SCL) are connected, 5V in, Ground of IMU to Ground of Arduino (Arduino uno, like in the guide)

Next I debugged the lines on the board using the multimeter: 5V on line in vs ground, 5V on the SDA/SDC lines (seemed fine)

Then I debugged using the i2cdetect library, however it reported empty.
 0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
 00:          -- -- -- -- -- -- -- -- -- -- -- -- --
 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 70: -- -- -- -- -- -- -- --

Using analog read I can get values that seem to change with board movement, that would confirm that - in theory - the board works.

Questions

Making sense from debugging: What could be somre reasons the board not listed using the i2cdetect library (also tried a script)?
Is there an easy way (or would you recommend spending time to investigate) to use the rawdata from the arduino's analog in lines to compute pitch,roll and heading?
Would a project like this be typically orders of magnitude easier to set up with a raspberry pi (I have one setup and ready)? (more libraries?)
Are IMU's usually easy to setup, and is it likely this would be easier with a more expensive IMU (e.g. MPU9250/6500)?

Thank you in advance, and please remember: I'm a noob, I ask for your patience and advice.

You didn't mention connecting the ground of the board to the ground of the Arduino... did you?

yes, I did! :))

initially I tried this with an Arduino nano and phone otg cable. But then same results with pc and Arduino uno

@Majenko thanks, added it in the description

@jsotola because I want the advice from the community and proceed to acquiring data (which I'm looking forward to). Possibly there is a recommendable way to integrate the raw sensor values into a sensor fusion system, as stated, I'm a noob with this, advice is very welcome. On the other hand I'm unsure why asking 'why' is goal-oriented - unless you presume a gross misconception?

what, no, I can read the analog out, but can't properly connect any library... unclear to me why you want to shut this down. I also wanted help to properly debug and figure out if the device is broken in a way I don't understand yet

@jsotola you made an edit ('truck has no fuel', which I'm not even sure what it is supposed to be an analogy for) in your comment that makes your condescending attitude clear. I don't think that is what this community deserves... just point out how I can improve, or improve my understanding. This is literally what I'm asking for. It's not like it's hard to find condescending attitude rather than any helpful remarks nowadays

Let us continue this discussion in chat.

I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode, I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before, will delete question in 24-48h unless objections

post that as an answer and accept it ... it may be useful for someone in the future

I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode (the one that looks like a loudspeaker), I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before


text:
Error occurs when compiling ESP32 self-update firmware code
when i write this code in esp8266, it's work fine. but when i tried that code in esp32 with some changes,it shows error on compile time:

board which i use : DOIT ESP32 DevKit v1

error is:
In file included from C:\Users\Gabbar Singh\Documents\Arduino\ESP32_OTA\ESP32_OTA.ino:5:0:
C:\Users\Gabbar Singh\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\HTTPUpdate\src/HTTPUpdate.h:47:6: error: multiple definition of 'enum HTTPUpdateResult'
 enum HTTPUpdateResult {
      ^
In file included from C:\Users\Gabbar Singh\Documents\Arduino\ESP32_OTA\ESP32_OTA.ino:3:0:
C:\Users\Gabbar Singh\Documents\Arduino\libraries\ESP32httpUpdate\src/ESP32httpUpdate.h:59:6: note: previous definition here
 enum HTTPUpdateResult {
      ^
Multiple libraries were found for "WiFi.h"
 Used:C:\Users\GabbarSingh\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\WiFi
 Not used: C:\Program Files (x86)\Arduino\libraries\WiFi

and the last error is : exit status 1
Error compiling for board DOIT ESP32 DEVKIT V1.
Code:

#include <Update.h>
#include <WiFi.h>
#include <ESP32httpUpdate.h>
#include <WiFiClient.h>
#include <HTTPUpdate.h>
#include <HTTPClient.h>

#define LED_BUILTIN 2

const String FirmwareVer = {"1.4"};

#define URL_fw_Version "http://vadaliya2007.000webhostapp.com/atte/ota/version.txt"
#define URL_fw_Bin "http://vadaliya2007.000webhostapp.com/atte/ota/firmware.bin"
HTTPClient http;

const char* ssid = "Honor8X";
const char* password = "1414141414";

void FirmwareUpdate()
{
  http.begin(URL_fw_Version, "5b fb d1 d4 49 d3 0f a9 c6 40 03 34 ba e0 24 05 aa d2 e2 01"); // check version URL
  delay(100);
  int httpCode = http.GET();            // get data from version file
  delay(100);
  String payload;
  if (httpCode == HTTP_CODE_OK)         // if version received
  {
    payload = http.getString();  // save received version
    Serial.println(payload );
  }
  else
  {
    Serial.print("error in downloading version file:");
    Serial.println(httpCode);

  }

  http.end();
  if (httpCode == HTTP_CODE_OK)         // if version received
  {
    if (payload.equals(FirmwareVer) )
    {
      Serial.println("Device already on latest firmware version");
    }
    else
    {
      Serial.println("New firmware detected");
      WiFiClient client;

      // The line below is optional. It can be used to blink the LED on the board during flashing
      // The LED will be on during download of one buffer of data from the network. The LED will
      // be off during writing that buffer to flash
      // On a good connection the LED should flash regularly. On a bad connection the LED will be
      // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second
      // value is used to put the LED on. If the LED is on with HIGH, that value should be passed
      //ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);

      t_httpUpdate_return ret = ESPhttpUpdate.update(URL_fw_Bin, "", "5b fb d1 d4 49 d3 0f a9 c6 40 03 34 ba e0 24 05 aa d2 e2 01");

      switch (ret) {
        case HTTP_UPDATE_FAILED:
          Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
          break;

        case HTTP_UPDATE_NO_UPDATES:
          Serial.println("HTTP_UPDATE_NO_UPDATES");
          break;

        case HTTP_UPDATE_OK:
          Serial.println("HTTP_UPDATE_OK");
          break;
      }
    }
  }
}

unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 30000;

void repeatedCall() {
  unsigned long currentMillis = millis();
  if ((currentMillis - previousMillis) >= interval)
  {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
    FirmwareUpdate();
  }
}

void setup()
{
  Serial.begin(115200);
  Serial.println("");
  Serial.println("Start");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print("O");
    delay(500);
  }
  Serial.println("Connected to WiFi");
  pinMode(LED_BUILTIN, OUTPUT);
}
void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second
  repeatedCall();
}

what is your question?

i got an error when i compile this code

that is not a question ... it is a description of a problem

how to solve this error...

Please tell us how you compile this, and show us the exact error message. Remember to [edit] your question, do not add information in the comments, they will be ignored.

ohh..i'm sorry...i'm new to this.. i compile this code in arduino ide

the error is i used two libraries esp32httpupdate and httpupdate, which both have same function so i remove the other one(httpupdate)... and now problem is solved.


text:
1.7 MHz generator for a water atomizer
I'm creating a  controller for a small greenhouse, I have a DHT22 for measuring and two relay module that controls heating and cooling systems, and I will use a piezo to produce humidity when it goes below X amount. This piezo works at 1.7 MHz and I know that Arduino can provide 1.779Mhz, I think It's close enough. After that I'll place a MOSFET at the output and then connect the piezo.
I'm quite new so I'm trying copy-paste some codes and this is what I've done:
I don't know how to turn on and off the frequency generator, I would like to know the code for that
           #include <DHT.h>
            #include <DHT_U.h>

            #define DHTPIN 6
            #define DHTTYPE DHT11 //Define sensor as DHT11

            #define RELAY1  4  // Relay heating
            #define RELAY2  5  // Relay cooling

            int red = 8; // red LED heating
            int blue = 9; // blue LED cooling

            DHT dht(DHTPIN, DHTTYPE);

            float temperature;
            float humidity;

            // Frequency Generator code
            const uint8_t OUTPUT_PIN = 3;  // = OC2B pin inamovible
            const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

            void setup()
            {

              pinMode(red, OUTPUT);
              pinMode(blue, OUTPUT);
              pinMode(RELAY1, OUTPUT);
              pinMode(RELAY2, OUTPUT);

              // Freq generator code
                pinMode(OUTPUT_PIN, OUTPUT);
                TCCR2B = 0;           // stop timer
                TCNT2  = 0;           // reset timer
                TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
                       | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
                       | _BV(WGM21);  // ...ditto
                TCCR2B = _BV(WGM22);  // ...ditto
                OCR2A = PERIOD - 1;
                OCR2B = PERIOD/2 - 1;
            }

            void soundBuzzer() {
                TCCR2B |= _BV(CS20);  // F_CPU / 1
            }

            void silenceBuzzer() {
                TCCR2B &= ~_BV(CS20);
                TCNT2 = 0;
            }
              //End of freq generator code
            void loop()
            {
              delay(1000); //delay time between measurements. 1 sec for DHT11

              temperature = dht.readTemperature(); //Reads temperature
              humidity = dht.readHumidity(); //Reads humidity

             if(temperature < 25)
                {
            digitalWrite(red,HIGH);
            digitalWrite(blue,LOW);

            digitalWrite(RELAY1,0);
            digitalWrite(RELAY2,1);
                 }
             else if(temperature > 25)
                {
            digitalWrite(RELAY1,1);
            digitalWrite(RELAY2,0);
            digitalWrite(red,LOW);
            digitalWrite(blue,HIGH);

            }

        if(humidity < 30)
         {
   TCCR2A |= _BV(COM2B1);
    }
        else if(humidity > 35)
                {
          TCCR2A &= ~_BV(COM2B1);

            }
        }

I don't even know if i'm doing it right, please let me know and thanks

Your code doesn't compile: humidity should be humedad, and turn on frequency does not mean anything in C++. Other than that, it looks fine. You should test it!

You should consider replacing your MOSFET with a suitable H-bridge driver and feed an RF transformer to drive the transducer with matched impedance. Just a simple MOSFET will give very poor results. At the absolute minimum you need a resistance across the transducer to bleed the charge, otherwise it won't do much. Medium, drive it with an H-bridge for a full swing signal. Best is to add a transformer as well. Alternatively a half-bridge and center-tapped transformer will reduce component count at the cost of a more complex transformer.

Code was fixed, So if you are telling me that mosfet isn't the best for this task I should consider simply turning ON another relay and adding a different circuit for the piezo then
I was planning to simply put a MP2565 on the output of the Arduino
As I told you before i'm pretty new at this so I don't know if it's good or not


text:
Can't Upload Sketches to Arduino Nano Every
first-time builder here.  I just got my Arduino Nano Every in the mail from Mouser, and I'm trying to upload a modified version of the blink example to my new brand-new board.  However, every time I try to upload a sketch, the IDE just spins its wheels for around 5 minutes before giving up.  I've been trying to look through similar questions and haven't found anything that has solved my issue.  My OS is Windows 10.
Here's a snippet of the log (I've turned on verbose reporting for compilation and upload):
Arduino: 1.8.13 (Windows 10), Board: "Arduino Nano Every, None (ATMEGA4809)"
…
Forcing reset using 1200bps open/close on port COM1
…
         Using Port                    : COM1
         Using Programmer              : jtag2updi
         Overriding Baud Rate          : 115200
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
An error occurred while uploading the sketch

Here are the settings I'm currently using:

Board is set to Arduino Nano Every, using Arduino MegaAVR Boards
1.8.6
Registers emulation:  none (ATMEGA4809)
Port:  COM1 (there are no other options that appear for me, and no
other port pops up in the device manager when I plug the board in)
Programmer:  Onboard Atmel    mEDBG (UNO WiFi Rev2)

Here's what I've tried so far:

Disabled antivirus
Uninstalled and reinstalled Arduino IDE
Turning on registers emulation
Restarting computer
Resetting board
Using different USB cables
Using different USB ports (3.0 and 2.0)
Manually installing Arduino drivers to Windows (Windows said the most
up-to-date drivers were already installed after I specified the
directory to search in)
Nothing is connected to the board.
The pin-13 LED blinks, so there's a bootloader on the board.
I've reset the board before uploading.

Any help would be very much appreciated.  I'm about to give up and just return the board and swap it for a different one.

see in Device Manager the USB devices and the COM ports if the descriptions match. did you try a different USB cable?

@Juraj I'm not sure what you mean by whether the USB devices and COM ports match; their names, descriptions under "details" tab, and location are all different.  I've tried two different cables, yes.

so if you disconnect the Every, the COM1 disappears and if you connect the Every the COM1 is back?

No, COM1 is listed in the device manager regardless of whether the Every is plugged in or not.

A new usb port should pop up when you plug in the Arduino board.  If it doesn't then there is a hardware issue (port or cable or device).  Also, i don't think that jtag is the proper programmer selection.  AVRISP mkII is default programmer I believe.

that programmer selection is ignored for Serial upload. the upload output in Question is right for Every. COM1 is no the Every. look in Device Manager for unknown USB devices

I've just tried with another different cable on another different port on my PC.  The same issue persists, so I suspect that the fault is not with the cable or USB port.  There is no unknown USB device listed under device manager.

try to reistall the megaavr boards package

I've already done that.  When I uninstalled the arduino IDE I uninstalled all associated files, including board packages.

uninstalling the IDE doesn't uninstall the boards packages

I'm aware of that.  I manually deleted all Arduino files everywhere I found them on my computer; original installation, documents library, and appdata.

Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.

I was getting the same error when I got my brand new Nano Every.
I had Registers emulation: ATMEGA328
I changed it to None (ATMEGA4809) and it uploaded without problems.
I'm on ubuntu 18.04, and this is after the IDE prompted me to install the megaAVR boards library (1.8.7) of course.

the emulation selection has nothing to do with the upload. it was something else.

Perhaps. Nevertheless I was having trouble uploading my sketch to my arduino nano every. I googled the error and landed on this question. After reading the question and answers, I realized emulation could be my problem, which it was. This answer was an attempt to aid others with my same problem.


text:
Wireless playstation 2 remote not connecting up to arduino
I am trying to connect my wireless playstation 2 remote up to my arduino but I am facing one problem. Whenever I restart my program (by clicking the red button) the PS2 remote's dongle blinks at the exact same times as the blink light on the arduino blinks. But as soon as the arduino's light stops blinking, the RX light on the PS2 dongle (which was blinking), stops blinking. I saw a guide out there on potential ways of fixing this and one type of way of fixing it according to the documentation for the PS2 libary (which no longer exists on a website) was by doing some type of pull-up resistor (I am not 100% too sure what this is). I have checked the wiring and its fine. This was the website that I followed that shows the step by step instructions on how to program the controller with the arduino and how to wire it: https://create.arduino.cc/projecthub/electropeak/how-to-interface-ps2-wireless-controller-w-arduino-a0a813. Here is the schematic that I followed for the concept with the pull-up resistor:

I have just tried removing the clock pin from pin 13 (which is already connected up to the clock pin of the PS2 controller).This got rid of the blinking of the dongle blinking directly at the same time as the arduino when restarting the program. The reason why I did this was because it seemed to get rid of the RX blinking issue. Here is a few images that might solve the confusion with the problem.

This is how my dongle is wired up to my arduino :

This is the PS2 dongle. The RX light is what keeps blinking synchronous to the arduino pin 13 light (This is the light that blinks each time you re-compile or restart the program).

This is the LED that I am referring to when I mention the LED on pin 13 of the arduino.
So when pin 13 on the arduino is blinking the RX light on the PS2 dongle is blinking synchronous to it.
The reason that I removed the clock pin from pin 13 on the arduino was because I knew that the pin 13's blinking LED connects up to pin 13 itself (which is wired up to the clock pin on the arduino), this did nothing.
What I am trying to aim to get is that the PS2 dongle

Is for it to be like this and for it to just stay on and NOT blink :
One final thing I forget to mention was that when the LED finished blinking (when restarting). the RX LED on the dongle went off.

You didn't really explain what the problem is, I think. From your text I have to think, that you don't like the receiver stop blinking. Maybe because you really like that blinking. But I don't think, that this is really the issue. Please explain more. Why did you remove the clock pin? SPI needs the clock. You won't get any data through without the clock connected. Of course you can use pullup resistors on the data wires (MISO/MOSI), though I cannot say, if that will help you.

@chrisl To be fair, I do agree with you that I did not explain it well, fair enough. I will send some pictures that show my problems.

@chrisl Ok, I have now updated it.

That gives more context (though the images are very blurry), but still the problem is not clear to me. You say, that you want the RX LED on the dongle to stay on. You didn't state, why you want this. I don't know how the dongle works, thus I don't know, what the RX LED means. From your description, that it blinks sychronous with the clock line (LED on pin 13 of the Arduino) I guess, that it shows receiving data from the Arduino. It cannot stay on, when you don't send data all the time and why would you want that?

You should work on how to focus your camera.  Those images are pretty bad.  I can't make out anything in any of them.  Try to get some in-focus pictures.


text:
Why must I reload ArduinoCreateAgent-1.1-windows-installer-chrome every time I restart my computer?
What am I missing that this is happening?
Used to use a laptop (with Create Agent installed on hard drive) which never had this problem.
Now using a Windows 10 desktop and the On-line Create Agent.
Unless I reload the Arduino Create Agent, I always get the 'No Plug-In Connection' error message, please see screen capture.  Device manager recognizes the Arduino Uno and assigns COM3 to the USB connection, please see screen capture.

what do you mean by reload the Arduino Create Agent ... do you mean that you have to refresh the webpage?

@jsotola, Agent is the locally installed part of the Web IDE. the installation sets it to start automatically at logon. it looks like this failed

Yes, I mean that I have to refresh the Arduino Create Editor each time the computer is rebooted.  Logging onto the computer or into the Arduino WEB IDE does not automatically refresh the Create Agent.  What would cause this to fail the refresh? How can I correct this issue? I am pretty computer savvy but this one is escaping me!

Thank you to all who have suggested corrective action for my posted communication problem.  After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor.  Next I installed the Arduino Create Editor as a fresh/new install.  Magically, all of my communication issues with the Arduino Uno have been corrected.  Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.


text:
Multi-array number generation
This part of my project is very hard for my brain to wrap around and comprehend. But basically I just need to go through every combination. For example:
If I have an array with 255 variables and I need to bruteforce all the combinations by 30's (0, 30, 60, 90) How would I go about doing that in a decently compact form? It's really brain hurting please help a noob out <3
Note: I'm making a universal IR Remote but if by chance I don't have the code then I can just change the mode to brute force it.
volatile uint16_t IRCode[]={384,171,43,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,21,21,64,21,21,21,64,21,64,21,64,21,64,21,64,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,64,21,64,21,21,21,64,21,64,21,64}; // ProntoHex to uint16_t delete first 4 array numbers.
volatile uint16_t MicrosPassed;
volatile uint8_t ArraySeq;
uint8_t LEDState;
uint8_t SetMode=0;

void setup() {
  Config();
  SendIRCode();
}

void loop() {

}

void SendIRCode() {
  if(LEDState==1) {
    TCCR1A&=63;
    LEDState=0;
  } else {
    TCCR1A|=192;
    LEDState=1;
  }
}

void Config() {
  DDRB|=10;
  ICR1=416;
  OCR1A=9983;
  TCCR1A=2;
  TCCR1B=24;
  TCCR1B|=1;
  TIMSK1=1;
}

ISR(TIMER1_OVF_vect) {
  MicrosPassed++;
  if(MicrosPassed==IRCode[ArraySeq]) {
    SendIRCode();
    MicrosPassed=0;
    ArraySeq++;
       }
}

this is a general programming question that is not arduino specific

examine the use of for loops

@jstola it is 100% arduino-uno specific. Config() is for arduino-uno made in the arduino ide. random() is a arduino function. If I did config() on anything but the uno it would most likely not work.

@fman122: your Config function is plain AVR C code. The only Arduino flavor is the fact that you have a setup and loop function rather than a main (or some other entry point) - and you're not using any Arduino functions in there either.

@Mat well I mean if you read the post instead of arguing I was planning on using a arduino function called random(). That's why I mentioned it. Why does everyone try to delete other peoples questions :| I've seen so many great questions on here and people always close them for stupid reasons and assume things about the post even if they are obvious. Also again if I did my specific sketch I would not be able to run it on anything other than a arduino. It makes literally no sense to go to any other forum. Arduino doesn't contain all of c/c++ so it would be dumb to go to another forum asking abou

infrared communication on a arduino uno on a forum about electronics, or programming. But I sha'll try that and see what result I get and update you. ;) HINT: (They will either close it or tell me to go to the arduino stack exchange).

What do you mean by "all the combinations by 30's"? Do you mean any possible combination of 30 elements out of the 255?

Not sure why you doing this? there are library exist that you could use, or learn from. You may want to take a look at Arduino-IRremote which was based on a c-library long existed even before Arduino was invented. Take a look at the IRsendRawDemo example, and the library source code.

In my opinion the question is on topic. It asks for Arduino solution of a problem. and then chrisl's and hcheung's comments apply

@chrisl I meant by counting by 20's. So 20,40,60. I found that you can skio microseconds and just jump and it will most likely work.

@hcheung 1. I get a better grasp learning something through analysis and the inner workings. 2. the project I am working towards can't have a single bug. So I'm keep it simple barebones and tight. Not even an emp will be able to mess with the electronics.

You still didn't really explain what combinations you want to go through. What does counting by 20s mean here (and why now 20s, not 30s like in your question)? Do you want to create an array, where multiples of 20 are randomly stored?


text:
What can I do to optimise this code?
I have optimised it as much as I feel I can and want to know what suggestions you have that could make it more efficient etc.
Note: I know the array goes on forever :)
volatile uint16_t IRCode[]={340,171,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,21,21,64,21,21,21,64,21,64,21,64,21,64,21,64,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,64,21,64,21,21,21,64,21,64,21,64,21,1556,340,86,21,3654}; // ProntoHex to uint16_t delete first 4 array numbers.
volatile uint16_t MicrosPassed;
volatile uint8_t Array_Seq;
uint8_t State;

void setup() {
  Config(); // Config sketch will set working settings for different microcontrollers.
  SendIRCode();
}

void loop() {

}

void SendIRCode() {
  switch(State) {
    case 1:
      TCCR1A&=63; // Opposite of case 0 -193 = 63
      State=0;
      break;

    case 0:
      TCCR1A|=192;
      State=1;
      break;
  }
}

void Config() {
  DDRB|=10;
  ICR1=416;
  OCR1A=9983;
  TCCR1A=2;
  TCCR1B=24;
  TCCR1B|=1;
  TIMSK1=1;
}

ISR(TIMER1_OVF_vect) {
  MicrosPassed++;
  if(MicrosPassed==IRCode[Array_Seq]) {
    SendIRCode();
    MicrosPassed=0;
    Array_Seq++;
       }
}

IRCode[], MicrosPassed, and Array_Seq are only used in the ISR; you could declare them as static in the ISR, IRCode[] could also be const, and no need to declare them as volatile because only the ISR reads/writes them. No idea if this will help the compiler optimising for speed, though.

For what to do you want to optimize? Clean code? Or some meaning of "speed" (which speed)?

convert array to actual bits .. 0 is 21, 21 ... 1 is 21, 64 ... s is  340, 17 - start ... and so on .... the array would be { s, 0, 0, 0, 1, 0 ......} ... you could even store bytes, instead of separate bits

Maybe fix the problem @chrisl mentioned before optimizing your code.

As hinted by chrisl in a comment, there are various criteria you may
want to optimize for: speed, size, readability... Judging from the
current state of this sketch, I would say that your first goal at this
point should be to optimize for readability.
The hardest think to make sense of are most of the plain numbers. When
setting registers that are bit fields, do not use decimal values: use
either hexadecimal or binary. Or, better yet, use the names of the bits.
The avr-libc defines those names, as well as the macro
_BV(bit_position), which expands to (1 << bit_position) and is meant
to be used with those names:
void Config() {
  DDRB   |= _BV(PB1) | _BV(PB3);  // PB1 and PB3 as output
  ICR1    =  416;        // timer period = 417 cycles
  OCR1A   = 9983;        // ???
  TCCR1A  = _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
  TCCR1B  = _BV(WGM12) | _BV(WGM13);  // ...ditto
  TCCR1B |= _BV(CS10);   // clock @ F_CPU
  TIMSK1  = _BV(TOIE1);  // enable TIMER1_OVF interrupt
}

Granted, the bit names are somewhat obscure, but they do make the
program easier to read if you have the datasheet nearby. I do like to
have comments that make the code understandable even without reading the
datasheet.
Note that evaluating those expressions does not make the program any
slower, as they are evaluated at compile time.
When a variable is used in a single function, it is better to define it
in that function. Keeping the definition close to where the variable is
used makes the code more “local” and thus easier to read. Since you want
some of those variables to remember their values across invocations of
the function, give them the static qualifier.
You may not need to optimize this program for speed. There is, however,
a low hanging fruit here: remove the volatile keywords. This keyword
is meant to explicitly disable some compiler optimizations that are
unsafe when a variable is shared between the interrupt and non-interrupt
contexts. None of the variable you use needs this.
If I understood correctly, the function SendIRCode() just toggles a
couple of bits in TCCR1A. You can simplify it to this:
void SendIRCode() {
  TCCR1A ^= _BV(COM1A0) | _BV(COM1A1);  // toggle PWM output on OC1A
}

Finally, there is I believe a bug in this sketch. The variable
Array_Seq is continuously incremented and never reset. The program
will then end up reading past the end of the IRCode array.


text:
ESP8266 always resetting after 65 second of running
I have a simple code where ESP8266 is asking MySQL database about actual state of LED (whether 1 or 0) and when DB has 1 ESP8266 turns LED on... But my problem is after 65-66 seconds of server running is still resetting... The program does what it is supposed to do, but after 65-66 seconds resets and trying to reconnecting to wifi
---- EDIT -----
After some experiments with code I have found, it doesn't matter the running time but, number of loop cycles... Every time no matter on delay or processing speed, it crash after 48 cycles....
.ino code
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

// Replace with your network credentials
const char* ssid     = "XXXX";
const char* password = "XXXX";
const char* host = "http://www.XXXX.XX/arduino_PHP/post_data.php";

// Set web server port number to 80
WiFiServer server(80);
HTTPClient http;

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;
byte green, red= 0;

void setup() {
 Serial.begin(115200);
 // Initialize the output variables as outputs
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
 delay(1000);
 pinMode(output5, OUTPUT);
 pinMode(output4, OUTPUT);
 // Set outputs to LOW
 digitalWrite(output5, LOW);
 digitalWrite(output4, LOW);

 // Connect to Wi-Fi network with SSID and password
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 // Print local IP address and start web server
 Serial.println("");
 Serial.println("WiFi connected.");
 Serial.println("IP address: ");
 Serial.println(WiFi.localIP());
 server.begin();
}

void loop(){
delay(500);
DB_state("Green",green);
DB_state("Red",red);
delay(500);
}

void DB_state(String component,int state){
 String postData =("component=" + String(component) + "&state=" + String(state));
 Serial.println(postData);
  http.begin("http://www.XXXX.XX/arduino_PHP/DB_state.php");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
 http.POST(postData);   //Send the request
 String payload = http.getString();    //Get the response payload
 Serial.println(payload);
 http.end();  //Close connection
 state_LED(payload,component);
 }

void state_LED(String str, String led){
 int x;
   if (led== "Green") {
     x = 4;}
   else if (led== "Red") {
      x = 5;}
   if (str == "State: 1") {
     digitalWrite(x, HIGH);}
   else if (str == "State: 0") {
     digitalWrite(x, LOW);}
 }

ESP8266 Stack debug
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads
PC: 0x4020744a: ClientContext::state() const at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
EXCVADDR: 0x00000184

Decoding stack results
0x40203f10: HardwareSerial::write(unsigned char const*, unsigned int) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 164
0x40203f1c: HardwareSerial::write(unsigned char const*, unsigned int) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 165
0x40207512: HTTPClient::connected() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 475
0x40202d24: HTTPClient::disconnect(bool) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 434
0x40203ac8: HTTPClient::end() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x402012ba: DB_State(String, int) at C:\Users\XXXX\Documents\Arduino\ESP8266_php_DB_control/ESP8266_php_DB_control.ino line 87
0x40201334: loop() at C:\Users\XXXX\Documents\Arduino\ESP8266_php_DB_control/ESP8266_php_DB_control.ino line 73
0x40100175: esp_schedule() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 125
0x40205628: loop_wrapper() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 197

Thanks for any advice

So it might be a memory issue like a leak or resource allocation problem.

I thought so, but how fix it?

Before you can fix it, you need to identify it. Read the documentation of WiFiServer and HTTPClient, use your web search skills on the detailed error message of "exception 28", and so on. Check your findings and assumptions with test programs; for example, call http.POST() twice in DB_state() and count the numbers of loops.

as first I would stop using String

Why? And how you replace it?

@Juraj pozdravujem slovenského brata v programovaní :D :D :D

I don't know how, but finally I have found working solution... I have add HTTPClient http; at top of function and it works...
void DB_state(String component,int state){
HTTPClient http; // THIS IS ADDED
 String postData =("component=" + String(component) + "&state=" + String(state));
 Serial.println(postData);
  http.begin("http://www.XXXX.XX/arduino_PHP/DB_state.php");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
 http.POST(postData);   //Send the request
 String payload = http.getString();    //Get the response payload
 Serial.println(payload);
 http.end();  //Close connection
 state_LED(payload,component);
 }

Can anyone explain me how it's possible? Because I don't fully understand this procedure.

You now construct and destruct the HTTPClient object in that scope each time, as C++ specifies. Presumably the global one leaks some sort of resource, but I can only speculate on that front.

Sorry, i don't understand. Could you be more simlier?

I can't break this down any further in the space provided to me by a comment. I suggest taking a tutorial on C++ that covers objects, constructors, destructors, and such, which will provide this info in a far cleaner way. But basically, instead of having one HTTPClient for the lifetime of the program, you create a new HTTPClient and clean it up after each request -- This makes sense intuitively, but I don't know the internals of HTTPClient enough to know why it happens to eventually crash if you reuse the same instance over and over again.

https://github.com/esp8266/Arduino/issues/7613#issuecomment-700782051


text:
servo acting weirdly
I have bought two original TowerPro MG966R 360 degree continuos rotation Hi-torq digital servos.
Expected results :

90       deg -- no rotation
90 - 0   deg -- speeding up to one side
90 - 180 deg -- speeding up to the other side

Real results :

When I am sending 50-90 degrees PWM, they behave like standard (non-continuos) servos and turn in 50-90 degree angle.
Bellow 50 there is small speedup, then continuos rotation at max speed to one side.
Above 90 there is continuos rotation at max speed to the other side.

I am using standard Arduino Servo library,
servo has external 2A power and
all grounds (servo, arduino, power) are connected together.
Both new servos behave same, so I assume fault is on my side (software).
Same code and wiring works fine with other (cheap,copycat) servo I have.
May I ask for some pointer to what am I doing wrong?
Thanks
My test code :
    // 9 - servo pin
    // 2 - pot pin

    #include <Servo.h>

    Servo srv;

    void setup(){
        srv.attach(9);
    }
    void loop(){
        //~ srv.write(map(analogRead(2),0,1023,50,90));
        srv.write(map(analogRead(2),0,1023,0,180));
        delay(10);
    }

Bought here : ebay
Manufacturer page : here

there is no reason to use the map function or the analogRead function ... use minimal code when debugging

What @jsotola said, and: you are updating the servo signal at a higher rate than its normal PWM frequency of 50Hz; anything could happen. Try a longer delay.

Ok, thanks for corrections .. I've tried simpler code and longer delays (20,50,2000) but it didn't help - same result.

Hm. Weird. Also weird: the Towerpro MG966R product video at the bottom of this page: http://www.towerpro.com.tw/product/mg995-robot-servo-360-180-rotation/ shows about the same behaviour you describe, but I can't imagine these servos in the video are "working as intended" if they are supposed to be continuous rotation servos.

I've contacted manufacturer and linked this question

looks like a soft start function of some kind

@Jirka-Justra: Any answers yet from the manufacturer?

Guy e-mailed me 'I will get back to you' .. so I am currently on hold.

update : I've send kind reminder; response was that they arrange replacement for me .. hmm - interesting, but ok with me so far

update : I've got new set .. it rotate both side and continuously, but speed is constant :/ ... will communicate with them more - build quality is great as usual