text:
On an esp8266 what is faster, 64-bit math or float math?
I need to do some math with vars from an attitude sensor (acclerometers and gyroscopes) on an esp8266. int32_t math with those vars does not have enough range and the float math operations are abyssmally slow.
I'm hoping to use a fixed-point format with 24 bits on the left of the decimal point and 8 bits on the right side.  So a number would be stored in a int32_t as 0xffffff.ff.  A typical operation would be a multiply like ((i64) x * y) >> 24).
So 64-bit math is needed. Would this be significantly slower than a float multiply?

do 10,000 operations of each ... time the results

By the way, if I was downvoted because the answer seemed obvious then they should read the rest of this thread.

If you need fast single-precision float operations, consider the ESP32 instead of the ESP8266.  It clocks in at 240MHz instead of 160MHz, has two cores, and has hardware single-precision FPU.  Especially if you want to use the WiFi or anything else that depends on interrupts you can do your DSP on the second core and not have to worry about your calculations getting sidelined by whatever else is going on in your main loop.

Yes, I've used the esp32 before with this attitude chip.  I just made every var a float and it breezed along.  But this is for a cheap toy and the extra $2 for the esp32 is too much.

Calculating the relative performance of 64 bit integer versus floating point multiplication is a little more difficult than it would appear.
It's easy to time a loop that does thousands of calculations, but unless you do something with the result the compiler will happily optimize them away. It's tempting to multiply constants, but the compiler will also happily optimize that away.
To keep the code as simple as possible and not introduce anything into the loop that would take more time, you need to disable or bypass the compiler's optimizations. An easy way to do that is to use the volatile modifier on the variables. volatile tells the compiler that it can't assume the variable hasn't changed, so the compiler will disable optimizations like caching the variable in a register or noticing that the same calculation is being done over and over again and just doing it once.
Using this technique, with a couple of tests to verify that the compiler would perform optimizations that interfere with timing, I get these results:
non-volatile uint32_t microseconds 1
constants uint32_t microseconds 5
uint16_t microseconds 162513
uint32_t microseconds 137513
uint64_t microseconds 1287533
int16_t microseconds 337513
int32_t microseconds 300023
int64_t microseconds 1287513
float  microseconds 912529

64 bit unsigned or signed multiplication takes about 1.4x the time as floating point multiplication.
The first test verified that non-volatile variables are optimized out. The second test verified that multiplying constants is also optimized out.
Turning off Wifi also helps keep test results consistent.
#include <Arduino.h>

#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif

#define TIMES_TO_LOOP 1000000

volatile uint16_t ux16, uy16, uresult16;
volatile uint32_t ux32, uy32, uresult32;
volatile uint64_t ux64, uy64, uresult64;

volatile int16_t x16, y16, result16;
volatile int32_t x32, y32, result32;
volatile int64_t x64, y64, result64;

volatile float xf, yf, resultf;

uint32_t x32n, y32n, result32n;

uint16_t seed16() {
  return random(0, 0xffff);
}

uint32_t seed32() {
  return random(0, 0xffffffff);
}

uint64_t seed64() {
  return seed32();
}

float seedfloat() {
  float x, y;

  x = seed32();
  y = seed32();

  return x / y;
}

void setup() {
  uint32_t i;
  uint64_t micros_start, micros_end;

  Serial.begin(115200);
  Serial.println("hello world");

  WiFi.mode( WIFI_OFF );

  delay(1000);

  x32n = seed32();
  y32n = seed32();

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result32n = x32n * y32n;
  micros_end = micros();

  Serial.print("non-volatile uint32_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result32n = 540000 * 15;
  micros_end = micros();

  Serial.print("constants uint32_t microseconds ");
  Serial.println(micros_end - micros_start);

  ux16 = seed16();
  uy16 = seed16();
  x16 = ux16;
  y16 = uy16;

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    uresult16 = ux16 * uy16;
  micros_end = micros();

  Serial.print("uint16_t microseconds ");
  Serial.println(micros_end - micros_start);

  ux32 = seed32();
  uy32 = seed32();
  x32 = ux32;
  y32 = uy32;

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    uresult32 = ux32 * uy32;
  micros_end = micros();

  Serial.print("uint32_t microseconds ");
  Serial.println(micros_end - micros_start);

  ux64 = seed64();
  uy64 = seed64();
  x64 = ux64;
  y64 = uy64;

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    uresult64 = ux64 * uy64;
  micros_end = micros();

  Serial.print("uint64_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result16 = x16 * y16;
  micros_end = micros();

  Serial.print("int16_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result32 = x32 * y32;
  micros_end = micros();

  Serial.print("int32_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result64 = x64 * y64;
  micros_end = micros();

  Serial.print("int64_t microseconds ");
  Serial.println(micros_end - micros_start);

  xf = seedfloat();
  yf = seedfloat();

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    resultf = xf * yf;
  micros_end = micros();

  Serial.print("float  microseconds ");
  Serial.println(micros_end - micros_start);
}

void loop() {
}

I ran your code and the results matched mine. Float is faster than 64-bit.
int64_t microseconds 650010
float microseconds 456266

Do note that 64 x 64 -> 64 bit multiply is typically 4x slower than the 32 x 32 -> 64 bit multiply that was in the original question.

I don't doubt this, but it is kind of surprising. For example: why is int16_t so slow compared to uint16_t? Multiplication is the same operation for those two types. Similarly for int32_t and uint32_t. Really bizarre. Is it possible that volatile is a bit too pessimistic in the sense that it also prevents strength reduction optimizations, whereas in a real app those would be available?

@jpa -- If you look closely you will see the muliplication is 64x64-bit, not 32x32.

@mark-hahn Then you have a different way of implementing fixed point math than I'm used to. C compilers are smart enough to know that if you have a 32-bit variable and cast it to 64 bits just before multiplication, the upper bits are zero and don't need to be handled.

OK, I took the trouble to code fixed-point routines and test them.  Here is the code ...

// fixed-point routines for 20 bit integer / 12-bit fraction
// format 0xfffff.fff, max value is +-524288.9998

#define FP_I 20     // integer bits,  e.g. 0xfffff.0
#define FP_F 12     // fraction bits, e.g. 0x0.fff
#define fpMul(_x,_y) ( (i32)( ((i64) _x * _y) >> FP_F) )
#define fpDiv(_x,_y) ( (i32)(  (((i64) _x) <<   32)      \
                             / (((i64) _y) >> FP_I) ) )
#define decToFp(_dec) ((i32) (_dec * 4096))   // e.g. decToFp(-1.2)
#define fpToI32(_fp)  ((i32) (_fp  / 4096))

I did a 1000 loops and used the loop counter as the operation argument.  So each loop was one operation plus one floating-point increment.  I did this for fixed-point multiply, floating-point multiply, fixed-point divide, and floating-point divide.
The results were shocking.  The fixed-point multiply took almost exactly the same time as the floating-point. The fixed-point divide took 60% longer than the floating-point.  I went over my code and tried everything I could think of.  I built it in debug and release mode.  I tried 80MHz and 160MHz.  I found floating-point speeds on the web and my floating-point tests closely matched those.
I am at a loss as to how the 64-bit math could be slower than the floating-point.  Both are implemented in software.  I'm sure the floating-point is highly optimized with some tricks and coded in machine language.  But my fixed-point code is just shifts and 64-bit multiply/divides.  I don't think there are any tricks that could be used for it.
At least this makes the decision easy. I guess I'll use floating-point as sparingly as possible and cross my fingers that I can get my app to work fast enough.
I hope this is helpful to some passing-by googlers.  I couldn't find anything when I googled it.

I didn't turn off wifi but I did use all the other recommendations you have here. I have played with this all day and it was hard to get right but I'm pretty confident in the results. Especially since my float results matched the results on the web from several other people who did a lot of work on this stuff. If anyone wants to insert my fixed-point code into their speed tests then let me know if your findings match mine. I've already burned up more time than I should have on this.

Hey, this is not a forum where we play ping pong with answers. When you write an answer it should contain a solution to the problem stated in the question. No back and forth please. Just questions and self contained answers. If you think you solved your own problem you should merge all your answers. If not, then you can add the additional info to your question. And please make sure that others can still understamd your question/answer, so they too can learn from it

And, welcome to Arduino Stack Exchange! Thanks for the update.

I don't understand.  Every forum I've used before was all ping-pong.  Where should we be having this discussion?

Have you considered implementing 32-bit multiplication as multiplications of 2-digit base 2^16 numbers? Something like this. It may be faster than converting both 32-bit numbers to 64-bit numbers before multiplying. Signed multiplication is also possible with two extra conditionals, if that's really important (I think it's not?).

...and if multiplying two 30-bit numbers to get a 60-bit number is enough for your application, you can drop the 4 cheap multiplies from my previous link to just 3 using the Karatsuba multiplication algorithm.

@mark-hahn: SE isn't a forum, it's a Q&A site. You'll note that the interface is structured differently, and the social conventions differ too. The site tour highlights some of the differences, as does our help center page on how to write a good answer. Anyway, for issues that do need some back-and-forth discussion, the appropriate place for that is either here in the comments or (especially if the discussion gets very long or drifts off topic) in chat.

BTW, your fpDiv implementation looks a bit wonky to me: e.g. fpDiv(decToFp(10), decToFp(2)) gives a division by zero error. Normally you'd want to do the right shift after the division, I think. (Also, I don't know if that's the case on the esp8266, but at least for some platforms / compilers / optimization settings, setting FP_F to a multiple of the/a "native" word size like 8, 16 or 32 bits might yield somewhat faster code. It could at least be worth a try.)

Just use the CCOUNT register in the xtensa CPU core to measure itself.


text:
Turn on a relay for a specified amount of time after the press of a momentary switch
This is my first time programming an Arduino. I have a small brushed DC motor that I want to control using a 5V relay, which in turn is connected and controlled by the Arduino.
What I would like to do is this: Command the relay to turn ON for a specified amount of time, after pressing a momentary push button, then turn OFF once the specified amount of time has passed.
Once that's done, I would like it to reset itself, so to speak, so if I press the push button again it does the same thing.
My current script is:
const int relay = 8; //motor relay
const int button = 9; //momentary trigger switch

int status = true;

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

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(button) == true) {
    status = !status;
    digitalWrite(relay, status);
  } while (digitalRead(button) == true);
  delay(500);
}

What it currently does is: if I push the push button once, it will command the relay ON until I press the button again, which then turns the relay OFF until further input.
I know that I should use the millis() function for the timer functionality, but for the life of me I haven't been able to figure out how to make it work thus far.
Any suggestions?

I suggest to ask the IDE to auto-format your code (Ctrl-T). Maybe you could see that what you wrote doesn't match your intention.

Yes I adapted some code I found online in order to test if everything was setup correctly hardware wise. I now want to add the functionality I described in my original post but I can't figure out how. I have tried to adapt code from similar use cases to mine but I just can't get them to work properly, if at all.

your code is if button is pressed then change the state of the relay, and if the button continues to be pressed, then wait .5 sec .... you want if button is pressed then turn on relay, wait .5 sec, turn off relay

Okay, so the code probably needs to be scrapped. I know that I must do the following:

De bounce the button
Use millis() preferably to time the relay, so it can be turned off after a specific amount of time

However, I have been unable to figure out how.

there is no need to debounce because the first contact closure results in a 500 ms delay ... the contact bounce will never get detected ... just change the few lines of code inside the if block

I have been unable to figure out how ... it is literally spelled out in english ... if button is pressed then turn on relay, wait .5 sec, turn off relay ... you already have all the necessary command lines ... just rearrange them

source: Stack Exchange

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

sort: votes


text:
ESP32 board package takes up a lot of HDD space
I recently installed ESP32 to the arduino IDE and have just discovered it takes up 5.4GB on my HDD!  I know it has to cover a lot of different boards but is there any option to only load in the boards I want - or delete others ?  I just want the ESP Deb Module. My system only has 64GB and Windows takes up a lot of that.

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


text:
Is it wise to use analog input pins to read digital buttons?
I am thinking about building a circuit that is literally going to take 11 of the 14 digital pins of an UNO to communicate with an SD card and an external EEPROM chip (EEPROM programmer).
Using 4 shift registers and the SD card, I will have 1 digital pin left.  Well, I'm also reserving pins 0/1 for serial communication.
Anyway, I need to read some external buttons and I have the 6 analog pins that I haven't touched.
I will only need about 4-5 push buttons in my design so they should fit nicely on A0+.
So, my question is, will I run into any issues doing this?  Or, are the analog inputs better left for true analog reading?
Thanks.

Possible duplicate: http://arduino.stackexchange.com/questions/4011/can-i-specify-that-analog-pins-be-used-for-digital-output

The Analog pins are essentially identical in functionality to digital pins when used as digital I/O.
If desired you could "be clever" and use an analog input in analog mode to read multiple keys using one pin. eg using 10k, 22k, 39k, 82k, 150k in series with 5 buttons from V+ to pin and a say 4k7 to ground would result in 5 voltages which were easily distinguished using an analog read. This is a very very old technique indeed and allows far more than 5 keys on one input pin. THere are limitations which can be discussed if required.
R1 ... R5 correspond to buttons 1...5
Vout = V+ x Rb / (Rb + Rbutton)
Example only
Rb = 39k
R1 = 10k
R2 = 22k
R3 = 39k
R4 = 82k
R5 = 150k
Gives

The % of V+ in column 2 when a button is pressed.
The voltage in column 3 with V+ = 5V

Delta-V is the difference between that key and the one below - very ample clearance.

Awesome answer.  Thanks!  BTW, I didn't even think about using the analog pins to read multiple buttons that way.  Thanks for the tip too.

Can this method be extended to detect multiple buttons pressed at the same time?

@LoganBlades Yes - within limits. If you think of button resistors as ~= injecting current into the lower resistor you'll see I have chosen values that are in an approximate binary ratio subject to std E12 values. ie I aimed at 10 20 40 80 160 and then took closest E12 value. So if you take the inverses it shows ABOUT how much they will pull a low value resistor up by - I say low value as that better approximates a current source. So contributions are in inverse R order of about 16 8 4 2 1 current units. So if you press B1 + B3 you get 20 current units, B3 + B5 = 3 etc. ...

... The 3CU of B3 + B5 lies between the 4 CU of B3 and the 2 CU of B4 so you need enough resolution to distinguish between them. If you used the resistors to control a "proper" current source and binary weight the resistors you get 2N^N levels for N buttons keys. So 8 buttons gives 256 levels AND with a 10 bit ADC vyou notionally have 2 bits between each level. That would almost certainly be tighter than you could easily manage in practice - you'd need 0.1% resistors and a 0.1% accurate current source. 6 buttons is probably doable. Easily experimented with using eg an Excel spreadsheet.

If you have no use for analog pins there is no problem. A5/A6 are used for I²C (on the Uno).

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


text:
How can I send data to many IC's without using tons of shift registers?
I'm building an audio circuit that will play VGM files (Video Game Music).
I have it working with two different "vintage" IC's such as the SN76489 and the AY-3-8912.
Currently, my design is using an Arduino Micro and two shift registers for the data buses and direct pins for the control pins on the audio IC's.
On average, an audio IC has 8 pins for the data bus and 4 pins for the control or address bus.  This varies per IC.  Some might be 3, some 4, some 6, etc.
Bottom line, even with the 20 IO pins on the Arduino, I will quickly run out of pins.  I thought about serializing many shift registers and basically pass 64 or 128 bit numbers to spread out to the multiple IC's but this sounds ugly.
I'd like to be able to support maybe 6 IC's which could be 60-80 pins.
I also have an Arduino DUE which has many more IO pins.  But then I have to deal with the 3.3v limit and I only have 4 level shifters (16 pins).
Any suggestions on how to handle this?
Thanks.

Get a ATmega128A and learn how to do MMIO.

A quick search reveals that MMIO "seems" to be very similar to how the Apple IIe handled the 7 slots.  Each slot has a /IOSEL pin that is normally HIGH.  When you access an address like $CNXX where N is the slot number, /IOSEL goes low and the slot becomes active.  Each slot has a 16bit address bus and 8bit data bus.  Is MMIO a similar technique?  So basically all IC's would be on the same address/data bus but different addresses would activate them separately?  If so, where can I find some info for doing this with Arduino?

Also, I should note that many of the IC's would not need to be disabled as they could be playing a note at the time.  So, I'm thinking that they all would share a common data bus.  Then, the address bus would be mapped to each IC so that certain ranges would turn the data bus on/off for them.  Would this be the job of an octal bus transceiver?

Neither the Atmega328P, ATmega1280, nor ATmega2560 have an external memory bus, so you'd have to look at something like the ATmega64A or ATmega128A. Many chips have a "select" or "enable" line as well as their data and command buses; if all of yours do then all you need to do is make sure that only one chip is enabled per address or range of addresses.

Thanks, that was an initial thought I had but I'm not sure yet how each IC will respond to being disabled while it's playing a note.  The AY-3-8912, for example, can be set to INACTIVE so I will have to see what that does.  I think it puts the address/data bus in high impedance mode.  But I don't know, yet, what that will do to the note(s) playing.

Looking at the datasheet, I don't believe that it will affect the notes in any way.

There are other ways,but for a brute force many pin driver solution:
Back at the beginning of time when steam driven IC's were all the vogue there was the awesome MM5450.  40 pin DIP. 34 on/off outputs. 3 pin control. Or the really keen could do it with 1` pin control and some basic RC timing. I was. I did.
Its day has passed. but, fortunately. neither Micrel or Digikey know this.
MM5450 datasheet
In stock Digikey $5.46/1
It's a very benign beat to drive once you get to know it. There is no reset (inless you buy bare dies) so you have to start off getting it synchronised  - it's not hard, just not quite usual. Works well.
For single GPIO pin control the pin acts as data out and clock with some RC timing.
Fot ICs with clock/data/load you can do all 3 with RC timing on one pin.
And there is a 44 pin PLCC pkg version available.

AND!
SN74LS673 16 bit SR, 24 pins
http://www.ti.com/product/sn74ls673
ICM7243
http://www.ebay.com/itm/ICM7243BIPL-HARRIS-40-Pin-DIP-LED-DISPLAY-DRIVER-ICM7243-7243A-/390402848376
And others
http://www.ebay.tv/sch/i.html?_sop=7&_nkw=led+driver+ic&_frs=1

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


text:
How can I run two Arduinos in sync for video generation?
I was thinking about building a video circuit that uses two Arduinos (maybe more) to generate video using NTSC and the AD725.  Although, VGA might be nice if possible.
Anyway, the idea is to use one Arduino as the background layer and the other one as the sprite layer (overlay).
Then, instead of masking the sprite data and having more cpu time, I was thinking of running the signals through a mux.  So that when drawing background data and no sprites (per scanline) then pipe the signal to the AD725.  But when there is a sprite mid-line, then the >0v signal of the sprite Arduino would cause the mux to pipe its contents through to the AD725.
Or, something similar.
I believe many arcade boards from the 80's did this.  Many of them had entire "sprite boards" attached and the signals would mix.  Each layer would have it's own RAM and not be aware of the other layer.
But to do this, I would have to keep the Arduinos sync'd perfectly.
So that's my question.  How I can do this?
Oh, my Arduino of choice in the beginning would be the UNO but I have others (DUE, Teensy3.1, etc.) if that would be a better fit.
Thanks.

I would discourage using arduino for anything with video.
A raspberry Pi comes with a built-on HDMI-out aswell as GPIO pins.

Not really interested in using the RPi for this.  But thanks anyway.

Arduinos are great for many things, and I think the idea of synchronizing two or more Arduinos might have several applications.
However, if I wanted to generated VGA or NTSC video, I would look at the Parallax Propeller as another option.
Many people use the Parallax Propeller to produce VGA video, keeping its 8 processors working in parallel.

"Hive retro computer"
"containing a total of 24 RISC processors, VGA graphics, stereo sound, ...
uses all DIP and through hole components."
"Signal processing module using Parallax's propeller chip",
apparently can do "video in ... to do video-overlay then send it to video out."
Dangerous prototypes has a long list of projects using the Parallax Propeller.
"Dangerous Prototypes: Parallax Propeller"
"Pocket Mini Computer on Parallax Propeller" includes VGA output
"Propellerpowered Forums" includes many people discussing video output on the Parallax Propeller.
etc.

I decided on the Propeller.  It's almost like it was made for this task.  :-)

I would take a look at MREtv which seems to promise all that you want to do, with just one arduino. This might not be the answer you're looking for, but getting threads to sync is a pain in the rear end, see this for explanation of why threads are a pain.
Now back on topic, it seems like MRETV might off what you want to do, and it can do some pretty impressive things from what I read in the arduino. You might need to modify the library a bit, but it offers already implemented encoding, so that is a plus.
http://www.instructables.com/id/MRETV-Video-Stereo-Sound-and-much-more-from-a-s/

I tried to get that MRETV to work.  Followed the instructions to the letter and it wouldn't even compile.  This is on a fresh install of the Arduino IDE (newest version).

@cbmeeks Could you give me details of what the IDE spat out when it failed to compile? Are you on windows? What was the actual error, the ide couldn't find a file?

I don't have the exact error in front of me at the moment.  But I'm on a Mac and the error was something along the lines of "must define const sound" or something like that.

Just a thought, you could try synchronizing micros() / millis() between Arduinos... [ https://aaka.sh/patel/2013/12/23/synchronizing-micros-millis-arduino/ ]
Over time you could set instructions/commands to execute at certain time intervals on target arduinos using something as simple as a 2 wire serial setup  [ http://arduino.cc/en/Tutorial/MasterReader ]

You would need to use interrupts on the "sprite arduinos" to get the timing very exact - the "background" arduino would need to send signals sync signals (horizontal and vertical) to the sprite arduinos. The sprite arduinos would then need to keep track of which line it is on, and time exactly how far along the line it is. You will need a circuit to either allow the incoming signal through (I believe the arduino will be too slow to pass it read it, then write it);
alternatively, have multiple (still synchronized) sources, each indicating if they want to be on the screen; then one that takes the "I want to be on the screen" signals, make a decision, and connect the appropriate one (via a transistor).
A basic tutorial on TV out is found at:
http://playground.arduino.cc/Main/TVout


text:
Driving APA102C strips from Mega 2560
I have written (cobbled together from code snippets) an Arduino program that pushes various patterns down 160 APA102C LED strips (5). I originally was using a 5V 40A power supply and everything worked peachy. That was when the length from the clock and data pins was maybe 6-8 inches. Now I am try to get ready for a XMAS parade and attaching 100 LED strips. I have the power but the data and clock pins aren't getting to the strips. Is there some quick and dirty (not a real electronics guy here, just a code pusher) method to get signals out to the strips, maybe 6 feet? I would greatly appreciate any help I could get and I'm sure the kiddies would have Santa throw some extra goodies your way if I could get this figured out. I've got like 10 days.....YIKES!!!!
Thanks so much!!!!
And Happy Holidays
Joe B

For a quick and dirty way you could cut a few LEDs from your strip, so that you have a number of single LEDs. Then you can place one LED after X feet of cable. Each LED receives its own data and outputs the signal for the next LED. So the signal after an LED is of the same quality as of the first signal. At least that is what can be done with other similar RGB LED strips. I would bet, that this is also the case for this type.
Before wiring everything up you should probably experiment a bit with the cable length. Test how long you can make the cable until you see problems. Then make the cables inbetween the LEDs shorter than that.
If you don't want these intermediate LEDs to light up, you can set them to off in your program.
Another - not so quick and dirty - way would be to put one microcontroller near the start of each cluster of strips (where one or multiple or all strips start) and let them communicate with a master microcontroller using an interface for longer distances (like RS485).
Depending on your situation the quick and dirty method might be enough.

Well then again  there is always having a FAULTY strip!!!. I was working on the base code and hardware configuration and never thought to try one of the other strips (I do after all have 5 of them). I just happened to grab one of the other strips and BOOM, all was well. At least to a point. It looks like I can run 3 or 4 strips at the same time from one Arduino (Mega 2560) if I crank the brightness factor down and limit the strips to 120 LEDs. Since this is a nighttime parade. I'll still be bright enough. I just HATE cutting the extra 40 LEDS off the strip.

At one point I was looking at using multiple Arduino Unos. Problem is they're the cheapo chinese ones with the 240 chips and I have a hell of a time communicating with them. Was going to use fiber optic (which I also play around with) and use them to communicate with each other. THANKS SO MUCH FOR THE RESPONSE!!!!! Of the 5 boards I posted to yours was the only answer I got. On top of all this silliness I also got a granddaughter on Monday afternoon. Now all I need are my new soldering tips.... THANKS AGAIN, Best of the Holidays to you and your family, STAY SAFE

@joebataz Why do you need to crank the brightness down? Are you providing the strips with power through the Arduino? If yes, then DON'T! You can easily burn the voltage regulator or the protection diode. Instead connect the strips power lines directly to the power supply (not through the Arduino). The Arduino can be connected in parallel.

Hey Chris,
I have MASSIVE power supplies 40A at 5V unfortunately my vehicle which has a 110V outlet only puts out about 2.5A so I am running the strips thru a 5V 5A supply. I got 3 strips (160 LEDs) running at acceptable brightness. The Arduino itself barely will power 1 strip, found that out years ago when I was developing the system. Here is what the strips look like at 200 LEDs per strip. I was a DJ/VJ until I got hurt.
https://www.youtube.com/watch?v=g7qDTtEqrSI
Video was shot in my very small office. Much more impressive in a club environment. Thanks again, Joe B

Ah ok, just wanted to be sure. You can also use the big power supply. The important measure here is power in Watts. 40A at 5V are 200W (current multiplied by voltage). 2.5A at 110V is 275W, so enough for your big power supply with some headroom for losses


text:
ESP Sim800l Firebase
So, I'm trying to send data from ESP boards- 32 and 8266 using sim800l module to firebase.
But I'm getting HTTP not connected error. I tried to search web but it seems that firebase changed something recently and the ways previously used cant be used. So anyone who has recently done that please help. P.S I'm considerably new to this.
Project - So to give you idea I'm trying to make a Vehicle GPS tracking system which would send data first to firebase using Sim800l.
My Code -
#define TINY_GSM_MODEM_SIM800

#define TINY_GSM_RX_BUFFER 256

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
#include <TinyGPS++.h> //https://github.com/mikalhart/TinyGPSPlus
#include <TinyGsmClient.h> //https://github.com/vshymanskyy/TinyGSM
#include <SoftwareSerial.h>
#include <ArduinoHttpClient.h> //https://github.com/arduino-libraries/ArduinoHttpClient
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
const char FIREBASE_HOST[]  = "vehicle-tracking-4a76d-default-rtdb.firebaseio.com";
const String FIREBASE_AUTH  = "6NGxNkNWf2inWa1LrdktCtq4************";
const String FIREBASE_PATH  = "/";
const int SSL_PORT          = 443;
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
// Your GPRS credentials
// Leave empty, if missing user or pass
char apn[]  = "airtelgprs.com";
char user[] = "";
char pass[] = "";
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
//GSM Module TX pin to NodeMCU D3
//GSM Module RX pin to NodeMCU D4
#define rxGSM 0 //D3
#define txGSM 4 //D4
SoftwareSerial sim800(rxGSM, txGSM);
TinyGsm modem(sim800);
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
//GPS Module TX pin to NodeMCU D1
//GPS Module RX pin to NodeMCU D2
#define rxGPS 5 //D1
#define txGPS 4 //D2
SoftwareSerial neogps(rxGPS, txGPS);
TinyGPSPlus gps;
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
TinyGsmClientSecure client1(modem);
HttpClient http_client = HttpClient(client1, FIREBASE_HOST, SSL_PORT);
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

unsigned long previousMillis = 0;
long interval = 10000;

//**************************************************************************************************
void setup() {
  Serial.begin(115200);
  Serial.println("NodeMCU serial initialize");

  sim800.begin(9600);
  Serial.println("SIM800L serial initialize");

  neogps.begin(9600);
  Serial.println("neogps serial initialize");
  delay(3000);

  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  //Restart takes quite some time
  //To skip it, call init() instead of restart()
  Serial.println("Initializing modem...");
  modem.restart();
  String modemInfo = modem.getModemInfo();
  Serial.print("Modem: ");
  Serial.println(modemInfo);
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  // Unlock your SIM card with a PIN
  //modem.simUnlock("1234");

  http_client.setHttpResponseTimeout(90 * 1000); //^0 secs timeout
}
//**************************************************************************************************

//**************************************************************************************************
void loop() {
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  //Restart takes quite some time
  //To skip it, call init() instead of restart()
  //Serial.println("Initializing modem...");
  //modem.init();
  //String modemInfo = modem.getModemInfo();
  //Serial.print("Modem: ");
  //Serial.println(modemInfo);
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  //  Serial.print(F("Waiting for network..."));
  //  if (!modem.waitForNetwork()) {
  //    Serial.println(" fail");
  //    delay(1000);
  //    return;
  //  }
  Serial.println(" OK");
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  //  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  //  Serial.print(F("Connecting to "));
  //  Serial.print(apn);
  //  if (!modem.gprsConnect(apn, user, pass)) {
  //    Serial.println(" fail");
  //    delay(1000);
  //    return;
  //  }
  //  Serial.println(" OK");
  sim800.listen();
  sim800.println('AT+SAPBR=3,1,"Contype","GPRS"');
  sim800.println('AT+CSTT="airtelgprs.com","",""');
  sim800.println("AT+SAPBR=1,1");
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  http_client.connect(FIREBASE_HOST, SSL_PORT);

  //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
  while (true) {
    if (!http_client.connected()) {
      Serial.println();
      http_client.stop();// Shutdown
      Serial.println("HTTP  not connect");
      break;
    }
    else {
      gps_loop();
    }
  }
  //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
}
//**************************************************************************************************

//**************************************************************************************************
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http) {
  String response;
  int statusCode = 0;
  http->connectionKeepAlive(); // Currently, this is needed for HTTPS

  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  String url;
  if (path[0] != '/') {
    url = "/";
  }
  url += path + ".json";
  url += "?auth=" + FIREBASE_AUTH;
  Serial.print("POST:");
  Serial.println(url);
  Serial.print("Data:");
  Serial.println(data);
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  String contentType = "application/json";
  http->put(url, contentType, data);

  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  // read the status code and body of the response
  //statusCode-200 (OK) | statusCode -3 (TimeOut)
  statusCode = http->responseStatusCode();
  Serial.print("Status code: ");
  Serial.println(statusCode);
  response = http->responseBody();
  Serial.print("Response: ");
  Serial.println(response);
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  if (!http->connected()) {
    Serial.println();
    http->stop();// Shutdown
    Serial.println("HTTP POST disconnected");
  }
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
//**************************************************************************************************

//**************************************************************************************************
void gps_loop()
{
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  //Can take up to 60 seconds
  boolean newData = false;
  for (unsigned long start = millis(); millis() - start < 2000;) {
    while (neogps.available()) {
      if (gps.encode(neogps.read())) {
        newData = true;
        break;
      }
    }
  }
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
  //If newData is true
  if (true) {
    newData = false;

    String latitude, longitude;
    //float altitude;
    //unsigned long date, time, speed, satellites;

    latitude = String(gps.location.lat(), 6); // Latitude in degrees (double)
    longitude = String(gps.location.lng(), 6); // Longitude in degrees (double)

    //altitude = gps.altitude.meters(); // Altitude in meters (double)
    //date = gps.date.value(); // Raw date in DDMMYY format (u32)
    //time = gps.time.value(); // Raw time in HHMMSSCC format (u32)
    //speed = gps.speed.kmph();

    Serial.print("Latitude= ");
    Serial.print(latitude);
    Serial.print(" Longitude= ");
    Serial.println(longitude);

    String gpsData = "{";
    gpsData += "\"lat\":" + latitude + ",";
    gpsData += "\"lng\":" + longitude + "";
    gpsData += "}";

    //PUT   Write or replace data to a defined path, like messages/users/user1/<data>
    //PATCH   Update some of the keys for a defined path without replacing all of the data.
    //POST  Add to a list of data in our Firebase database. Every time we send a POST request, the Firebase client generates a unique key, like messages/users/<unique-id>/<data>
    //https://firebase.google.com/docs/database/rest/save-data

    PostToFirebase("PATCH", FIREBASE_PATH, gpsData, &http_client);

  }
  //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
//**************************************************************************************************


text:
Serial does not read buffer with integer characters greater than 43
I'm trying to write a script to move an object coupled to a linear axis through a stepper motor. The user must send information such as the length to be moved, the speed of movement, the direction of movement, or even if he wants to make millimetric adjustments via the serial. However, I can't read lengths from 43 mm where I send the integer 43 over serial. I tested several methods that I found on the internet. Below is the current code and some alternatives of the serial read section that failed.
void(* resetFunc) (void) = 0;

//Serial read
const int bufferSize = 30; // Tamanho máximo para o buffer de leitura
char buffer[bufferSize];   // Buffer para armazenar os dados lidos via serial

//Step motor
const int stepPin = 3;
const int senPin = 2;
const int enPin = 8;
int sen, sp, len, ad; //sen = forward or backward, sp = speed, len = length, ad = enable steps to adjustment
int REV;//motor revolutions
int time_motor; // interval of pulse (on/off)

void setup()

{

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

  Serial.begin(9600);

  while (!Serial.available()) {
    delay(10);
  }

  int bytesRead = Serial.readBytesUntil('\n', buffer, bufferSize);

  buffer[bytesRead] = '\0';

  sscanf(buffer, "%d,%d,%d,%d", &ad, &sen, &len, &sp);

  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("sen: ");
  Serial.println(sen);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);

  time_motor = 100;

  REV = int(768 * len);

  if(ad == 0){
    if (sen == 1){
      backward(REV, time_motor);
      }

    else {
      forward(REV, time_motor);
      }

      resetFunc();
  }
  else{
    if(sen == 1){backward(768, time_motor);resetFunc();}
    else{forward(768, time_motor);resetFunc();}
  }
}

void forward(int len_fact, int time_c) {
  digitalWrite(enPin, LOW);
  digitalWrite(senPin, HIGH);
  for (int x = 0; x < len_fact; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(time_c);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(time_c);
  }
}

void backward(int len_fact, int time_c) {
  digitalWrite(enPin, LOW);
  digitalWrite(senPin, LOW);
  for (int x = 0; x < len_fact; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(time_c);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(time_c);
  }
}

void loop()
{

}

An alternative below:
  while (!Serial.available()) {
    // Aguarda até que haja dados disponíveis na porta serial
  }

  delay(100); // Pequeno atraso para garantir que todos os dados tenham chegado

  int bytesRead = 0;
  while (Serial.available() && bytesRead < bufferSize - 1) {
    char c = Serial.read();
    if (c == '\n') {
      break; // Termina a leitura ao encontrar uma quebra de linha
    }
    buffer[bytesRead] = c;
    bytesRead++;
  }

  // Adiciona o caractere nulo para indicar o final da string
  buffer[bytesRead] = '\0';

  // Usa a função sscanf para extrair os números do buffer
  sscanf(buffer, "%d,%d,%d,%d", &ad, &dir, &len, &sp);

  // Imprime os valores lidos para verificá-los
  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("dir: ");
  Serial.println(dir);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);

And the other:
  while (!Serial.available()) {
    // Aguarda até que haja dados disponíveis na porta serial
  }

  // Lê os dados da porta serial e armazena no buffer até atingir o tamanho máximo
  int bytesRead = 0;
  while (bytesRead < bufferSize - 1) {
    if (Serial.available()) {
      char c = Serial.read();
      if (c == '\n') {
        break; // Termina a leitura ao encontrar uma quebra de linha
      }
      buffer[bytesRead] = c;
      bytesRead++;
    }
  }

  // Adiciona o caractere nulo para indicar o final da string
  buffer[bytesRead] = '\0';

  // Usa a função sscanf para extrair os números do buffer
  sscanf(buffer, "%d,%d,%d,%d", &ad, &dir, &len, &sp);

  // Imprime os valores lidos para verificá-los
  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("dir: ");
  Serial.println(dir);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);

Serial returns nothing or "?". How should I proceed to solve this problem?
I'm using an original Arduino uno and writing in the arduino IDE. The version is 1.8.19.

maybe you set the wrong baud rate in the serial console

reduce your program. to minimum code that still exhibits the problem

You are sending 4 numbers over serial, right? Please copy and paste the exact numbers that you are sending.

Before the sscanf I would be printing what is in that buffer.

Well, you didn't provided that much info, but i picked up on some of your code (below) and in the serial monitor i can read all the numbers :
    const int bufferSize = 30; // Tamanho máximo para o buffer de leitura
char buffer[bufferSize];   // Buffer para armazenar os dados lidos via serial

//Step motor
const int stepPin = 3;
const int senPin = 2;
const int enPin = 8;
int dir, sp, len, ad; //sen = forward or backward, sp = speed, len = length, ad = enable steps to adjustment
int REV;//motor revolutions
int time_motor; // interval of pulse (on/off)

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
while (!Serial.available()) {
    // Aguarda até que haja dados disponíveis na porta serial
  }

  delay(100); // Pequeno atraso para garantir que todos os dados tenham chegado

  int bytesRead = 0;
  while (Serial.available() && bytesRead < bufferSize - 1) {
    char c = Serial.read();
    if (c == '\n') {
      break; // Termina a leitura ao encontrar uma quebra de linha
    }
    buffer[bytesRead] = c;
    bytesRead++;
  }

  Serial.println(buffer);

  // Adiciona o caractere nulo para indicar o final da string
  buffer[bytesRead] = '\0';

  // Usa a função sscanf para extrair os números do buffer
  sscanf(buffer, "%d,%d,%d,%d", &ad, &dir, &len, &sp);

  // Imprime os valores lidos para verificá-los
  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("dir: ");
  Serial.println(dir);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);
}


text:
Direct port manipulation takes 300 nanoseconds to execute for some reason
I have this code
#include <Arduino.h>

void setup() {

  DDRD  = B00001000;

}
void delayNanoSeconds(int time){
    int ans = (float)time / 62.5;
    for(int i = 0; i < ans; i++){
        _NOP();

    }

}
#define delay250 _NOP(); _NOP();_NOP(); _NOP();
#define delay1000 delay250 delay250 delay250 delay250
void loop() {
  while(1){
       PORTD ^= B00001000;
       delay1000; delay1000;
  }

  }

but I am getting delay of 2300 us
here is a picture of the logic analyzer
and when I change delay to 250 or 1000 I am still getting this extra 300ns so why

Remember: every single thing the CPU does takes time. Here is a
disassembly of your loop():
    ldi  r25, 0b00001000 ; r25 = B00001000
1:  in   r24, PORTD      ; r24 = PORTD
    eor  r24, r25        ; r24 ^= r25
    out  PORTD, r24      ; PORTD = r24
    nop
    nop
    ...
    nop
    rjmp 1b              ; goto previous label 1

As you see, besides your series of nop, there are four instructions in
the loop:

in, eor and out take one cycle each
rjmp takes two cycles.

That is a total overhead of 5 CPU cycles, or 312.5 ns when
running at 16 MHz. Pretty close to what you are seeing.
If you want an exact timings, you will have to disassemble your code and
count the overhead cycles, as I did here. Then, I suggest this simpler
approach:
#define OVERHEAD_CYCLES 5

void loop() {
    for (;;) {
        PORTD ^= _BV(PD3);
        _delay_us(2 - OVERHEAD_CYCLES / (F_CPU / 1e6));
    }
}

Ok thanks for help

By the way how did you see the assymbly code

@Abdrlrahman: Re “how did you see the assymbly code”: avr-objdump -SCz sketch.elf > sketch.lss. You should see the location of the ELF file if you enable verbose compilation. The avr-objdump tool is somewhere in your Arduino installation, but the exact location may depend on your OS and the installed version of Arduino. You may have to search for it.

By the way shouldnt it be _delay_us(2 - OVERHEAD_CYCLES  * (F_CPU / 1e6)); instead of /

@Abdrlrahman: No, it's really a division. It ends up being 2 − 5/16.0 = 1.6875 µs.

2 - OVERHEAD_CYCLES / (F_CPU / 1e6) must be evaluated at compile time, of course. Thus the 2 cannot be added at runtime. Interesting that _delay_us has a float parameter, compared to the Arduino delayMicroseconds(unsigned int)


text:
Can't figure out why what I'm trying to do isn't working. Trying to light up a RGB with buttons with AnalogWrite
DISCLAIMER : I have just started Arduino, like 2 days ago, I've been following some tutorials on YouTube, and I tried to do this myself, but I can't figure out why it isn't working, can't find what I'm doing wrong.
THE SETUP (I've already tested it with some other code that proved me that the setup is working, each buttons and each pin of the RGB LED, I know for sure that this is the code not working)

I am trying to light up the led to RED thanks to second button (from LEFT), Green with third, Blue, with fourth, and the first one to put the LED off . I am aswell trying to make a perfect visual transition between each colors going from 255 to 0 decimal..
Here is my code :
#define BLUE 10
#define GREEN 11
#define RED 5

int buttonBlueOn = 9;
int buttonGreenOn = 8;
int buttonRedOn = 3;
int buttonRgbLedOff = 2;

void setup() {
  // put your setup code here, to run once:
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(buttonRedOn, INPUT_PULLUP);
  pinMode(buttonGreenOn, INPUT_PULLUP);
  pinMode(buttonBlueOn, INPUT_PULLUP);
  pinMode(buttonRgbLedOff, INPUT_PULLUP);

}

int redValue;
int greenValue;
int blueValue;

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

  // -------------------------------- RED ------------------------------ //

#define delayTime 20

  if (digitalRead(buttonRedOn) == LOW)
  {
    digitalWrite(RED, HIGH);
    redValue = 255;
  }

  if (digitalRead(buttonRedOn) == LOW and GREEN == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out green brings red full
    {
      redValue += 1;
      greenValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  if (digitalRead(buttonRedOn) == LOW and BLUE == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out blue brings red full
    {
      redValue += 1;
      blueValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(BLUE, blueValue);
      delay(delayTime);
    }
  }

  // -------------------------------- GREEN ------------------------------ //

  if (digitalRead(buttonGreenOn) == LOW)
  {
    digitalWrite(GREEN , HIGH);
    greenValue = 255;
  }

  if (digitalRead(buttonGreenOn) == LOW and RED == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out red brings green full
    {
      greenValue += 1;
      redValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  if (digitalRead(buttonGreenOn) == LOW and BLUE == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out blue brings green full
    {
      greenValue += 1;
      blueValue -= 1;
      analogWrite(BLUE, blueValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  // -------------------------------- BLUE ------------------------------ //

  if (digitalRead(buttonBlueOn) == LOW)
  {
    digitalWrite(BLUE, HIGH);
    blueValue = 255;
  }

  if (digitalRead(buttonBlueOn) == LOW and RED == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out red brings blue full
    {
      blueValue += 1;
      redValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(BLUE, blueValue);
      delay(delayTime);
    }
  }

  if (digitalRead(buttonBlueOn) == LOW and GREEN == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out green brings blue full
    {
      blueValue += 1;
      greenValue -= 1;
      analogWrite(BLUE, blueValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  // -------------------------------- OFF ------------------------------ //

  if (digitalRead (buttonRgbLedOff) == LOW)
  {
    digitalWrite(GREEN, LOW);
    digitalWrite(RED, LOW);
    digitalWrite(BLUE, LOW);
  }

}

WHAT IT DOES : Nothing at all, nothing lights up, nothing happens, I'm a bit confused
I am so new to this, sorry if I'm doing something wrong on this forum

Looks like you did not connect the buttons to ground.

You have connected the buttons to the blue power rail of the breadboard, but you haven't connected that to ground on the Arduino

insert a layer of separation between the detection of a keypress and the resulting change to LED brightness ... do not do if button pressed, set led brightness ... instead do if button pressed set variable deltaRed=1 ... then further in loop() do redValue += deltaRed; light red led

GREEN == HIGH will never be true, that's a comparison between two constants

Your program makes things too complex. You should rethink your whole strategy.
My preferred method is to have a "target" colour and a "current" colour. When you press a button you simply change what your target colour is. And then every iteration through loop() (either slowed down with a short delay() or triggered with millis()) you compare the target and current colours, and if they differ then move the current colour a step closer to the target colour.
That way you remove all the logic of "if this is pressed but not this then fade between these two colours", instead it's just "if this is pressed then I want to go to this colour" and the changing of the colour is completely independent.
I wrote a blog post on the topic some time ago that you might find helpful.


text:
ESP32: why does malloc can only alloc 126888 bytes with 402540 bytes heap?
I need a buffer of the size 153600 bytes in my ESP32 project, but I could not create a static buffer in code nor can I malloc the buffer.
The ESP32 itself reports:
  ESP.getHeapSize()  // = 402540
  ESP.getFreeHeap()  // = 376980
  ESP.getPsramSize() // = 0
  ESP.getFreePsram() // = 0

malloc(153600) returns NULL; I wrote a little loop which decrements by one and retries to malloc. The first time it works is malloc(126888) so this seems to be the maximum buffer I can get.
(I tried it with different boards; one from eBay and one from a genuine distributor - no differences.)
Clearly the heap size is big enough. So I'm thinking that the RAM is possibly split into different chunks and no one is big enough for my buffer?
Is there any documentation which explains this behavior?

Are you allocating memory in other places as well? Could it be that you already fragmented the memory before you try?

Yes, the ESP32 memory is arranged in a number of different chunks. Those chunks are all aggregated by the memory manager to appear as a single heap, but they're actually separate.
As the ESP-IDF documentation mentions:

At startup, all ESP-IDF apps log a summary of all heap addresses (and sizes) at level Info:
I (252) heap_init: Initializing. RAM available for dynamic allocation:
I (259) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM
I (265) heap_init: At 3FFB2EC8 len 0002D138 (180 KiB): DRAM
I (272) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM
I (278) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
I (284) heap_init: At 4008944C len 00016BB4 (90 KiB): IRAM

And of course you have some heap fragmentation from other threads allocating and deallocating memory, so the biggest contiguous block of memory you can allocate will be smaller than the biggest region.
To further illustrate I found this handy memory map on the Arduino forums:

There you can clearly see the SRAM is split into different chunks. The main reason for this is to better allow concurrent access by the two cores in the dual-core variants of the chip.


text:
Motor for a winch (with controller and external power supply)
I'm in need of a motor or continuous servo to power a winch. The motor must be continuous* and reversible, but it does not need to be fast, precise, nor bear a load when powered off. It just needs to overcome ~50 Newton of friction force (to winch open my bedroom curtains laterally).
(* it needs to, given a discrete drum (maybe max 4cm diamater), winch about 1m)
I am using a MEGA2560 R3 which has a 5V port. I've tried using a 12V DC stepper motor (24BYJ48) with a standard ULN2003 controller, with a winch drum of ~2cm diameter, but it could not overcome the friction. I didn't spare much thought for the parameters of the arduino Stepper instance though; I just used a configuration which worked for winching lighter loads.
I'm a rookie, but I'm assuming my board cannot sufficiently power the motor(s) (I have 3), and possibly that they themselves are too weak. Hence I'm looking for a stronger motor and controller, controllable by my arduino, but which has a direct power supply (from mains). So:

have I got this all wrong? Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?
is there a shield for my MEGA which can enable these motors to function in parallel?
otherwise, is there a strong continuous servo with an external power supply that would work here?

Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

No, you should never ever power a motor through an Arduino. It can only provide a limited amount of current, before it gets fried. You need to provide the motor driver with voltage directly from your power source. You haven't stated, what you are using as a power supply. I assume, you are just using an USB port of a PC. That is also a no-go, since it will only provide 500mA at max (that's even less, than the Arduino can bear). You should power your motor with a power supply of 12V, since it is rated for that voltage. You can buy a simple wallwart for that.
Also, currently you are providing the 12V motor with only 5V, so it cannot give you it's full power. Use a power supply with the correct voltage and more than enough current capability. Though you should keep an eye on the current ratings of the ULN2003. The datasheet is not really clear, if that chip supports 12V supply voltage. Some variants like the ULN2004 seem to support it, but I'm not sure about the ULN2003. If it is not rated for 12V, you can destroy the chip that way.
We cannot know, if the motor with it's driver will be able to rotate the winch, since the seller does not name the torque of the motor. You could try to contact the seller and ask directly about this. More specialized sites, where you can buy motors, will tell you exactly, what the torque of the motor is, that you are buying. Buying a cheap part at Amazon is somewhat the lightweight variant of buying it directly from china: The documentation is a bit better, but still not great. Without documentation or information from the seller, you are stuck with just buying and trying.

is there a shield for my MEGA which can enable these motors to
  function in parallel?

It isn't clear, what you mean by that. You can control as many motors simultaneously, as you have pins and as you have enough computation time (meaning not too much steps per second or other stuff going on in the program). As mentioned above the power has to be supplied to the drivers from outside of the Arduino, so that does not apply here.

otherwise, is there a strong continuous servo with an external power supply that would work here?

Power supply and motors are 2 different parts, that aren't usually sold together. Also you should start with the motor: Look for a motor, that can provide the torque, that you need. Then look for a driver circuit, that can provide the functionality, is rated for the same voltage as the motor and can provide enough current for the motor (the max. motor current is also information, that a good seller will provide). Then look for a fitting power supply. Unless you are buying some kind of kit, you need to choose these parts yourself. (We don't do product recommendations here)

A possibility, that you might not have though about: You could buy a normal DC motor, which provides enough torque. As speed is not your biggest concern, you could buy a geared DC motor, which can be rather strong. For a driver you would need to buy or build a H-bridge controller (which is essentially just 4 transistors put together). Be sure to use a MOSFET based driver, if you want to buy a driver chip. The standard L298n is pretty lossy.

It seems, that you generally don't know, how to build such a project. So here are some notes, that might help you with that:

Connecting everything together: In most cases (and especially when handling high current motors) you cannot get around soldering. You can buy a perfboard (cheap PCB material, with some pads already connected for ease of use), put the parts onto it and solder everything to the perfboard. Using shields as no-solder solution can only work, when you find a fitting shield and fitting motor for your requirements. That can be a far fetch. So if you want to get into electronics and Arduino, you probably should get yourself a soldering iron (there are also many tutorials about using it on the web).
Connecting the power supply: When buying a walwart power supply, it will normally come with a cable attached to it. At the end of this cable may be a connector. You have 2 options: Cut the connector and solder the wires in the cable directly to your perfboard, or buy the counter part of the connector, which you then can solder to your perfboard. Depends on if you want to disconnect the power supply from the circuit or not.

As I'm suggesting here to invest in this a bit, I want to also sketch an alternative, if you just want to get it work and don't experiment (this site is full of makers, you do this for fun, but that does not have to apply to everyone):
You may be able to use a shield to do, what you want to. This might cost a more, than putting the parts together yourself, but it will safe you the investment in tools, which you might not need in future. As above you need to choose the parts fitting your requirements. Decide on the type of motors, that you want to use (if money is not such a deal, you can nearly use any motor with enough power, stepper motor, DC motor, ...). Look for a shield, that can provide the needed current and voltage to the motor.
Every motor shield has a terminal for connecting the external power supply for the motors. On good shields this is a screw terminal, so you would simply strip the cable of the power supply and put the wires of it into the screw terminal.

I'm still unsure how I would power the driver with an external supply (I've only seen power plugged directly in to the arduino). Would the supply connect to a shield (that I connect to the arduino) with its own 12V port? Also, do I really need a driver if I just bought a motor like this one?

The power connection (assuming you still want to power the Arduino over USB) would be: 12V supply + to + of the motor driver, 12V supply - to ground of the motor driver, ground of the motor driver to ground of Arduino. A shield does also exactly this. And yes, you need some kind of driver, since you want to turn the winch both ways. But as I wrote, a driver can be as easy as 4 MOSFET transistors connected together (you can google MOSFET H bridge to find out how exactly). Without driver, the motor is be on the whole time. You need something to control it (interface between Arduino and motor)

Gotcha - actually I would like to power both the driver (e.g. this one) and Arduino using mains power - though they need 12V and 5V respectively. I imagine the MEGA regulator can't handle 12V; is there some shield/transformer combo that will let me power both with a single power adapter (and a split cable)? Furthermore, I can't even find a 12V power shield online - where can I look for these things?

I think the Mega can handle 12V at Vin, though that's about the maximum. If nothing else is powered through the Mega, that should work. Otherwise you can buy an extra voltage regulator, that is rated for these voltages. And shields are not the answer to everything. Don't search for a power shield, but for a 12V wallwart and if you need it for a 12V to 5V voltage regulator (both rated for enough current)

Wew ok I'll try. But don't I need to connect the wallwart to something to integrate it into my setup? I can't stick cables straight into the plug of the power supply.

@AntiEarth I tried to add some notes about that, though I'm not completely clear, what exactly the problem is. It more seems, that you have general missing knowledge in how to build an electronics project.

Your new note says I should strip a wallwart myself and connect it to the motor driver via screw terminal - how on Earth should that be intuitive, given most novice electronics problems are 'plug in play', as is the very cable you suggest? Your info has been very helpful, thanks very much, but your attitude is very strange

@AntiEarth I don't say, that it is intuitive. I just try to sort out, what exactly the core problem is and how I can help you within the structure of this simple Q&A site. I can write a more general answer about how building this, though that would not really fit to your original question and might be worth a new question. The thing with plug&play is, that such kits are made either very general, just for experimentation, or for a very special case. When you want to reach a special goal outside of it, you are mostly tied to do much yourself.

Such a project might not be the best point for starting as a beginner from zero. Most kits are really experimentation kits, so that you can learn the basics without a specific goal in mind.

"Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?"
Huh? Do you mean can you power a 12V stepper directly from the 5V supply on an Arduino? How would that work? You need an external power supply and a motor controller that converts the 5V control signals from the Arduino to 12V. The answer is "absolutely not." Motors draw way, way too much current to be powered from an Arduino logic pin, and all but the smallest motor will draw too much current for the 5V supply line. Plus you said you were using a 12V motor. You can't run a 12V motor on 5V.
A stepper seems like the wrong tool for this job. You should be able to use a high torque 12V DC motor and an H-bridge motor controller. An H-bridge will let you run the motor forwards or backwards.
You'll probably need a motor with a gearbox, since you likely want a fairly slow turning shaft. How many newton-meters/second do you need?


text:
analogWrite never outputs a non-zero voltage
With a very simple connection of an LED (which can withstand 5V) to ground and to a pin on my Galileo gen2, I can never output a non-zero voltage from the pin via analogWrite, regardless of whether the pin is digital or analog (although PWM digital works)
The LED is in the correct bias and I'm calling pinMode(pin, OUTPUT) before attempting to call analogWrite(pin, 255) (or any 2nd parameter in-between), even though it's not even necessary.
The LED glows if I call digitalWrite(pin, HIGH) on both analog and digital pins, but does not glow at all for analogWrite(pin, 255) with the same configuration and pins, nor does it for any 2nd param in [0, 255]. This holds for whether the call is attempted in loop() or setup().
The only possible way I can get the LED to receive any power from analogWrite is through a digital PWM pin, but I know the other digital pins can still produce square-waves with timers and the analog pins should certainly be able to use PWM.
(So far, I've been to scared of short-circuits to connect the analogWrite output straight into an analog input to read the voltage)
Is there something I don't understand about the underlying board, or am I experiencing some strange malfunction?
Thanks,
Tyson

(I could understand it not working on non-PWM digital pins, because perhaps analogWrite doesn't make the necessary use of timers to simulate a square-wave, unlike the function tone. But why wouldn't analog pins write analog?!

When simulating on 123d.circuits.io, again only PWM digital pins work as expected, but analog and digital pins interpret analogWrite as binary digitalWrites, thresholding past 255/2 (slightly different to always being 0 on my Galileo)

As per other answer: analogWrite ONLY works on hardware-PWM capable pins*. What you see is correct operation. * uC's with DAC may allow analog.write on DAC equipp3d pins.

On most boards, the standard implementation of Arduino's analogWrite() will only ever produce PWM, and only on a specific set of (digital) pins. These are usually pins 3, 5, 6, 9, 10, and 11, although it's slightly different on some boards.
The only official board which has 'true' analog output is the Due (pins DAC0 and DAC1).
If you want any other behaviour (such as outputting PWM on non-standard pins), you'll either need to modify the Arduino implementation, or directly manipulate the microcontroller's special registers. Note though that modifying the chip's configuration could cause other standard Arduino functions not to work as expected.

So the analog pins don't support PWM (they're only titled such because they can read analog)? What about the use of timers to produce square-waves which emulate analog as discussed here: http://arduino.stackexchange.com/questions/8357/why-does-a-piezo-buzzer-not-require-a-pwm-digital-pin-gallileo-gen2/8363?noredirect=1#comment15232_8363

@AntiEarth Yes, analog pins are for reading analog only. For square wave output, the MC's timers can usually be routed to any GPIO pin in theory. The tone() function can output to any pin, for example, but it comes with its own limitations. It's important to note that Arduino is only designed to support a subset of the underlying MC's capabilities. The official Arduino website documents all of this if you need to look anything up.

So to clarify/summarize: only digital PWM pins can actually produce square waves upon calling analogWrite. The other pins (normal & analog) can achieve square waves using timers, but this is not implemented in the analogWrite function, nor in the Servo definition. Have I understood correctly?

@AntiEarth You're right about everything except the Servo library. It can work with any pin because it doesn't use analogWrite(). It manipulates the timers directly. This unfortunately means it can prevent PWM from working in some cases, so you have to be careful about how you use it.

That is exactly opposite what I've discovered experimentally; simple calls to the Servo functions only work on digital PWM pins on my Galileo (gen2); they absolutely do not work on other digital pins or analog pins. The mystery continues!

@AntiEarth I suppose it's possible that the Galileo is different, since it has a different chip at its core. I'm just going by what the Servo library documentation says! :)

I am not sure where you are getting your LEDs but the ones I purchase do not survive 5 volts. You need to put a resistor in series with then, something in the 220 to 510 ohm range.  When you get some resistors test your LEDs you may have damaged them as well. A good indication of this if there color if obviously off and or dim. If the timers are set up correctly the digitalwrite will set the PWM value, somewhere from 8 to 16 bits depending on the Arduino and timer used. This PWM output will appear to control the brightness of the LED. It does this by simply turning it on and off at a speed the eyes cannot follow. the longer it is on the brighter it is. Hopefully this will help you get your arms around the circuit.

I don't believe Galileo has a D/A converter, which is what it sounds like you're expecting. In the Arduino 'eco-system', analogWrite() sets a PWM duty cycle - that's kinda-sorta somewhat like an analog output, but not really. You could add external circuitry to low-pass filter the PWM and produce some sort of proportional DC but it might be a good trick get it clean enough for whatever you plan to put downstream.

As discussed here http://arduino.stackexchange.com/questions/8357/why-does-a-piezo-buzzer-not-require-a-pwm-digital-pin-gallileo-gen2/8363?noredirect=1#comment15232_8363, I'm just trying to emulate an analog signal by digital square-waves


text:
Remote Controlled Self-Balancing Robot - how to mix control input with IMU input?
I'm building a two-wheeled, self-balancing, remote-controlled robot. I'm familiar enough with the IMU and PID to get it working to just stand up but I need to drive it via remote control.
I've got no code written yet; trying to understand the concepts before diving in.
This much I understand: [IMU] -> [Kalman filter] -> [PID] -> [Motors]
Where I'm getting tripped up is where to mix the RC component into that control chain?

The PID get's a set point from you. For a standing still robot this a basically an angle of zero in respect to the gravity direction (which variable you use for the PID depends on your actal implementation, but it always be something derived from the angle to gravity direction). For driving forward, the robot must lean forward. So you set the new angle set point to let's say 2 degrees. The PID will try to hold that value by driving forward constantly, with a speed depending on the set angle.
So, via the remote control you simply change the angle setpoint.

Seems so obvious now, thanks!


text:
`__has_include` macro on ESP board
I am working on a code for ESP boards that can be used on either ESP32 or ESP8266 and I want to make sure I include the correct libraries.
I know I can check if ESP32 OR ESP8266 are defined, but I wanted something more specific.
Anyway, in my project I have a class called Storage which provides an interface for a storage medium, and two implementations: one with the Preferences library and another with SPIFFS.
I want to have instantiation functions for each implementation (sort-of factory pattern), and to use pre-compilation checks to only compile the valid implementations for the currently selected board.
This is my current code:
#include <memory.h>
#include "Storage.h"

#if __has_include(<Preferences.h>)
#include "PreferencesStorage.h"
std::unique_ptr<Storage> createPreferencesStorage() {
    return std::make_unique<PreferencesStorage>();
}
#endif

#if #if __has_include(<SPIFFS.h>)
#include "SpiffsStorage.h"
std::unique_ptr<Storage> createSpiffsStorage() {
    return std::make_unique<SpiffsStorage>();
}
#endif

My problem is that #if __has_include(<Preferences.h>)returns false for some reason even though I can import the library.
It only returns true if I first include <Preferences.h> which obviously is not really helpful.
Does anyone have idea what might be the cause?

here's a two year old post https://github.com/arduino/arduino-cli/issues/1782


text:
Extra 0x00 sent with RS485 message
I am currently trying to use an arduino to send an RS485 via an SP3078EEN RS485 transciever. I have my arduino code set the DE pin high, wait 1ms, then write and flush a data buffer to the serial which is connected to the DI pin of the transciever. Post-this it sets the DE pin low again. This is almost all working as intended except for the fact that I am getting an extra 0x00 byte after my data as read by my oscilloscope and PC (measured via an RS485 to USB converter).
Below I have the important portion of my code as well as the oscilloscope measurements of Di (Driver Input), A (RS485 Positive Output) and DE (Driver Enable). I also have provided a simplified schematic of my circuit. The only thing I can see that might be the cause of this is the seemingly capacitive discharge on the "A" signal which occurs when I switch DE from high to low. I don't know why this is happening or how to fix it. I have tried putting pullup / pulldown resistors on RO, RE and DI to no avail. I have also tried increasing the pre-write delay and also adding a post-write delay, also to no avail.
If anyone can help me figure this out it would be greatly appreciated.
Oscilloscope

Code:
void setup() {
    Serial0.begin(19200, SERIAL_8E1);
    Serial1.begin(19200, SERIAL_8E1);
}

void loop() {

    // Setting the buffer to a static value for debugging purposes
    byte buffer1 = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x04, 0xC4, 0x0B };

    // Set the DE_1 pin high to enable writing to the RS485 bus
    digitalWriteFast(DE_1_PIN, HIGH);

    delay(1);

    // Write the buffer to the RS485 bus
    Serial1.write(buffer1, 8);
    Serial1.flush();

    // Disable writing
    digitalWriteFast(DE_1_PIN, LOW);

    delay(1000);
}

Super-Simplified Schematic

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". -- Beside the fact that your source and the record don't match in data, your schematic does not show the obligatory pull-up and pull-down resistors on the bus. Please [edit] your question to add whether you have them or not.

Anyway, your issue is not actually Arduino related. It could be closed soon for this reason. A better place would be SE/EE.

Your TX/RX pins are reversed on the schematic: TX should go to DI, and
RX to RO. I guess this is an error on the schematic only, not on the
actual circuit.
Regarding the extra 0x00 byte after the message... I cannot see it on
the scope trace. I see the A signal falling when it stops being driven,
and this looks very much like a start bit followed by a stream of zeros.
However, there is no matching stop bit. Thus, this shouldn't be
interpreted as a transmitted byte, but rather discarded as a framing
error. More appropriately, this is a “break” condition on the line.
I see two options for you:
On the software side, you should probably configure your receivers to
not ignore framing errors, but instead discard mis-framed bytes. On
the hardware side, you probably already have some termination resistors
at the ends of the line. You can replace those by voltage dividers
between GND and +5V in order to make the undriven A line idle at a
potential higher than the undriven B line. This way the undriven bus
idles at logic 1, like a serial line is supposed to. You should be
able to find documentation on the Internet showing how to compute the
appropriate resistor values.


text:
analogRead values all over the place, while measuring light
I'm trying to detect light using an led that's already attached to the circuit. I have a flashlight shining on the led.
Minimal sketch:
while( true )
{
    int photoValue = 0;
    analogReference(INTERNAL);
    photoValue = analogRead(A5);

    Serial.println(photoValue);

    delay(300);

}

While I have my multimeter attached, it reads a pretty constant value around 5mV. The serial output however swings around, as seen in this sample output:
0
0
4
4
0
16
15
22
21
25
20
36
40
34
36
24
5
0
3
6
0
0
0
0

That would translate to values between 0 and 43mV.
When I disconnect the multimeter only get 1023 printed.
I don't get how the values from the ADC and the multimeter, totally don't match.

Can you show your circuit?

I strongly suspect that the LED isn't able to produce enough current to charge the S&H capacitor. Plus the LED, when not generating enough voltage, will most likely make it look like the pin is floating somewhat. You may need a high impedance buffer between the LED and the ADC.

In a few days I will have high impedance buffers available on eBay based around the OPA355. I will experiment with one when the components arrive to see what a difference it makes.

Not enough current; makes sense. The circuit is 8 LEDs in parallel, connected between gnd and A5. Tomorrow I'll try adding a small capacitor to the A5 pin. I don't have any room for something like an opamp. So if that doesn't work I'll just have to scrap this, nice to have, extra feature.

What is it you're trying to do, ultimately?

I have a string of tiny SMD LEDs attached to some fake eyelashes. I currently have a few different animations/patterns programmed. I thought it would be fun to make them more interactive, by e.g. turning the LEDs  on after camera flash is detected. Or just a regular increase in light hitting the LEDs, as camera flashes are very short. Pretty weird project but they look awesome when attached to a models eyelids.

That sounds fun! I'd love to see it when it's done. So I can imagine that space is at a premium. I can't imagine how / where you have stashed the Arduino... Does the model have a big hooter? ;)

The PCB is a 3 cm circle. ATMega328 on the front, CR2032 battery on the back, along with a hearclip. PCB will be placed on the back of the head, with wires going to the eyes. The wires are 0.1mm enameled copper. Here is an older photo. Final version will be two color (charlieplexed). Adding a 2.2nF capacitor (>100x the 13pF S&H capacitor) seems to stabilize at least a bit, though I haven't had much time to do some proper testing.

That is awesome! I love it! I expect to see it on the catwalks of London, Madrid and New York soon!

I have tested with an OPA355 and it improves things massively.

I printed the analogread values to the serial port. With the 2.2nF capacitor. You can see the voltage rising relatively slowly, when I point the flashlight on it. About a second. Removing the light does produce a sharp edge. Read values are still a bit is noisy, but I didn't put a cap on the aref pin in my pcb.

The problem you are facing is that the output of the LED is too high impedance for the ADC to work reliably.
Basically the LEDs can't produce enough current to charge the S&H capacitor properly, and on top of that the LED doesn't act as a resistive load when not forward biased, so the input is basically floating and picking up noise.
The best cure is to add a voltage-follower buffer with incredibly high input impedance in front of the ADC input.
By high impedance I mean something measured in the 10s to 100s of TΩ. Something like the OPA355.

Thanks for all the feedback. Due to the deadline I have to scrap the idea for now. But the next competition is in October, so maybe then. Anyway; much appreciated.


text:
Use DS3231 with battery and vcc at the same time
I have ds3231 which i want to use to keep track of time even when the in my ase esp32 is without electricity. I however read some difference stuff regarding using the vcc and battery on he same time. Someone said it would destroy the battery. But
Using only battery will not be able to communicate with it (with i2c) since that only works with vcc
Using only vcc will not be able to keep track of time when power is cut.
Isnt the device switching between vcc when power is on and battery when it is off?

From the datasheet analog.com/media/en/technical-documentation/data-sheets/… it seems that it you connect the 3.3v power supply and the backup battery (but not to the same pin), and when the power goes down, the battery is automatically used. It says that a " comparator circuit monitors the status of VCC to detect power failures, to provide a reset output, and to automatically switch to the backup supply when necessary. "

when I meassure over the battery pins I get 3.3volt over the battery pins when vcc is connected and no battery. isnt that supossed to be 0? It seems like i have go a charging unit in my module?

Your first stop on issues like this is the data sheet. Reading and understanding is a necessary skill for developers.

Isnt the device switching between vcc when power is on and battery when it is off?

The chapter "Power Control" has the table 1 on page 10:

SUPPLY CONDITION
ACTIVE SUPPLY

VCC < VPF, VCC < VBAT
VBAT

VCC < VPF, VCC > VBAT
VCC

VCC > VPF, VCC < VBAT
VCC

VCC > VPF, VCC > VBAT
VCC

Yes, it switches automatically according this table. BTW, VPF (power-fail voltage) is typically 2.575 V, see page 2.

when I meassure over the battery pins I get 3.3volt over the battery pins when vcc is connected and no battery. isnt that supossed to be 0? It seems like i have go a charging unit in my module?

The chapter "Pin Description" on page 9 tells us (emphasis by me):

VBAT Backup Power-Supply Input. When using the device with the VBAT input as the primary power source, this pin should be decoupled using a 0.1μF to 1.0μF low-leakage capacitor. When using the device with the VBAT input as the backup power source, the capacitor is not required. If VBAT is not used, connect to ground. The device is UL recognized to ensure against reverse charging when used with a primary lithium battery.

No, the battery will not be charged by the IC.
However, some modules with the DS3231 seem to include a charging circuit. Consult your module's documentation. And disable that circuit if you use a primary cell.


text:
How do I properly use an ISR inside a class definition?
I want to write a class for a model bike.
For controlling the steering I use a DC motor with two encoders.
To get the steering angle stAng of the bike, I attach a interrupt to the pin ST_ENC_A where one of the encoders is connected to. This interrupt is attached when the bike is initialized with the function bike.begin(). When the interrupt is triggerd, the increment-steering-angle-function incStAng is triggerd.
Said function is member of the class Bike. To make the whole code compile and upload I had to make the increment-steering-angle-function static void incStAng() and the steering-angle-variable volatile static float stAng static.
The code is running, there are no errors or warnings.
Now, when I provide pin ST_ENC_A with 3.3V the interrupt should be triggerd and I should see the printed value of stAng increse in the Serial Monitor. This is not the case. It stays at 0.00.
This is my first real class I am writing. I only want to create one instance of my bike so the static definition of stAng and incStAng should be no problem.
So far I found the following websites helpful for information on 'static' and ISR.
I would be glad if someone could help me and give me a hint why the steering angle is not increasing when I give said pin 3.3V!
Board: Arduino Nano RP2040 Connect
Below you will see the .ino, .h, .cpp files in this order.
// myBike.ino - main file

#include "Bike.h"

Bike bike;

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

void loop() {
  float val = bike.getStAng();
  Serial.println(val);
}

// Bike.h - header file for the Bike library

#ifndef Bike_h
#define Bike_h

#include "Arduino.h"

class Bike {
  public:
    Bike();
    void begin();
    float getStAng();
  private:
    volatile static float stAng;
    static void incStAng();
};

#endif

// Bike.cpp - implementation file for the Bike library

#include "Bike.h"

#define ST_ENC_A      12
#define ST_ENC_B      11

#define DEG_PER_CNT   0.51428571428

Bike::Bike() {
  pinMode(ST_ENC_A, INPUT);
  pinMode(ST_ENC_B, INPUT);
}

void Bike::begin() {
  attachInterrupt(digitalPinToInterrupt(ST_ENC_A),incStAng,RISING);
}

void Bike::incStAng() {
  volatile float stAng;
  int b = digitalRead(ST_ENC_B);
  if(b==HIGH){
    stAng = stAng - DEG_PER_CNT;
  }else{
    stAng = stAng - DEG_PER_CNT;
  }
}

float Bike::getStAng() {
  volatile float stAng;
  return stAng;
}

Did you connect that pin to ground previosly before changing to 3.3V? Do you use external pullup or pulldown resistors? The pin might already have been at 3.3V, thus connecting it to 3.3V would not generate a rising edge. Have you tried connecting and rotating the actual encoder?

You have three different variables named stAng here:

a static member of the Bike class, which has been declared but not
defined, and is never used
a local variable of the Bike::incStAng() method
a local variable of the Bike::getStAng() method

There should be only one such variable. For this, you should define the
first one: in Bike.cpp
volatile float Bike::stAng;

and get rid of the other two.
Side note: I would recommend avoiding floating point computations within
an ISR, as these can be quite slow. Instead, count the integer number
of encoder steps in the ISR, and convert to an angle within
Bike::getStAng().

Thank you for this quick help, it works like I want it to!
I am still wondering why it has to be like this though.
Adding these two local variables you mentioned made the code compile, this is why I did it.  So, in the class I only declare stAng as a static member but with volatile float Bike::stAng; in Bike.cpp I define it, right? I do not get the underlying rule why I have to do it this way. Could you give me a short explanation? If I add a non-static variable to the class and want to access and modify it using a method of Bike I do not have to add such a definition in Bike.cpp.

@Ole: The class definition in Bike.h defines a type only. No data. The line Bike bike; in myBike.ino defines a Bike object, and thus all the data belonging to that object (which in this case just happens to be none). A static data member does not belong to any object, and thus has to de defined elsewhere. It has also to be defined only once, so a .h file, which could potentially be included in multiple other files, would not be appropriate.


text:
Megaboard Problems about pySerial Communication from Python to Arduino
I asked same question on another forum, but i need more opinions and advices.
I wrote a simple Python code and Arduino code.
In my code, the Excel matrix data is loaded into Python,
then converted into a numpy form of matrix data in Python,
and then extracted the values of each element of the matrix converted into numpy.
Each extracted element value is a screw lead value.
These screw lead values are calculated and converted to the number of revolutions of each screw.
These converted screw rotational speed values are now transferred to Arduino using pySerial.
Once the values of the screw revolutions are transmitted to Arduino,
rotate the step motor connected to Arduino by the number of revolutions of the screw.
So here's my Python code.:
import csv
import pandas as pd
import numpy as np
import os
import serial
import time

py_serial = serial.Serial(
    port="COM5",
    baudrate=9600
)

Location = 'C:/Users/KIMWONKI'
File = 'excel_example.xlsx'

data_pd = pd.read_excel('C:/Users/KIMWONKI/excel_example.xlsx',
                        header=None, index_col=None, names=None)

data_np = pd.DataFrame.to_numpy(data_pd)

start = 2
pitch = 3
lead = 0

for i, row in enumerate(data_np):
    for j, element in enumerate(row):
        lead = data_np[i][j]
        rotation = lead/(start*pitch)
        reverse_rotation = - rotation
        rotation = round(rotation, 6)
        if rotation > 0:
            print(f'motor rotates in the forward direction at {abs(rotation)} times.')
            rotation = str(rotation)
            py_serial.write(rotation.encode())
            time.sleep(8)

And next is my Arduino code.:
int DIRM=8;
int PULM=9;
int DIRP=10;
int PULP=11;
float rot_number = 0;
float sig;

void setup() {

  Serial.begin(9600);
  pinMode (DIRM, OUTPUT);
  pinMode (PULM, OUTPUT);
  pinMode (DIRP, OUTPUT);
  pinMode (PULP, OUTPUT);
}

void loop() {
  while(Serial.available()){
    sig = Serial.parseFloat(); // sig is rotation number inputted from python
    if(sig > 0){
      rot_number = sig; // rotation number
      rotate_CW(rot_number);
      delay(1000);
      rot_number = 0;
      break;
    }
    else if(sig < 0){
      rot_number = sig;
      rot_number = abs(rot_number);
      rotate_CCW(rot_number);
      delay(1000);
      rot_number=0;
      break;
    }
    else{
      break;
    }
  }
}

void rotate_CW(float rotation_number)
{
  int numberOfRounds = int (rotation_number * 4000);

  for (int i = 0; i < numberOfRounds; i++){
    digitalWrite(DIRM,LOW);
    digitalWrite(DIRP,HIGH);
    digitalWrite(PULP,HIGH);
    digitalWrite(PULM,LOW);
    delayMicroseconds(100);
    digitalWrite(PULP,LOW);
    delayMicroseconds(100);
  }
}

void rotate_CCW(float rotation_number) // reverse rotation function
{
  int numberOfRounds = int (rotation_number * 4000);

  for (int i = 0; i < numberOfRounds; i++){
    digitalWrite(DIRM,HIGH);
    digitalWrite(DIRP,LOW);
    digitalWrite(PULP,HIGH);
    digitalWrite(PULM,LOW);
    delayMicroseconds(100);
    digitalWrite(PULP,LOW);
    delayMicroseconds(100);
  }
}

I connected four input/output cables attached to the step motor driver to Arduino. I wrote the code accordingly. DIRM stands for DIR-pin and DIRP stands for DIR+pin PULM means PUL-pin and PULP means PUL+ pin.
I first connected the Arduino Uno board, ran the Arduino code, and then ran the Python code.
Here is the terminal output appears in the Python program.:
motor rotates in the forward direction at 0.5 times.
motor rotates in the forward direction at 1.166667 times.
motor rotates in the forward direction at 1.333333 times.
motor rotates in the forward direction at 1.5 times.
motor rotates in the forward direction at 0.833333 times.
motor rotates in the forward direction at 0.666667 times.
motor rotates in the forward direction at 1.333333 times.
motor rotates in the forward direction at 1.333333 times.
motor rotates in the forward direction at 0.666667 times.
motor rotates in the forward direction at 0.333333 times.
motor rotates in the forward direction at 1.666667 times.

When using the Arduino Uno board, the motor actually 'rotated' to match the output of this terminal, with 0.5 turns, 1.166667 turns, 1.333333 turns, etc.
But now I changed the board from Arduino Unoboard to Mega Board, and the motor didn't work.
It's not like there was an error message in particular, or the code didn't execute at all. Only the output message came from the above terminal output window, and the motor did not rotate.
I checked where the problem occurred. Through the serial monitor of the Arduino IDE, I directly entered the screw revolution value into the Arduino code and found that the motor rotated normally regardless of whether it was using the Arduino Uno board or the Arduino Mega board.
However, the attempt to run Python and transfer the screw revolution value data to Excel->Python->Arduino was only possible on the Arduino Uno board. When the Arduino Mega Board was used, the Python terminal output window still says 'N times' but the motor did not actually rotate.
I checked all the board rates and port names. Board rate settings and port settings were correct, but still motor does not rotate. I don't know where the problem is.
The megaboard I used is 2560 megaboard. My code is a mess, but I'd appreciate it if you could help me.

write a simple arduino sketch that runs the motor for one second, stops for one second, reverses motor for one second, stops for one second and repeats

Insert time.sleep(2) following  py_serial = serial.Serial(.... It may or may not have anything to do with your actual problem, but it is something you should do anyway, if nothing else to eliminate it as a question as to whether not it matters.


text:
Node MCU Esp12-E does not support server accept function
I am trying to get a web server to run on the ESP12E on the Node MCU variant, and following the example from the esp8266 documentation page here. But the code does not compile, throwing the following error message:
'class WiFiServer' has no member named 'accept'; did you mean '_accept'?

I'm relatively new to MCUs in general, and cannot find a solution for this on any website. Any help would be appreciated.

The 'latest' documentation applies for git master branch.
accept() is ready for the next release of Arduino esp8266. It will be version 3.1.0. Until then you can use server.available(). It works the same way as accept() in ESP8266WiFi library's WiFiServer.
I initiated the addition of server.accept(), because server.available() in esp8266 WiFiServer works as Ethernet library's server.accept(), not as server.available().


text:
Fluctuation in 4 half bridge load cell via combinator
I'm currently using a Sparkfun 4 Half-Bridge load sensor (50 Kg) with combinator and amplifier both are from the Sparkfun. Link:https://www.sparkfun.com/products/10245 (For Load Sensors)https://www.sparkfun.com/products/13878 (Combinator)
https://www.sparkfun.com/products/13879 (HX711)
Our application requires long-term use i.e 8 to 10 hours of load application and monitoring the weight change during this time. Is this possible to achieve the above requirement using these chips/amplifiers? As we have experienced a drift in the readings if a weight is placed for more than approx. 3 minutes.
We are using 4 half-bridge sensors, a combinator, and an amplifier.The issues I am tackling right now are,

Zero balance: Load sensor value exponentially increases or decreases after calibration(this is a cyclic thing and keeps happening). The error ranges usually from -20g to +40g.
Drift in reading: When the load is placed and kept for more than 3 minutes a drift is observed which increases with time and rises up to 50 to 60g.
Can you please assist in this matter?
have used different libraries. Results are the same.

how much weight is placed on the sensors?

@jsotola 9.2kg.

Can you post the minimal code that demonstrates each of your issues? Also a photograph showing the setup?

What is your anticipated error range based on the sensor data sheet and amplification? e.g., creep, zero drift, noise

Consider a change in temperature either the cause or partially the cause for weight drift.  This supplier web page talks about load cell temperature compensation.  There they consider a 2000lb load cell.  Their chart infers a 20 degree Fahrenheit change can cause an temperature uncompensated load cell to change about 1.5lb.

I took precautions and tried to maintain the same temperature throughout the test. So I don't think temperature is an issue in my case. Could it be the HX711? @st2000

If this answer does not solve your problem consider un-accepting it so that others may offer alternative solutions.  If you like this answer you can always up-vote it. There are many possible sources for fast and slow unexpected changes. Temperature is just one. Bad or under-rated power supplies is another. Bad voltage references. Air currents (many balances are built inside an enclosure). Vibrations (some balances are built with heavy bases). Also, you did not say over what period of time you saw variation. Or the total weight of the mass you tested with. This may help to answer you question.

Thanks for replying @st2000. Performed a couple of tests. The duration of the tests was between 40 to 60 minutes.
1)Zero balance test.
2)Full Scale
for zero balance the fluctuation was from -2 to 9 within 5 minutes and the maximum and minimum peak experienced in an hour were -4 to +12.
And the full-scale error was almost 50g over 1 hour.

Until you solve this problem, I do recommend un-accepting the my answer (and, if you like, vote it up) to encourage others to offer alternative solutions.  2. It is encouraged for you to edit your question to make it clearer as to what you are asking.  I would add the test weight of 9.2kg and the above times. 3. Where the changes random (i.e. 0g, -4g, 8g. 2g ...) or were they slow showing a trend (i.e. 0g, 2g, 6g, 8g ...)?


text:
how to save float with 3 decimal places
i am transmitting sensor data from my atmega328p to my esp8266. The Sensordata has 3 decimal places. The esp8266 sends this data to my pc and there I see only two digits. This is because the data is saved with two digits in the float variables.
Is there a way to save them with 3? The way to multiply and later to divide does not work because of some issues on my pc server so I need to hand it straight with 3 digits.

This is because the data is saved with two digits in the float variables.

No, it's not. It's because Serial.println() by default prints only 2 decimal places. You can specify the number of decimal places to print in the function:
Serial.println(myVal, 3);