text:
Attiny85, high output impedance, dim leds
I designed what I thought should be a very simple badge using the Attiny85 SU, schematic below:
The problem is the tiny doesn't seem to be sinking current properly. For testing I switched to a 20 PU on the breadboard and 100 ohm load resistors. At 3v supply this should give approximately 30 mA per pin, well under the rated 40 mA per pin and 200 mA total. However with the loads connected only pin 6 sinks any significant current, and appears to be higher impedance than it should be (1.6v across the resistor for 16 mA). The other pins seem to be very high impedance, they drop to ~7 mV (70 microamps) when the loads are connected. With the load resistors disconnected they function normally (digitalWrite HIGH = supply voltage - junction drop).
I'm using pinMode [this was a problem] (OUTPUT, N) [/this was a problem, should be (N, OUTPUT)] to set up pin N, and digital writes for on/off. I've been able to drive transistors before using an exactly similar setup, although admittedly these have much lower current requirements.
Anybody know what's going on here?
EDIT: Turns out I had accidentally swapped the order of OUTPUT and N in the pin mode command. Not sure why the compiler had no problems with this, but I am at least getting useful outputs now.
I'm gonna leave this up out of curiosity/etc, because I'm still getting higher impedance than I'd have expected on the outputs. With the 100 ohm load resistor, I'm only getting about 16 mA (expect closer to 25). Supply voltage from the CR2032 is ~2.48v under load.
Based on the graph on the datasheet (figure 22-19, PG 182), at 25 c ambient (currently 20) I should expect a voltage drop from VCC to output somewhere on the lower end between 400 and 600 mV when supplying 15 mA, but my readings at 16 mA above represent a voltage drop of almost 900 mV across the Tiny. Additionally the LEDs drop 2v at 10 mA, for which you'd expect approximately 300 mV drop across the tiny according to the graph, but mine is dropping almost 500 mV. I'm not sure if this is something in my setup or if the characteristic curves on the datasheet simply aren't that accurate for production models.

Note that output pins on most AVR-based Arduinos are supposed to source/sink a max of 20mA, with an ABSOLUTE max of 40mA. 40mA the current level at which you are likely to burn out the output. For normal use you should stick to a 20mA/pin limit (and also watch the total current limit of 200mA as you mentioned.)

The answer to the main problem was that I had used pinMode(mode, number) where the actual syntax is pinMode(number, mode). Presumably modes can be selected by number and the compiler though I wanted to set an undefined pin to mode number.
TL;DR the correct syntax is pinMode(4, OUTPUT) to set PB4 (pin 3) to output.
The problem of higher than expected output impedance remains, though the outputs are now quite usable. As detailed in the edit, I'm still experiencing voltage drops across the microcontroller nearly 2x higher than I'd expect from the graph on the datasheet for a given current.

Thanks for taking the time to post a self-answer after finding the cause of your problem. Not many people do that. (Voted)

You already found your problem. I am answering only to provide some
insight on why you were experiencing the symptoms you had.
pinMode() takes two integer arguments (two uint8_t to be precise).
The names INPUT, OUTPUT and INPUT_PULLUP are just macros for 0, 1
and 2 respectively. This is why the compiler accepts your code with the
arguments swapped.
On the AVR microcontrollers, setting a pin's output register to HIGH
on a pin that is configured as input has the effect of turning on the
internal pullup. Thus
digitalWrite(pin, HIGH);

has the same effect as
pinMode(pin, INPUT_PULLUP);

on an input pin. When you do this, the pin will source (not sink) a very
small current. The pullup resistance is typically of the order of
30 kΩ, and this is why you get such a small current.

Ok, that makes sense. I was wondering why it worked at all. Well reasoned as to why reversing the parameters created a high-impedance output. (Voted)

Awesome explanation, it also explains why PB1 (pin 6) was functioning normally since it would have been getting pinMode(1, 1) with the macro


text:
ARDUINO flashing lights
I'm making a circuit with my Arduino so that when it receives a '1' or
'2' or 'a' it turns on or off the LEDS. But I wanted the lights to
flash and do not know how to do loops in loops or if that's what I
need to do at all. Any help would be very much appreciated and the
code will be below.
//-----------------ELECTRONICS-----------------//

int left = 11;
int stoP = 12;
int right = 8;

//variables
int Received = 0;
int left_state =0;
int stoP_state = 0;
int right_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(left,OUTPUT);
  pinMode(stoP,OUTPUT);
  pinMode(right,OUTPUT);
}

void loop() {

  if (Serial.available() > 0)
  {
    Received = Serial.read();
  }

////////////////LEFT//////////////////

if (left_state == 0 && Received == '1')

{
  digitalWrite(left,HIGH);
  Received = 0;
  left_state = 1;
}

if (left_state == 1 && Received == '1')

{
  digitalWrite(left,LOW);
  Received = 0;
  left_state = 0;
}
///////////////////////////////////

///////////////stop////////////////

if (stoP_state == 0 && Received == 'a')

{
  digitalWrite(stoP,HIGH);
  Received = 0;
  stoP_state = 1;
}

if (stoP_state == 1 && Received == 'a')

{
  digitalWrite(stoP,LOW);
  Received = 0;
  stoP_state = 0;
}

 ////////////////////////////////

 ///////////right///////////////

if (right_state == 0 && Received == '2')

{
  digitalWrite(right,HIGH);
  Received = 0;
  right_state = 1;
}

if (right_state == 1 && Received == '2')

{
  digitalWrite(right,LOW);
  Received = 0;
  right_state = 0;
}
}

You could turn off the LEDs after a short time using millis(). You can look at the BlinkWithoutDelay example, that comes with the Arduino IDE

As chrisl already mentions, you have to use the millis function.
Besides setting a pin HIGH, you keep a variable for each state for the start time and set it when the corresponding state is set to 1:
unsigned long left_start_time = millis();

Than within the loop you check for each state when it is 1 (on or actually flashing) and switch the pin on or off, example:
if (left_state == 1)
{
    digitalWrite((millis() - left_startTime % 400) < 400 / 2) ? HIGH : LOW);
}

What this does is for the first half of the 400 ms period (time % 400 < 200) to be HIGH, and the last half (time % 400 >= 200) to be LOW.
Improvements:

Do not use 400 but a constant value.
Do not use separate variables for left/right/stop, but put them in a structure, keeping the state, time, pin, and activation key ('1', '2', 'a') together.
If you do the above, you can make your program more simpler (and avoid code duplication) by parameterize your code.

source: Stack Exchange

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

sort: votes


text:
Cryptic compiler errors
I'm getting the error:
    left_hand:3:20: error: expected ']' before ';' token
     #define HAND_ROWS 5;
                        ^

on this code:
    #include <Keyboard.h>

    #define HAND_ROWS 5;
    #define HAND_COLS 6;
    #define ROW_PINS {9, 8, 7, 6, 5};
    #define COL_PINS {10, 16, 14, 15, 18, 19};
    #define LOOP_SPEED = 10;

    const char keymap[HAND_ROWS][HAND_COLS] = {{0xB1, '1', '2', '3', '4', '5'},
                                               {0xB3, 0x81, 'q', 'w', 'e', 'r'},
                                               {'6', 0x80, 'a', 's', 'd', 'f'},
                                               {'7', 'z', 'x', 'c', 'v', 'b'},
                                               {'h', 'j', 0x82, ' ', 'k', 'l'}};
    boolean pressedKeys;
    int keymapIndex;

help, please? This makes no sense to me...
If I try to use Keyboard.LEFT_SHIFT and equivalent constants for the hex-codes in the keymap, they tell me 'expected unqualified-id before numerical constant'
What does this even mean? I'm so lost...

There's no semicolon needed on a #define.

You mustn't terminate a #define with a ;.  Semicolons are for C and C++ statements. #define is a preprocessor statement.
#define creates a literal string replacement, so when you use it you end up with:
const char keymap[5;][6;] = {...

which is, of course, wrong.

Thank you for catching my beginner mistake!

It's no beginner mistake... I have done it myself from time to time... the fingers go on automatic...

Guess that's the fate of Java programmers who move to C, or at least that's the case for me.

@LowellCamp Or the fate of people that jump between three or four programming languages at once - and do their programming in the wee small hours of the morning ;)

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


text:
millis and micros always returns 0 (or other constant)
On an Arduino Uno, I have a sketch akin to this:
void setup()
{
    // Generate some PWM signal on Pin 5, using Timer 0.
    pinMode(5, OUTPUT);
    TCCR0A = 0b00110011;
    TCCR0B = 0b00001000;
    OCR0A = 0x80;
    OCR0B = 0x20;
    TIMSK0 = 0b00000100;

    Serial.begin(115200);
}
void loop()
{
    // Just write the result of millis to the terminal.
    unsigned long ms = millis();
    char s[100];
    sprintf(s, "%lu\r\n", ms);
    Serial.print(s);
}

Setup timer 0 to generate a PWM signal, setup the serial port, constantly print the result of millis() to the terminal.
The numbers printed to the console do not increase as expected, but stay "0".
Similarly, if I use micros, "4" is printed constantly.
How's that?

millis and micros appear to use timer 0 internally. Using that timer to also generate a PWM signal messes with their ability to function properly.
The solution is to either use a different timer to generate the PWM signal, or to roll a custom equivalent of those functions.
Why does the official arduino documentation not specify that millis and micros occupy timer 0?
Why are there no Google results mentioning timer 0 when searching for "arduino millis returns 0", "arduino millis constant", "arduino millis not counting" and the like? (There are results with the same symptoms, but for different reasons.)
Who knows.

PWM with analogWrite() and millis() work together on Uno if you don't change Timer0. every ATmega timer handles a pair of pins. Timer0 has 5 and 6 on Uno/Nano/Mini https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/#_notes_and_warnings

You are supposed to use analogWrite() for generating the PWM, and only access the low-level peripherals if you know what you are doing. I agree that mentioning Timer 0 in the millis() doc would be good. Note that a google search on “millis timer 0” return many relevant results.

@Juraj analogWrite does not allow changing the period (because that would then mess with how fast millis would count). But thanks for mentioning it; others might find it useful for there purpose.

In 2014 I wrote a library to use Timer 2 as a millis()/micros() replacement. You can read about it on my personal website here: https://www.electricrcaircraftguy.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html. If you use this, you could use Timer 0 for whatever you want. Granted, Timer 2 and Timer 0 are both 8 bit timers with the same level of functionality, so there's no real advantage to using one over the other for timing, but my implementation has 0.5us resolution instead of 4us resolution (8x better) at the cost of more frequent ~4~5us jitter (8x more frequent).

Regarding which timer does what, you have to get in the habit of looking at the source code to see when, how, and why hardware resources like timers and counters, input capture, output compare, UARTs, watchdog timers, external interrupts, pin change interrupts, etc., are being used. Just off the top of my head: millis()/micros() is timer 0, servo library is timer1, tone library is timer 2 I think, etc.

Why does the official arduino documentation not specify that millis and micros occupy timer 0? - probably one reason would be that this would vary from processor to processor. If you start fiddling with the hardware registers you might expect things to not behave as documented. For example, if you change the registers pertaining to serial output, then writing to Serial might not work.

@NickGammon That wouldn't stop me from writing that info down for each controller. Arduino (the company) knows which processors they have on their boards.


text:
Why does Arduino IDE take so long to open?
I have Arduino IDE, version 1.8.10 (Windows 10 x64, 8GB RAM, i5-7200 @2.5GHz) on a network drive mapped to D:, on a 100Mbit wired network and fast file server.
If I navigate to the network shared folder and launch 'arduino.exe', it takes at least 2 minutes for the IDE to appear.
This seems totally unreasonable considering the entire arduino.exe file is only 395kB. Seems more likely the IDE is waiting for something until a timeout occurs, before finally loading up the IDE.
What can be causing this and how can I diagnose it?
As an aside, it seems the compilation process takes longer than it should too, even for programs that use no external libraries and are very short.

dowload sysinternals process monitor and run it ... it will log everything ... see what the Arduino IDE is doing ... https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite

The libraries and applications used and called sum up to considerable sizes. As @jsotola said, use Sysinternal's process monitor or the task manager to watch these sizes.

arduino.exe is only a launcher. it starts the Java Virtual Machine. Arduino IDE is written in Java. antivirus program can slow down the compilation, because of many process and files opened

Did you try installing everything on a local drive? (including all libraries) ?

and the Java used is bundle with IDE installation so on the network drive too

The simple answer is "libraries".
Every time you start the application, all files inside your library folder are parsed.
And this is not done over your OS, but over the Java-Virtual Machine.
So it is not just slow, it is ultra-slow! Since your antivirus will probably also check each file.
Once, all files was read (maybe 1/2 of the time spent by your Arduino start), all your sketch folders are parsed.
At the end Windows devices and Arduino specific libraries are loaded.
On my Arduino IDE (is installed locally), on each starts, the Arduino IDE checks about 300.000 files. I need up to 20 seconds to load everything, before I can use the IDE.
What can you do?
Base

do not waste the library folder with unused libraries
NEVER put some documentation or non-Arduino files in your sketch folder, as they are all parsed by the IDE
disable the Antivirus for the folders:

Arduino
libraries
sketch

Advanced
If you open always the same project, you can for example edit the "preferences.txt" file.
If you remove some parameters from the preferences.txt, you will be able to lauch your IDE much faster. I created an application that statrs your Arduino IDE with personalized settings:
https://github.com/Adrianotiger/ArduinoIDE_Launcher
This application can remove some preferences like:

boardsmanager
last.* settings
recent sketches

when the Arduino starts, so it will be launched faster. But if you set the preference sketchbook.path, you can start your Arduino IDE 3-4 times faster. Just place the folder with your project libraries and you can start the IDE much faster.


text:
Arduino MKRZero malfunctioned after trying to load a program
I have an Arduino MKRZero that I tried to load the following program into:
#include <FastLED.h>

#define NUM_LEDS 60
#define ledPin 4;

AudioFrequencyMeter meter;
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  meter.setBandwidth(70.00, 1500);
  meter.begin(A0, 45000);
  FastLED.addLeds<WS2812B, ledPin, RGB>(leds, NUM_LEDS);
}

void loop() {
  float frequency = meter.getFrequency();
  Serial.println(analogRead(A0));
}

After which, the Arduino IDE said:
"Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload."
And windows gave this message:

The board is dead for all I can tell. The light still comes on when I connect it to my computer and when press reset, windows makes the "you just plugged something in" sound, but it doesn't work. Can anyone tell me what happened?

Maybe the board was dead before you programmed it? The LED is probably fed by the 5V supply. As long as this supply is not shorted, the LED will shine, but not tell anything about the rest of the electronics.

@Huisman No, I used the board to only light up the led before including the bit with the frequency meter. That worked just fine.

Did you change the baud rate of the serial port you were using to communicate with the device?

@Tyler I don't know what that means. No, I didn't do anything like that.


text:
Cannot flash Arduino Bootloader on SAMD21G with STLink via SWD programming and openOCD
I'm trying to flash the Arduino Bootloader on a bare ATSAMD21G with STLink via SWD programming and OpenOCD.
These are the steps that I took:

Create *.hex file to flash with ArduinoCore-samd repository
Connect SWD pins from ST-Link to the ATSAMD21G pins

Execute OpenOCD command
openocd -f interface/stlink-v2.cfg -c "set CHIPNAME at91samd21g18; set ENDIAN little; set CPUTAPID 0x0bc11477; source [find target/at91samdXX.cfg]" -c "init" -c "reset init" -c "load_image {/Path/To/ArduinoCore-samd/bootloaders/zero/samd21_sam_ba.hex} 0 ihex" -c "verify_image {/Path/To/ArduinoCore-samd/bootloaders/zero/samd21_sam_ba.hex} 0 ihex" -c "reset run" -c "exit"

Command Line output:
Open On-Chip Debugger 0.10.0
Licensed under GNU GPL v2

For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select <transport>'.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
none separate
adapter speed: 400 kHz
Info : Unable to match requested speed 400 kHz, using 240 kHz
Info : Unable to match requested speed 400 kHz, using 240 kHz
Info : clock speed 240 kHz
Info : STLINK v2 JTAG v17 API v2 SWIM v0 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 2.922730
Info : at91samd21g18.cpu: hardware has 4 breakpoints, 2 watchpoints
target halted due to debug-request, current mode: Thread
xPSR: 0x61000000 pc: 0x00000f10 msp: 0x20007ffc
in procedure 'reset'
in procedure 'ocd_bouncer'
in procedure 'ocd_process_reset'
in procedure 'ocd_process_reset_inner' called at file "embedded:startup.tcl", line 248
in procedure 'at91samd21g18.cpu' called at file "embedded:startup.tcl", line 331
in procedure 'ocd_bouncer'

5824 bytes written at address 0x00000000
downloaded 5824 bytes in 0.132341s (42.976 KiB/s)
target halted due to breakpoint, current mode: Thread
xPSR: 0x61000000 pc: 0x2000002e msp: 0x20007ffc
verified 5824 bytes in 0.481737s (11.806 KiB/s)
in procedure 'reset'
in procedure 'ocd_bouncer'
in procedure 'ocd_process_reset'
in procedure 'ocd_process_reset_inner' called at file "embedded:startup.tcl", line 248
in procedure 'at91samd21g18.cpu' called at file "embedded:startup.tcl", line 331
in procedure 'ocd_bouncer'

Really unsure what steps I am missing as it does not seem to flash the bootloader at all. I cannot detect M0 on the USB port after trying to execute the OpenOCD command. Thanks!

Actually the verification message seems to indicate the code was flashed.  You may need to look at non-code configuration settings, possible errors in the code, clocking, board or electrical issues, etc.  Perhaps you should try using SWD to load a test program that flashes an LED or generatures actual UART output without a bootloader or needing USB to work.


text:
How to compare an incoming byte from cool terminal as modbus hex value and compare it with a predefined value in set in the program?
My Input from Cool terminal is
    05 03 00 01 00 02 94 4F
I should be able to read this input 05 03 00 01 00 02 94 4F compare with the same(05 03 00 01 00 02 94 4F). If the incoming value(05 03 00 01 00 02 94 4F) and the predefined value(05 03 00 01 00 02 94 4F) are the same it should print the hex value like

05 03 04 43 65 BA 7D 04 E8

I tried to code it but i could'nt get the value.
Here is my code in Arduino
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
      static char buffer[1024];
      static size_t length = 0;

      if (Serial.available()) {
        char c = Serial.read();

        // Otherwise buffer the incoming byte.
        //else if (length < sizeof buffer - 1) {

        Serial.write(c);  // echo
        buffer[length++] = c;
      }
    }

You didn't include your code. And what does "couldn't get the value" mean?

Did you read what you copy & pasted? (edit question, select code, press ctrl-k to align). What means 'read this input compare with the same' ? And where is the predefined value in the code (or is the predefined value something else? If so, what exactly?

I have edited it would be good for you to understand now.

how are you determining the value to print? .... ar you doing some calculation?

@jsotola I am not doing any calculation. I just wanted to print the answer

the printed hex values are different from the input hex values ... that indicates data manipulation of some kind

Yes Yes yes !!!! The printed hex values are different because I am just printing them( and I am not mofifying anything).


text:
Reading port register and print
I am playing with port registers directly to improve speed on a Arduino micro. I have no problem writing them, like
PORTF &= B11101111

However, when I try to read and print it, things get funny and I hope to know why.
Observation 0:
byte dat = PORTF;
Serial.print(dat,BIN);

produces a single 0, where I am expecting 8 0's as for a byte. And, even when I check that a digitalRead correctly gets a 1 from PF5 or A2,
Observation 1:
byte dat = PORTF;
Serial.print(dat,BIN);
Serial.print(dat,BIN);

produces a compiler error like
...cores\arduino\Print.cpp: In function 'println.constprop':
...cores\arduino\Print.cpp:143:1: internal compiler error: Segmentation fault
}
^

To reproduce your compiler problem, please post a minimized sketch showing the error. And tell us which PC system (Win, Linux, Mac) you're using. [edit] your question, don't put additional information in a comment, please!

the compiler error is the error of the compiler. use Arduino boards package 1.6.21. this is not the right way to work with registers. and PORTF &= B11101111 is PORTF = PORTF & B11101111. so if PORTF is all zeros, the result is zero

https://arduino.stackexchange.com/questions/70104/adc-register-always-returning-high/70108#70108

The compiler error is a compiler bug. What version of the IDE are you using? If it's not the latest, you may want to upgrade.

@EdgarBonet, it is a problem of avr-gcc used in Arduino AVR core 1.6.22 and 1.6.23. the version in AVR core 1.8.0 and 1.8.1 has the problem of 'over-optimizing'. (1.8.0 was next after 1.6.23. 1.7.x was skipped).

@Juraj: What do you mean by “over-optimizing”? Another compiler bug?

@EdgarBonet, this one https://arduino.stackexchange.com/questions/70597/function-parameter-of-type-int-not-working-as-expected#comment153249_70597 and one more was on Arduino Forum

The function Serial.print() and it's siblings cuts all leading zeros. So 0b00001111 get's displayed as 1111 and 0b00000000 as 0. So you actually get what you expect. It's just printing different.
Also, when reading PORTF, you actually read the output state of the pins, as you have set it before. If you want to read the real input level of the pins, you should read PINF instead.
Though I don't know, where that segmentation fault came from.


text:
When does the ADC take the reading?
I'm experimenting with the "2 pin capacitance meter" and trying to make it more accurate. Currently I've made the Arduino read 62.5 ns intervals but this means the time for the ADC to read is taking up a bigger part of the interval. I'm currently using a prescaler value of 8 on the ADC. Unfortunately reading continuously isn't really an option so I am limited to around 8us of read time instead of 6.5us. This isn't that much of a problem since I know that the read will take near 8us from experiments, however I do not know when during that 8us interval the actual reading takes place.
So that is my question, does the adc take the average value during those 8us, does it "lock" the bits at the beginning or when exactly does the reading occur?
Link to capacitance meter, specifically the third one: http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/#comment-363733)

The timing of analogRead() is not critical in the “2 pin capacitance meter” program. Only the time between pinMode(OUT_PIN, INPUT_PULLUP); and pinMode(OUT_PIN, INPUT); (variable t) needs to be known with high accuracy.

@EdgarBonet Why exactly is the timing to pinMode(OUT_PIN, INPUT); the important time, we do take a reading with the ADC after this, does changing the pin mode ”trap” the voltage or what’s going on here?

Yes. The INPUT_PULLUP pin mode charges the capacitor through the internal pullup resistor. The INPUT mode stop the process and, as you say, “traps” the charge in the capacitor. The time between the two mode changes is the charging time, which is the relevant time for solving for the capacitance.

@EdgarBonet Thank you! This knowledge greatly increased the accuracy I am able to achieve. I'm probably just chasing cars at this point, but you don't happen to know when the the voltage is "traped". I'm using PORTC to switch the pullup resistor on and off, and it appears it take only 1 clock cycle, however I am unsure if it's best to measure time before,after or in-between the switches. I'm currently measuring time after I switch.

Read the time either before or after switching PORTC. It doesn't matter as long as you do it consistently. If you took one reading before switching on the pullup and the other after switching it off (or vice-versa), you would have a small timing error. For maximum reliability, do this with interrupts disabled, e.g. cli(); PORTC |= _BV(PC2); start_time = TCNT1; sei();

@EdgarBonet Can switching off the interupts mess with the TCNT2 updating? I mean it’s not an interrupt which causes it to reset to 0 when it overflows in CTC mode, right?

No, TCNT2 doesn't rely on an interrupt for resetting.

The ADC is a "Successive Approximation" type ADC.  It works by:

Taking a snapshot of the incoming voltage in a small capacitor
Generating a reference voltage
Comparing the voltage in the capacitor to that reference voltage
Refining the reference voltage
Go back to 3 until you have the accuracy you desire.

There's lots of "time" involved there:

The capacitor can only store the voltage accurately for so long before the self-discharge (leakage current) causes the voltage to drop (this defines the maximum amount of time you can take to do a reading)
Each refining of the reference voltage and comparison thereof takes one ADC clock tick. There are a few "setup" clock ticks as well. This defines the minimum number of ADC clocks that you need to take a reading (13)
The DAC and comparator take a certain amount of time to operate each clock tick - this limits the maximum clock frequency the ADC can run at.

So you have a "sweet spot" of speed (like the "goldilocks zone" of the solar system). Set the ADC too slow or try and get too high a resolution out of it and you lose accuracy due to voltage droop on the capacitor. Set it too fast and the DAC can't keep up and you lose accuracy due to the comparison voltage not being right.
Well, that's the internals. Then on top of that you have the Arduino API. That adds an entire other layer of complication. analogRead() is a blocking operation.  It:

Congfigures the IO pin (if needed)
Turns on the ADC (if needed)
Configures the ADC MUX to the right channel
Starts a conversion
Sits there twiddling its thumbs for a while
Reads the conversion result
Returns it to you

And it does that (except maybe 1 and 2) every time you take a reading.  That's fine for reading a potentiometer, or an LDR, etc. But rubbish when you want to do fast, time-based, readings.
Instead you need to push the envelope a little and step away from the Arduino API.  Much of what the ADC does is done without intervention of the CPU. Manually configuring the ADC to read continuously and trigger an interrupt when the conversion is done, and then using that interrupt to grab the result of the comparison and start a new one (or use a timer interrupt to read the previous result and trigger a new reading) will give you much more control over the ADC and exactly when things happen.
So, now to answer your main question of "when during that 8us interval the actual reading takes place.", in the context of how the ADC works:
At the moment the SAH capacitor is detached from the MUX to start the comparison sequence.
When exactly is, though, is subjective.  If you use the Arduino API (analogRead()) then it's at some point near the start of the function call, but not at the start of it.
If you configure it manually and trigger it from within a timer interrupt, it's on the second (out of 13) falling edge of the ADC clock after ADSC has been set HIGH.
There are also "Free Running" and "Auto Trigger" modes whose timing is the same as for a single conversion.  Note that the first conversion performed in any mode imposes a "run-in" clock sequence where the ADC MUX and reference voltage DAC are initialised.
All this timing can be found in figures 23-4 and 23-5 on page 209 of the ATMega328P datasheet.  On page 210 there is a handy table that gives you how many ADC cycles from the start of a conversion the Sample And Hold occurs and how long the conversion takes in clock cycles.
For best throughput you want to use "Free Running" mode and read and store the ADC result in the interrupt the ADC triggers.  For most accurate and controllable timing you want to use Auto Triggered mode with a timer for the trigger source, and again read the result in the ADC interrupt.

Wow, this was an amazing answer :D Extremely detailed :D
I don't think Free running mode will work for me, since the analog pins will be used for output and analogRead. However, I did come across the low noise interupt mode which works very well. However, I cannot measure it's speed (since all timers go dead), do you happen to know how long it takes for the arduino to go to sleep and start the ADC? :s


text:
Atmega328p Uploads via ISP but not bootloader
I'm trying to upload a bootloader to my atmega328p on a custom pcb containing external oscillator at 16MHz. It is possible to upload program via ICSP pins using Arduino as ISP (Official Arduino Uno) but not possible to upload a bootloader. This pcb needs bootloader as it will be used via FT232RL interface.
I've tried to upload bootloader at 115200 baud rate but that did not read any device signature. Also exact definition of my IC is "ATMEGA328P-AU TQFP-32 8-bit 20MHz", if it helps.
P.S That exact definition says it is 20MHz but I suspect that's correct as I don't entirely trust that shop.
Thanks in advance
Upload log
Sketch uses 1626 bytes (5%) of program storage space. Maximum is 32256 bytes.
Global variables use 192 bytes (9%) of dynamic memory, leaving 1856 bytes for local variables. Maximum is 2048 bytes.
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem14101 -b115200 -D -Uflash:w:/var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/deniz/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem14101
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "/var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex"
avrdude: writing flash (1626 bytes):

Writing | ################################################## | 100% 0.27s

avrdude: 1626 bytes of flash written
avrdude: verifying flash memory against /var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex:
avrdude: load data flash data from input file /var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex:
avrdude: input file /var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex contains 1626 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.21s

avrdude: verifying ...
avrdude: 1626 bytes of flash verified

avrdude done.  Thank you.

Bootloader log (P.S. all sync attempts happen at the same time)
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/cu.usbmodem14101 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/deniz/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem14101
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x60
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x66
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x78
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1e
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x06
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x7e
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe6
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x80
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x98
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x80

avrdude done.  Thank you.

Have you tried to "Burn Bootloader"? Because by default it uploads compiled sketch without bootloader (it can be changed in board settings to use hex file with bootloader too).

That output is from Burn Bootloader button specified in Arduino IDE. So is it possible to upload bootloader and sketch at the same time?

In the build direcotry there'll be another hex file like this: sketch_dec06a.ino.with_bootloader.hex (however can't remember where it should be set exactly)

Yep I found it. I'll be trying that one. Also will there be a problem with flashing sketch with bootloader without redefining fuse-bits?

Also if you can write your comment as an detailed answer I can approve if it works

And are you sure the first is really working? The programmer = arduino is usually bootloader. You should see that stk500v1 too if you are using "Upload Using Programmer" (programmer must be set to Arduino as ISP). Maybe you've just uploaded it directly into the arduino that should be an programmer instead (and removed that ArduinoISP sketch from it)

I've uploaded ArduinoISP sketch again and tried to upload only the sketch, with_bootloader and only bootloader but no luck. I've updated the upload log in the question. Seems like programmer can't read target's device signature. I've successfully uploaded the bootloader to two of the same PCBs but no luck on this one.

If you have time to look into this more deeply I can move this comment section to a chat. I would be very happy if it's possible.

Let us continue this discussion in chat.

The first issue might be in Upload log. There is mentioned programmer = arduino (in version before edit). That means you might be uploading code into the wrong Arduino. So there is no ArduinoISP sketch and it won't work (getsync() errors)
Check if the upload is working between two arduinos, that should opted out wrong wiring on the programmer side and so on.
And as it's self made board, there might be some issues with wiring, omitting bypass capacitors (as it turned out in chat discussion - it was the main issue)


text:
Make OTA work with Arduino Uno Wifi
I just bought a Arduino Uni Wifi Rev. 2, with the itention of doing over the air uploads to the devices.
By reading the official Gettings started with the Arduino Uno Wifi guide, I thought the process was just to power the devices, connect to the SSID, then browse to it's IP and set it up.
But it seems like this is not the case, and that others have made this same mistake. This Arduino device doesn't create network by default, we have to upload a sketch that connects to our wifi.
So I have two questions.

What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?
How can I get OTA support for my particular board?

have you gone through this? https://www.arduino.cc/en/Guide/ArduinoUnoWiFi

@SimSon Yes. That's the article I linked to in my post. It's only for Arduino Uno Rev. 1 it looks like.

What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?

The first Uno WiFi was made in 2016 by arduino.org. It is retired and not available in stores.

How can I get OTA support for my particular board?

The OTA support for Uno WiFi Rev. 2 is ready or almost ready, but the required additions are not merged in GitHub firmware and library repository even if they wait some months now. It looks like Arduino focuses on something else.

Thanks for this. Do you have a link to the Github issue/pull request for that feature, so that I can follow it?

As far as I understand, it should be possible to upload a sketch to the arduino over USB, that connects it to your wifi, so that it then can support OTA uploads. Do you have any insight into that?

not for Uno WiFi Rev 2. for many others https://github.com/jandrassy/ArduinoOTA

and plans for Uno WiFi Rev 2. https://github.com/arduino/nina-fw/issues/36

https://docs.arduino.cc/retired/getting-started-guides/ArduinoUnoWiFi

@Bruno that is for Uno WiFi Developer Edition, not for Uno WiFi Rev2


text:
How to check if two device has the same address on I2C?
I start a new project with Arduino UNO and MCP23017 expander. Using this, I can connect 8 chips on Arduino, by selecting different addresses ( from 0x20 to 0x27 ).
My question is, if I connect two MCP23017 chips with the same address, there is any way to see somehow that I have two chips with the same address ?
I am using a standard I2C scanner in Arduino code, but is nt return me if I have multiple chips with the same address, he see only one chip for example !
Can you please help me with some ideas to check how man chips are connected with the same address?

You can probably tell by the way you wired it and see what address you configured your slaves to be. Slaves have "address" pins.

It's my understanding that duplicate I2C addresses prevent the master from communicating from the slaved devices, so the answer is no.
Instead, connect the devices one at a time, run the I2C scanner, note the address for each, and take note of any duplicate addresses.

If both devices are the same, are configured the same, and respond the same, then it is impossible to tell if there is one, two, or four hundred.
However if there are differences between the two devices you will get corrupt data.
I2C is an open-drain protocol. For a device to send a 0 it pulls the data line low. For it to send a 1 it lets the pullup resistor pull the line high.
So if you have two devices and they both send a 1 you get a 1. If they both send a 0 you get a 0. But if one sends a 1 and the other sends a 0 then the 0 will "win" and you will see a 0.
Since most devices, when powered up, revert to some pre-defined default state, chances are you will always see multiple devices of the same type on a single address as just one device.
One possible way around it is to have some control signal that is unique to each device which will cause them to only respond one at a time. For example, you might choose to pull all the RESET pins of the slaves LOW and raise each one in turn to see what address the device is on. If you then see two that respond on the same address then you know you have a conflict and can report it as such.
Another possibility is to connect the address control pins to IO pins and communicate with all the slaves on the same address - but you only set one slave's address to the "live" address at a time. That also gives you the ability to have far more than just 8 slaves.


text:
Button circuit draws all power away from LEDs
I'm very new to Arduino, so please forgive me if I don't know the proper terms for things.
Whenever I press the button on the board, the LEDs all shut off.

I can't host the image files on imgur, and I don't know how well Flikr will work with it.
Now:
The resistors being used are 220 ohm resistors for the LEDs. The one for the button is a 10k ohm resistor.
This also happens without a resistor in place. I tried simply replacing the button with a wire from the positive to a row, with a wire leading from there to another row, back to ground.
What do I do to fix this?
Edit: Sorry about the images being extremely low quality, they've been updated.
Here's the code, but it's mostly irrelevant:
//DEFINE STUFF BABYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
int ButtonState2 = 0;
int ButtonState1 = 0;
int ButtonState0 = 0;
const int ButtonPin2 = 2;
const int ButtonPin1 = 1;
const int ButtonPin0 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
  digitalWrite(7, LOW);
  digitalWrite(6, LOW);
  digitalWrite(5, LOW);
  digitalWrite(4, LOW);
  digitalWrite(3, LOW);
  pinMode(ButtonPin2, INPUT);
  pinMode(ButtonPin1, INPUT);
  pinMode(ButtonPin0, INPUT);
  Serial.print(78);
}

void loop() {
  // put your main code here, to run repeatedly:
  ButtonState2 = digitalRead(ButtonPin2);
  ButtonState1 = digitalRead(ButtonPin1);
  ButtonState0 = digitalRead(ButtonPin0);
  if (ButtonState2 == HIGH){
    digitalWrite(13, HIGH);
    }
    else{
      digitalWrite(13, LOW);
      }
}

As per your statement, wire from the positive to a row, with a wire leading from there to another row, back to ground.
That describes a short circuit between V+ and ground.
Remove either the ground wire or the positive wire.

This fixed the issue. I removed the ground wire, and the resistor.

You have your switch shorting both pin 1 and V+ to ground when you press the switch. Do not do that.
The resistor you have isn't doing anything at all. It isn't really a meaningful part of your circuit. It is in the middle of one of the rows of your breadboard. All the pins in the same side of one row of the breadboard are connected to each other.
In your breadboard, every row, from 1 to 30, is divided into columns a-e and columns f-j. All the pins a-e in a row are connected to each other, and all the columns f-j are connected to each other. You have one end of your resistor in row 7, column g, and the other end in row 7, column h. So the resistor is short-circuited by the breadboard, and doesn't serve any purpose.
It's as if both ends of your resistor are connected to different points on a wire. If you were to measure the resistance between the leads of that resistor as it's connected, you'd get zero ohms.
You need to rearrange your wiring so you have a wire coming from +5V to one row of your breadboard. Let's call that the +5V row. Have a 10K resistor with one lead into another pin in that row, and then put the other end of the resistor into another row. Let's call that the pull-up row. (It's weakly connected, through a 10K resistor, to +5V. Now plug your switch into that row, also. Finally, run a wire from the opposite side of the switch and into ground.
Make sure to configure the pin as an INPUT.
If you set it up as an OUTPUT, set it to HIGH, and close the switch, you'll short the pin output to ground, probably destroying that pin's output driver. DON'T DO THAT.
Now, when the switch is open, the pull-up resistor weakly connects the pin to +5V, so you get a HIGH signal. When you close the switch, it shorts the pin to ground, pulling the input LOW.
Note that you could skip the connections to +5V and set the pin to INPUT_PULLUP mode instead. INPUT_PULLUP mode connects the pin to +5V internally, through a high ohm resistor.


text:
PWM using timer3 for servo control won't generate any output
I'm making a program for a small robot arm controlled by four servos.
Problem: I need for PWM outputs, timer1 has three so i need to use timer3 for the last one
The main program and the timer1 outputs work great, the robot arm is functional. My problem is in the initialization of the PWM's. The PWM for timer1 is set to phase-correct, 64 pre-scaling and using WGM1[0-3] to 1010 so that i can use ICR1 as the top value, leaving OCR1[0-2] for counting up so output is on OCR[0-2].
According to the ATMEGA 2560 data book I should be able to initialize an identical PWM with timer3 with just one output in just the same way, but it just won't give me any output at all on OC3A.
Any help is greatly appreciated! :)
PS this is for a class project, so no servo libraries, and no major changes to the program (the current code is already approved by my professor, also the due date is in 24 hours so i don't have the time. Yes I know that sounds like trouble, but the project is technically done, I'd just really really like to get a full range of motion on my little Plexiglas robot)
PWM.c:
// INITIALIZE PHASE CORRECT PWM ------------------------------------------------------------------------------
void initPWM()
{
    DDRB |= (1<<DDB7);      // Output pin 5 OC3A
    DDRB |= (1<<DDB5);      // Output pin 11 OC1A
    DDRB |= (1<<DDB6);      // Output pin 12 OC1B
    DDRB |= (1<<DDB7);      // Output pin 13 OC1C

    // Initialize TIMER1 for OC1A, OC1B, OC1C:
    TCCR1A |= (1<<COM1A1)|(1<<COM1B1)|(1<<COM1C1)|(1<<WGM11);     // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
    TCCR1B |= (1<<WGM13)|(1<<CS11)|(1<<CS10);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal
    // Initialize TIMER3 for OC3A
    TCCR3A |= (1<<COM3A1)|(1<<WGM31);                            // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
    TCCR3B |= (1<<WGM33)|(1<<CS31)|(1<<CS30);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal

    // TIMER1 Top and bottom value:
    ICR1 = 5000;
    TCNT1 = 0;
    // TIMER3 Top and bottom value:
    ICR3 = 5000;
    TCNT3 = 0;

    // Start PWM in OCR = 200 (mid value for servo)
    OCR3A = 200;
    OCR1A = 200;
    OCR1B = 200;
    OCR1C = 200;

}

I can see nothing wrong in your program except this:
DDRB |= (1<<DDB7);      // Output pin 5 OC3A

This is setting pin PB7 as an output, whereas
digital pin 5 (OC3A) is PE3.

I found that out a few hours after posting, despite having raked through my code for two days and now i feel like a bit of an idiot... Thank you very much for the help


text:
How to know my Arduino core version and its location on my Ubuntu laptop?
Bakground:
When compiling a demo project about e-paper, I got this problem
./GxEPD/src/GxIO/GxIO_SPI/GxIO_SPI.h:39:5: error: ‘SPISettings’ does not name a type
     SPISettings _spi_settings;
     ^

which on the Internet, people often say your Arduino core is not up-to-date and the one installed from
sudo apt install arduino-core

is ancient. And you have to install the latest version.
Regardless of whether this solves my original problem or not, I want to have the latest Arduino core on my  laptop.
From arduino.cc I grabbed a zipped file and ran ./install.sh which did not provide enough results to know what it exactly did. Now, I am concerned that I have multiple installation in several places.
Main question:
When I run my make file and it is processed by arduino-mk, which version of arduino-core is it referred to and where is it located?
I am looking for a full proof method. I do not want to open somewhere from / directory accidentally. Because maybe this is not the arduino-core in use.

On Linux install.sh creates a shortcut on Desktop.  A version of AVR boards package is part of IDE installation, but other version and other boards packages managed with Boards Manager are in ~/.arduino15

@Juraj,
Actually, I do not use AVR board package. I use make file which calls avr-gcc.
I think I could find the answer a bit easier by paying attention to the logs coming out of make such as /usr/share/arduino/hardware/tools/avr/bin/avr-gcc -MMD -c -mmcu=atmega328p ... as well as ARDUINO_DIR = /usr/share/arduino and ARDUINO_VERSION = 105. Now the question is whether my Arduino core is recent?

@Juraj, at arduino.cc, the version of Arduino Software (IDE) is 1.6.2. Is this only the version of IDE or is it the version of core too?

IDE is at version 1.8.10 on arduino.cc. AVR core is at 1.8.1, but last good version in my opinion is right now 1.6.21

/usr/share/arduino/hardware is the location of boards packages bundled with IDE

The ancient version installed by apt lives in
/usr/share/arduino/hardware/arduino/cores/arduino.
If you download and unpack a recent version, it will stay wherever you
left it. For example, I have an Arduino core in
/home/edgar/Downloads/arduino-1.8.10/hardware/arduino/avr/cores/arduino.
The installation script doesn't really install those files. It does
install some icons and desktop shortcuts, but neither the core nor the
Arduino IDE. Instead, it assumes the downloaded package will stay
wherever it was when you ran the script.
If you want a somewhat cleaner installation, I suggest you move the
package to /opt, recursively chown it to root, and run the setup script
there. The core will then be in
/opt/arduino-<version>/hardware/arduino/avr/cores/arduino.

Thank you very much. Then how to tell arduino-mk to which version to use?

Can I insall it in a temp directory and then overwrite it on the ancient arduino core?

@ar2015: Read the comments at the beginning of /usr/share/arduino/Arduino.mk. They tell you the variables you can use for selection the version. It would seem ARDUINO_DIR is the main one.


text:
Use JYETech 2.4 Inch LCD Display Screen Module with Arduino?
I have this JYETech 2.4 Inch LCD Display Screen Module that I would like to use for a project I have in mind, however, I'm not sure how to wire it up with my Arudino Mega. Here is the datasheet for the display. I have also attached a picture of the display below. The display is meant to work with a DIY oscilloscope but according to the manufacturer and other forum posts, it can be used as a display with other projects as well.
Pictures of the display

That display is an ILI9341 based one. On the DSO138 it connects the data pins D0-D7 to PORTB of the STM32.
You need to connect those 8 pins to 8 pins on the Arduino, along with the RS (Register Select) and CS (Chip Select) pins. The RD pin can be connected to 3.3V and the WR pin to GND, since you only really want to write to the screen (if you do want to read from the screen then you will want to connect RD and WR to two IO pins as well). Reset can be connected to a GPIO or to 3.3V, depending on if you want to do a hard reset at any point or not.
LED-A can connect to 5V, and each of the LED-K* pins should connect to ground through a resistor each. The size of the resistor will set the backlight brightness (try 100Ω to start with).
Then it's just a matter of finding a library that works with the ILI9341 in 8-bit parallel mode (u8glib maybe? I don't know, I never use Arduino to drive a TFT).
Note that since this is a 3.3V device you should really use a level shifter for all the digital signals.

the ILI9341 has a serial interface available


text:
LCD screen suddenly displaying and updating inaccurately
For the final project of my Arduino course, I have decided to make an alarm clock. The actual clock part was easy enough, but when I wired my buttons up, I accidentally loosened a few wires that a classmate with an identical kit helped me wire up. And although that is resolved now, the halves of my screen are flipped and the second ticker is now only updating every 5 seconds with the same code, even when I comment out unrelated code and reupload. I triple checked the wiring and moving wires around didn't do much either, so I have no idea what is causing this glitch, but hope one of you guys can help me figure it out. Here are some images for reference: https://i.stack.imgur.com/BzrYM.jpg and my code is below:
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
/*
 * VSS: GND
 * VDD: 5v
 * V0: Potentiometer
 * RS: D1
 * RW: GND
 * E: D2
 * D4: D4
 * D5: D5
 * D6: D6
 * D7: D7
 * A: 5v
 * K: GN/>
 */

//Variables to make the time work
int hour = 11;
int minute = 59;
int second = 40;
int flag = 1;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
  lcd.begin(16, 2); // initialize lcd width width and height
  lcd.clear();
}
void loop() {
// Print the time and make sure there are always 2 digits
    lcd.setCursor(0,0);
    if (hour < 10)
      lcd.print ("0");
    lcd.print(hour);
  lcd.setCursor(2,0);
    lcd.print(":");
  lcd.setCursor(3,0);
    if (minute < 10)
      lcd.print ("0");
    lcd.print(minute);
  lcd.setCursor(5,0);
    lcd.print(".");
  lcd.setCursor(6,0);
  if (second < 10)
    lcd.print ("0");
  lcd.print (second);
  lcd.setCursor(10,0);
    if (flag == 0)
      lcd.print ("AM");
    if (flag == 1)
      lcd.print ("PM");
}```

What do you mean? I noticed that my links aren't working properly, so I'll try again via imgur. link Hope this works. Took the best pictures I could of my wiring and output.

And the code that displays the characters:
    if (hour < 10)
      lcd.print ("0");
    lcd.print(hour);
  lcd.setCursor(2,0);
    lcd.print(":");
  lcd.setCursor(3,0);
    if (minute < 10)
      lcd.print ("0");
    lcd.print(minute);
  lcd.setCursor(5,0);
    lcd.print(".");
  lcd.setCursor(6,0);
  if (second < 10)
    lcd.print ("0");
  lcd.print (second);
  lcd.setCursor(10,0);
    if (flag == 0)
      lcd.print ("AM");
    if (flag == 1)
      lcd.print ("PM");```
Hope that clarifies things enough.

Alright, post is updated. Better now?

the picture showing . 04 AM 01 : 00  is not useful if you do not say what you expect it to display instead .... what should the display be showing exactly?

Oh, right. It should display "1:00.04 AM". It was before, but after my little complication, the screen is flipped. Like the code is the same as before, setting the hour to 0,0, minute to 3,0, second to 6,0 and the flag to 10,0.

it is more than flipped ... look very carefully ... when debugging, it is important to observe the unexpected results in detail

what do you see if you run lcd.print ("0123456789abcdef");? ... no other lcd.print() code

you should also pay attention to the expected results ...  "1:00.04 AM" is missing the leading zero

if the code displays correct text in incorrect places, then it is a sofware issue ... if the wires were crossed, then incorrect text would show up


text:
I'm trying to use a CONZIR CO2 sensor to find CO2 concentration
Hey I’m a beginner Arduino user trying to use a CO2/Humidity/Temperature sensor to read in the atmospheric conditions near the sensor and then control a heating pad and solenoid valve to adjust the conditions to what I need. I am having a lot of trouble simply getting realistic values that are usable. It would be awesome if someone could point me in the right direction. I am trying to use sample code provided to me by CO2 meter and am not having any luck having the conditions update in the serial monitor. Any help would be greatly appreciated. Below is the code I am trying to use and linked below is the manual. After figuring out how to simply read the CO2 values, I would like to expand it to temperature and humidity.
(http://co2meters.com/Documentation/Manuals/Manual_GC_0024_0025_0026_Revised8.pdf)
#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13); // RX, TX pins on Ardunio

int co2 =0;
double multiplier = 1;// 1 for 2% =20000 PPM, 10 for 20% = 200,000 PPM
uint8_t buffer[25];
uint8_t ind =0;
uint8_t index =0;

int fill_buffer();  // function prototypes here
int format_output();

void setup() {
  Serial.begin(9600);
  Serial.print("\n\n");
  Serial.println("             AN128 Ardunio to Cozir CO2 Sensor - Demonstration code 11/29/2017\n\n");
  mySerial.begin(9600); // Start serial communications with sensor

  // mySerial.println("G");

  pinMode(4, OUTPUT); //heating pad pin
  pinMode(3, OUTPUT); //heating pad pin
  pinMode(5, OUTPUT); //solenoid valve pin
  digitalWrite(4, LOW); //change between HIGH or LOW value to make the valve/heating pads turn on/off
  digitalWrite(3, LOW);
  digitalWrite(5, LOW);

  //mySerial.println("K 0");  // Set Command mode
  // mySerial.println("M 6"); // send Mode for Z and z outputs
  // "Z xxxxx z xxxxx" (CO2 filtered and unfiltered)
  //delay(20);

  mySerial.println("K 1");  // set streaming mode

}

void loop() {

  // Serial.println(" Hello World ");
  fill_buffer();  // function call that reads CO2 sensor and fills buffer

   Serial.print("Buffer contains: ");
  for(int j=0; j<ind; j++)Serial.print(buffer[j],HEX);
  index = 0;
  format_output();
   Serial.print(" Raw PPM        ");

   index = 8;  // In ASCII buffer, filtered value is offset from raw by 8 bytes
   format_output();
   Serial.println(" Filtered PPM\n\n");
}

int fill_buffer(void){

// Fill buffer with sensor ascii data
ind = 0;
while(buffer[ind-1] != 0x0A){  // Read sensor and fill buffer up to 0XA = CR
  if(mySerial.available()){
    buffer[ind] = mySerial.read();
    ind++;
     // Serial.println("Fill loop");
    }
     //Serial.println("Fill loop");
  }
  // buffer() now filled with sensor ascii data
  // ind contains the number of characters loaded into buffer up to 0xA =  CR
  ind = ind -2; // decrement buffer to exactly match last numerical character
  }

 int format_output(void){ // read buffer, extract 6 ASCII chars, convert to PPM and print
   co2 = buffer[15-index]-0x30;
  co2 = co2+((buffer[14-index]-0x30)*10);
  co2 +=(buffer[13-index]-0x30)*100;
  co2 +=(buffer[12-index]-0x30)*1000;
  co2 +=(buffer[11-index]-0x30)*10000;
  Serial.print("\n CO2 = ");
  Serial.print(co2*multiplier,0);
// Serial.print(" PPM,");
//    Serial.print("\n");
   delay(200);
 }

what does this mean? ... trouble simply getting realistic values

So the value I am getting is -9600 ppm (a negative CO2 value),  and after receiving one CO2 reading it won't continue to loop and give me more readings. I was under the impression that it would continue to get buffer readings and thus be able to update and give me new readings


text:
Adding time in Serial Monitor
I need help in my Arduino project. I am trying to add the current time in Serial Monitor but i couldnt make it happen... I was also trying to do something like this...
Here is my current code right now...
// Purpose: To monitor the room temperature
// Programmer: Emmanuel Quiambao Sr.
// Date: Nov. 26, 2019

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// set the current time
// Set temperature parameter
const int hot = 85;
const int cold = 70;
const int motorPin = 7;
int switchState = 0;

void setup () {

  pinMode(A0, INPUT); // Temp sensor
  pinMode(10, OUTPUT); // Green Led
  pinMode(9, OUTPUT); // Yellow Led
  pinMode(8, OUTPUT); // Red Led
  pinMode(motorPin, OUTPUT); // Fan
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  Serial.begin(9600); // opens serial port
  Serial.println("Time Voltage Temperature");

 }

void loop(){

  int sensor = analogRead(A0);
  float voltage = (sensor / 1024.0) * 5.0;
  float tempC = (voltage - .5) * 100;
  float tempF = (tempC * 1.8) + 32;
  int reading = analogRead(A0);
  unsigned long curMillis = millis( );  // get current time

  Serial.print(" ");
  Serial.print(voltage);
  Serial.print(" \volts");
  Serial.print(tempF);
  Serial.print(" \F");

  Serial.print(curMillis);
  Serial.println( );
  delay(100);

  if (tempF < cold)            // Too cold
  {
  digitalWrite(10, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
  lcd.setCursor(1,0);
  lcd.print(" Too Cold "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd
  }

  else if (tempF >= hot)      // Too hot
  {
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, HIGH);
  lcd.setCursor(1, 0);
  lcd.print(" It's Hot "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd
  }

  else                        // Desired temperature
  {
  digitalWrite(10, LOW);
  digitalWrite(9, HIGH);
  digitalWrite(8, LOW);
  lcd.setCursor(1, 0);
  lcd.print(" It's Fine "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd

   switchState = digitalRead(9);
  if (switchState == HIGH) {
    digitalWrite(motorPin, HIGH);
  }
  }

  delay(5000);
}

What would be the time source for your Arduino? Do you have an RTC hooked up?

Sir, I just want to add the current time. also if possible maybe you can help me in fixing the columns of it like the one in the photo that i attached. i would like if possible to be "TIME VOLTAGE TEMPERATURE". I appreciate your prompt response.

I attached the temp sensor only. I apologize for my ignorance I am new to this project; what is RTC?

A real time clock. It's a device that can tell your Arduino what time it is.

Ow, i do not have that in my kit... just a question do I need an RTC if i just want to add the time in Serial Monitor? I just want to record the change of temperature every 10 secs?


text:
Wemos D1 Mini using RF with RCSwitch
I’ve bought a RF transmitter and receiver on eBay and I’m trying to get my garage door codes with my Wemos D1 Mini.

I’ve downloaded the RCSwitch library, hooked up the receiver to ground, 5v and data to pin D4.  Also flashed the sample receiver sketch.
The problem is that I don’t get anything on serial monitor... the Wemos board has an inbuilt led that flashes when I press my garage remote buttons, which means that pin DATA is sending a signal to the board, but I can’t see anything on serial monitor (Baud rates and serial connectivity is all good).
Tried other pins and didn’t get anything different.
Does anyone know how can I specify the pins with RCSwitch or have and idea of what is going on?
UPDATE 1
I’ve certified that transmitter is working and hooked properly using the Radiohead library.

UPDATE 2
The remote I have is so cheap that it is barely impossible to determine which chip it uses:

get the neighbor's garage door codes too if it is possible :-)

Well, I can’t get even my garage door codes...

why do you believe that you can receive your garage control codes with that device?

Actually, I don’t need the code, I need to clone the signal to open my garage using my Wemos

how about sharing your code?

There is no code to share. I was running the example from RCSwitch library

Would be interesting to share the code anyway, also the schema you're connecting your arduino to the RC or TX devices. I am connecting to D2 (pin #2, so INT0) as the sample requests.


text:
String generator not working as expected
I'm trying to build a random string, save it to EEPROM as int, then read it back and output it.
If I give it a predefined string then it works fine. But Something is wrong with the random string generator.
  String output;
  char letter;

  String mystr=""; //"ABCabc123..";
  String characters = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz";
  String numbers = "0123456789";
  String other = "<>!.,()?|=&%¤#";

  // add random characters to empty string
  for(int i=0 ; i < 12 ; i++){
    mystr += characters[random(0, characters.length())];
  }
  // add two numbers, one other and two more characters
  mystr += numbers[random(0, numbers.length())];
  mystr += numbers[random(0, numbers.length())];
  mystr += other[random(0, other.length())];
  mystr += characters[random(0, characters.length())];
  mystr += characters[random(0, characters.length())];

  // loop the string and place one character in each EEPROM address
  for(int i=0 ; i < mystr.length() ; i++)
  {
    EEPROM.writeInt( i,mystr[i] );
  }

  // read the string back from EEPROM
  for(int i=0 ; i < 17 ; i++){
    letter = EEPROM.readInt(i);
    output += letter;
  }

If I run the code output will be "H". Every time.
If I use the predefined string "ABCabc123.." then it works correct.
What am I doing wrong with building the mystr?

EEPROM.writeInt() and EEPROM.readInt() don't look like standard Arduino functions. Where did you get them? Also note that “¤” is not an ASCII character. It takes two bytes if you write it in UTF-8.

@EdgarBonet I can't include EEPROM.h . It's missing from Digispark boards I guess. I found EEPROM.h and downloaded it, but when I included it, I got an error that Debug.h was missing. So I just gave up on that and found anothter library.

Your first mistake is to use String. Don't. Instead use a char array.
char mystr[18]; // Room for 17 characters plus the NULL terminating character

Your string constants should also be char arrays, not String variables. And better to put them in PROGMEM:
const char characters[] PROGMEM = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz";
const char numbers[] PROGMEM = "0123456789";
const char other[] PROGMEM = "<>!.,()?|=&%¤#";

Now filling your target array becomes:
for(int i=0 ; i < 12 ; i++){
  mystr[i] = pgm_read_byte_near(characters + random(0, 50));
}

mystr[12] = pgm_read_byte_near(numbers + random(0, 10));
mystr[13] = pgm_read_byte_near(numbers + random(0, 10));
mystr[14] = pgm_read_byte_near(other + random(0, 14));
mystr[15] = pgm_read_byte_near(characters + random(0, 50));
mystr[16] = pgm_read_byte_near(characters + random(0, 50));
mystr[17] = 0; // Don't forget the NULL...

Your second problem is the use of EEPROM.writeInt and EEPROM.readInt.  Those are for writing integer values, not characters.  Instead just use EEPROM.read and EEPROM.write:
for (int i = 0; i < 17; i++) {
    EEPROM.write(i, mystr[i]);
}

Then to read back:
for (int i = 0; i < 17; i++) {
    mystr[i] = EEPROM.read(i);
}
// And don't forget to terminate the string...
mystr[17] = 0;

I can't get this working. First off all, the random does not seem to change between runs. I get the exact same string each time, only if I change something do I get a different result. When I output the array, character by character I get a shorter string than it should be. 7 characters Åo-Åyäv And two of those is not included in the character char.

Random isn't random, no. It's pseudo random. You have to set the "seed" to change the "random" sequence.

I see. I will try and use a different approach then.


text:
Arduino not starting after 1.8.10 update
First off sorry if this is the wrong place.
Yesterday I updated the Arduino IDE to 1.8.10 and I was able to program a couple of hours.
Powering up my laptop today though the IDE is active, I can't switch to it and it shows a white screen if I hover over it in the taskbar below.
When I run the arduino_debug it literally says no error whatsoever it just loads the configuration and start the IDE (5 lines)
Already tried uninstalling and using another version of the IDE

Delete your Arduino data directory, wherever that happens to be on your operating system of choice...

Worked! Also made sure the new installation went into a different folder than it was and that solved it... Thank you :)


text:
Connect a hundred SIM800L's to Arduino (or any other board)
Is there a way to connect one hundred SIM800L's to Arduino? Essentially I want to be able to communicate with any of them that I want. If Arduino isn't capable of doing this, what do you suggest, so I could connect to and control 100 SIM cards?
Thanks for your help in advance!
R.

Wow, 100 is much. Maybe with a series of multiplexer modules (only talking to one at a time). But why do you need to talk to 100 SIM800L? What are you trying to achieve?

It is likely the additional hardware needed will exceed that of most Arduino platforms.  That is, while using an Arduino Uno may work, it would be like building a race car from a go cart.

@chrisl That's for a project I am creating a PoC for. Ideally I want to be able to talk to an unlimited number of SIMs for making calls, sending texts etc. Can you please provide a link or example for using "multiplexer modules" ?

@st2000 That's fair do's. It doesn't really have to be an Arduino. I just don't know how to connect a SIM800L to a Desktop computer for example, let alone connecting hundreds of them. If money wasn't an object (within reason), what hardwares would you propose to achieve this? I'm a software engineer so coding it up is I guess the easier part, as long as it's possible to talk to the modules.

You need to think modular. Forget one central "brain" with hundreds of modems connected to it - think lots of small brains with only a few modems on each one, all communicating to a central controller over some other transmission medium (ethernet?)

@Majenko Could a SIM800L be connected to a normal desktop motherboard? Would that be through a USB-to-Serial interface? If so, are there these interfaces that provide, say 50 serial output pins so I could connect 50 SIM800L's?

@jsotola It's going to be sending lots of texts from different numbers.

@jsotola I highly doubt they will work without a SIM card active somewhere in the network. Also the networks I've been on don't support that feature. Also I want to be able to receive texts too. Maybe add a phone call feature later on too. So no, I will need to physically connect my 100 sim cards somewhere.

now it is clear what you are trying to do .... your question above is still unclear ... please edit the question to include all of the information that you put in comments, then delete the comments

You left unclear, what your exact requirements are. So the answer will be as general as your question. The SIM800L uses the Serial interface (UART). So the point is to connect to 100 different serial interfaces.
If it is ok to talk to each SIM800L sequentially (only one at a time), you can use a series of multiplexers. A multiplexer chip connects one pin to one of multiple pins (called channels here). Depending on the used chip, the channel can be selected in different ways. The standard way is with simple digital input pins, that construct a binary number. So for 8 channels you need 3 input pins (2^3). Other ways are through communication interfaces like SPI or I2C.
Normally a multiplexer has only 8 channels, though you can also find once with more, but I don't think there are multiplexers with 100 channels. So you could next the multiplexers. If you put another multiplexer on every channel of the first multiplexer, you get 8*8 = 64 channels with 9 multiplexers in total. Add some more multiplexers on the next level and you will get to over 100 channels. Then you need 2 of these multiplexer trees to multiplex both serial lines (TX and RC). Since that are a lot of multiplexers and thus a lot of inputs to choose the correct channels, you could use multiplexers with SPI or I2C interface. The first would require 1 digital output pin of the Arduino per multiplexer as slave select pin, the latter would require either a multiplexer type, that can as many different I2C addresses as multiplexers in your system, or a bit more complex programming and also 1 pin per multiplexer to change the address of the chip to configure. How to use these multiplexers with Arduino depends on the used chip. You should refer to it's datasheet.
As you now see, connecting one single Arduino to 100 serial interfaces it a complex task. Depending on your actual requirements and goals in your "PoC project", it might be a better way to follow Majenkos advice and build it more modular with multiple Arduinos/microcontrollers.

Thanks, I understood what those multiplexers do. I assume the multiplexers switching between pins would have a delay. That, and the fact I wouldn't be able to for example ask 10 SIM800L's to each do something (multithreading if you like), makes it a not so good option. Agreed Majenkos' solution sounds better.


text:
Missing time when using timer
I have set up Timer2 to count every tick at 16MHz, or 62.5ns per tick. Then I run the following code:
int t = 0;
    for (int i=0;i<64;i++){
  data[4*i] = TCNT2;
  data[4*i+1] = TCNT2;
  byte now = data[4*i+1];
  byte last = data[4*i];
  t += now > last? (long)(now-last) : 256 -(long)(last-now);
  data[4*i+2] = TCNT2;
  data[4*i+3] = TCNT2;
  }
}
for (int i=0;i<255;i++){
  Serial.println(data[i]-data[i+1]);
}

and I get the output: "4 4 4 11" (repeated) which makes sense, 4 clock cycles to read TCNT2 and write it to the correct place in data and 11 cycles when also evaluating the loop condition. However, I can't understand when the variable t is updated. I have tried running with and without t and both give the same timings. From my (obviously lacking) understanding updating a variable is at minimum one instruction, so how can it do it under one clock cycle? Am I misunderstanding what one instruction is or does the TCNT2 counter for the timer not update accurately here?

Ops, I just realized it's the compiler working it's magic. I never used t, thus the compiler said "Wtf is this guy doing, this t is useless and I'll remove it!". When I used t I got sensible results.


text:
default in switch doesn't appear to execute
I have a situation where the default case in my switch statement doesn't appear to execute as expected. I wonder if there is some subtlety I'm missing here?
Given the following enum:
enum HomingPhase
    {
    Idle = 0,
    Detecting,
    Stopping,
    Reversing,
    AtHome,
    };

and the following methods:
void HomeSensor::setPhase(HomingPhase newPhase)
    {
    phase = newPhase;
    Serial.print("Phase ");
    Serial.println(phase);
    }

void HomeSensor::onMotorStopped() const
    {
    std::cout << "Hstop " << phase << std::endl;
    switch (phase)
        {
        case Reversing:
            setPhase(AtHome);
            break;
        case Stopping:
            setPhase(Reversing);
            const auto target = commandProcessor.targetStepPosition(homeSettings->position);
            motor->moveToPosition(target);
            break;
        default:
            setPhase(Idle);
            return;
        }
    }

At runtime, onMotorStopped() is called and I see the following output, which indicates that phase is AtHome (4) on entry to the method.

Hstop 4

I expect the default case to execute, setting the phase to Idle but I do not see the output from setPhase(), which suggests that the default case isn't executing. Subsequent output from elsewhere in the code confirms that phase in fact remains set to AtHome (4) and isn't being set to Idle as expected.
I think I may have gone code blind. Can anyone see the issue?

One's going to std::cout (works). The other to Serial. I don't know std::cout on an Arduino...  Are you really running it on an Arduino?

Yes,  works surprisingly well. I should probably change thos to use one or the other and not mix them like that, but the Serial.println does produce output in other circumstances so it's not that the print statement isn't working.

I would try it with Arduino AVR core 1.6.21. Newer have problems

What happens if you put debug output (either way) on each case and default?


text:
Why does the reading on the ESP32 read max, when the reading on UNO read accurately?
I have a 'Capacitive Soil Moisture Sensor' hooked up to my Uno.
Very simple code. AnalogRead(MoistureSensorPin);
This will return a differing value that I can work with.
When applying the same code to an ESP32 with a similar set-up. It always returns '4095' which I understand is the maximum value an analog input can return. But I cannot understand why it does this.
Any help will be much appreciated.

Thanks friend, this response also helped me a lot

The ESP is a 3.3v device. If your Uno is a 5v device, its A/D converter can measure and report voltages from 0 to 4.9878v (5v minus 1 LSB). If the same signal is presented to the ESP, any value above 3.29919 volts (3.3v - 1 LSB) will read as 4095, i.e., out of range.
(If this isn't your issue, adding wiring diagrams of each system to your question will help us understand it better.)
Update:

Perhaps a different ESP unit would be the ideal solution?

As far as I know, all of the ESP's are 3.3v devices. So the solutions I see are:

Power your sensor with 3.3v (is this an option?) so its output will be within the input range of the ESP's built-in A/D.
Scale the sensor output from it's 0-5v range to the 0-3.3v range the ESP can accept. Whether you can use a simple divider network or would need an op-amp may depend on the sensor, but if, as I suspect, it is a simple resistance device, a voltage divider should work.
Use an external 5v A/D converter. This will require a 5v power supply (which I presume you are using already, to power the sensor) and voltage level conversion between the A/D and input pin(s) of the ESP. The conversion could be a purchased level-converter board or a simple resistor-divider network.

Thank you for the response!
I believe this is the issue I am facing, so it's an A/D converter issue on the ESP device...
Perhaps a different ESP unit would be the ideal solution? (ESP82?)
Or, do you know of a different solution for me to be able to get a different result from my ESP32?
Much appreciated.


text:
Trying to control DC motor speed with PID
i'm trying to control a DC motor with PID. I have already made a code where i control the motor with an ultrasonic sensor (for distance) but now i need to run the motor at a given RPM (the Output). I did a lot of resarch and found that i will have to use the PID Library. But with my existing code i'm not sure if it's going to work. I know that i will have to modify PWM values by the Input on the analogWrite(). Can you enlight me on this PID? Here is my code:
int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

void setup() {
  pinMode(enableBridgePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(backWardPin, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);
  Serial.println(distancefonction(dt,distance));

  if (distancefonction(dt,distance)<15 && distancefonction(dt,distance)>7){
    slowdown();}
}

int distancefonction(int dt, int distance) //function to show distance

void slowdown(){
  for(int i=255;i>=0;--i){
      analogWrite(enableBridgePin,i);
      delay(10);}
   Serial.println("SLOWDOWN");
}

PID is a feedback loop control. So you first need feedback from the motor, e.g. some way to measure the actual speed/RPM of the motor. Only then you can use PID.

Does your  PWM analogWrite(enableBridgePin,i); work as desired ?  ( A minimal but complete and compilable code is appreciated :)

@chrisl the motor returns the tickPin

@DataFiddler yes the pwm works properly i tried it.

What does the motor with trickPin? You haven't explained this, nor do I see anything in your code. Are you already reading the current RPM back from the motor, or is this be actual problem?

@chrisl I can't read RPM on the motor. The tickPin is actually a timer pin connected to channel A (motor with encoder), i think everytime there is an impulsion the timer increments (i'm not sure abt that)

Is the "tickPin" a tachometer signal?

PID- or any similar control needs

set point
actual value
controlling variable (your PWM value)

The difference between set point and actual variable and its change over time are combined to calculate the controlling variable in order to minimize that difference.
Control theory in general is too complex to answer the "how to" here in general.
Besides measuring the actual value you also need knowledge about the behavior of your system: e.g. If you change the PWM value from 50 to 100, how much and how quick will the motor speed change? Even the response form over time will affect the optimal parameters for your control loop. It's called (feedback) loop because any change of the PWM value will change that difference and lead to a different new value of the controlling PWM value again (Allowing for instable behavior in case of bad controlling parameters).
Getting the actual value is your first task. How your distancefonction affects the desired value (set point) might also need more clarification...

thanks for the explanation. Actually 'distancefonction' just displays the distance between the object and the sensor. what i don't understand is how i'll get the actual value? the setpoint is 100rpm

One of the simpler ways is a optical wheel, or even just a small 'flag', attached the motor shaft, that interrupts a light beam every revolution (or part of one). Time the pulses and convert to RPM.


text:
Arduino Nano/Uno and js sketch compiling/uploading from browser
I need to compile generated source code in js runtime then upload it to my device.
Compiling:
I have found arduino-cli
Uploading:
There is only avrgirl but it doesn't work in browser. What should I do?

Arduinos cannot be programmend in Nodejs. You need to write C/C++ or Assembler.

@chrisl, it's not about programming (code is c-generated one) it's about calling compiler from js

Ah, ok. But you can also upload sketches with arduino-cli. If you can use it, you can also upload sketches

You can't, and that's a good thing. If the browser could let a Web site access your hardware, that would be a huge security breach. You may be able to bypass this security restriction if you can write an extension (plugin) for your browser.

Okay then I will use extension for hex code uploading. Then how can I compile it using only in-browser js?

I mean: source code -> String -> Compiler -> Hex-string -> Extension -> Uploading

@caxapexac: Building a C++ compiler in JavaScript is not a trivial task. You may try to port avr-g++ using Emscripten.

Seems for me a weird way to do everything in the browser. Normally in such a situation you are actually building a web service, so the compilation could be done server side by calling avr-g++ or arduino-cli through the nodejs code. Then you only would need to encapsule arduino-cli in an extention for uploading on the local computer

I modify the code from js-stk500 to work from browser with web serial API. but I can't makr Arduino CLI to work in browser. Is that possible?


text:
Driving an enable pin low via arduino
I have the following V regulator, that has an enable pin that i'd like to control via an arduino:  https://www.pololu.com/product/2582
I tried using a relay (ELEGOO Relay Module 4 Channel DC 5V with Optocoupler for Arduino) with the following pins:
Relay pin1: 0v of 24v battery
Relay pin2: enable pin of pololu v regulator
I then enabled the above relay via an arduino digital out pin.
However it seemed to have no effect, the regulator never shut off.
If i manually join the two relay pins, pin1 and pin2 the regulator does shut off though ..  A and B in picture.
Any ideas why the relay is not working via the arduino?  or should it work? am i doing something wrong?  I am not too familiar with pull up or pull downs..
I have since disconnected everything and put it away, i am just looking for theory help, confirmation it should wotk.   I managed to get the relay working for leds at the time .. would the fact that current flows in the other direction for this pull down relay setup, be my issue and that i should swap around wires A and B?
(As a workaround i used a relay to switch on or enable the 24v Vin line out from the battery instead, that seemed to work okay..)

A circuit diagram and details of the arduino code used would help in diagnosing the problem

what is relay pin1? ... for all we know, it may be an unused pin

Unless you require galvanic isolation (and it's highly unlikely that you do) you don't need the relay.
The EN pin only needs to be above 1.3V to turn the unit on, or below 0.9V to turn it off. The voltage range is anything up to 30V.
Just connect the EN pin directly to an Arduino IO pin. Write a HIGH for on and a LOW for off.  And of course connect the grounds together.

thanks for the tip! I will use this next time, but still wondering what was my issue.


text:
How to set an array size to a variable which might change later into the code?
I'm trying to initialize an array globally which could be of different sizes according to future code in Arduino.
int n=0;
int val[n];
This says that the array bound is not an integer constant before ']' token. This also says that the val variable wasn't declared.
I have browsed other forms and have been told to use dynamic storage usage which I don't know how to use.
I'm trying to store different weight values respective to time in a variable. I first tried to store the weight in one variable but couldn't find the total weight etc.

Please edit your question and add the code in "text format". There is a "button" on the Edit window tool bar that looks like this {}. Highlight all of your code then click it.

This looks like an XY problem to me. The array of variable size is not the real goal, and is most likely a bad idea in the first place. What is your real purpose? What are you trying to accomplish?

why not use int val[10] or int val[50]?

As others have suggested, dynamically allocated memory is often problematic on a memory-starved device like an Arduino. As you create and release memory, the "heap" (a pool of memory to be used for that purpose) gets broken up into "islands" of free memory with still-used blocks of memory peppered throughout.
In fairly short order you wind up with your available memory pretty much unusable, your app runs out of available memory, and your app crashes.
This is known as "heap fragmentation". When you only have a couple of K of RAM to work with, it quickly becomes fatal.
If you can be sure that you allocate a dynamic buffer in a function call sequence, don't do any other dynamic memory allocation, and then free it before returning, you can probably get away with it without fragmentation, but you really have to be careful.
If you instead dynamically allocate a block of memory very early in your app's life and then keep it for the entire run that can be okay too. That block takes a chunk of your heap and just stays there.
A third alternative is to allocate a statically sized array at compile time that's big enough for your largest use, and treat that as a buffer. You can save contents there as needed, then when you're done with those contents, use the buffer for something else.

The Arduino platform uses a C / C++ compiler.  In C++ one can use features such as Vectors to create what appear as arrays of varying sizes.  However, it is likely memory is wasted when trying to abstract the memory usage from the application in this way.  In an embedded environment, memory is likely at a premium.  Consequently, it is almost always better to handle array sizes in embedded situations by allocating the expected amount manually at the beginning of the program.
Tip: If the size of the array depends on the situation the application is used in and there are advantages of smaller verses larger arrays depending on the application, try using Conditional Compiling to create different versions of the application.

In general arrays declared like
int array[n];

needs a constant size n, so that the correct memory size can be allocated at the time of declaration. Otherwise the compiler doesn't know what to do with that variable. You cannot change the size of an array, especially not by simply assigning values to non-existent elements. To create a new array with a size unknown at compile time, you would need to use dynamic allocation:
int *array = new int[n];

The variable array is actually not the array itself, but a pointer to an integer array. The compiler will create the pointer variable, which will only hold an address, where the new dynamically created array is stored. With the new keyword we are allocating a new memory space. With int[n] we are telling the program to allocate space for n integers. You can create arrays with sizes unknown at compile time, but you cannot change the size of an array. You would need to create a new one to change size. Dynamically allocated storage, that is not needed anymore should be freed. (You can google more about this)
BUT: On an Arduino you should not use dynamic allocation. If you use the dynamic allocation too much (over and over again) in a program, you will get memory fragmentation. As you allocate and free memory of different sizes, you will get many small memory spaces, which are too small to hold your new arrays. So this memory is now useless and Arduinos only have very little RAM to use for dynamic memory. When your RAM is full, your program will crash. Real computers - in contrast - have loads of memory, so that is not a problem there.
It is better to allocate your memory statically, with enough space to handle your biggest expected amount of data. So you should really think about, if you really need dynamic allocation. I would say no.

There are also other problems with your code.

You use the following for loop:
for(n = 0; isFinished = true; n++)

A single = marks an assignment. So at the start of every for loop iteration you are assigning true to isFinished. And every assignment will evaluate as true. So you have an infinite loop there. If you want to check for equality, you need to use == (double equal sign). Also in that for loop isFinished newer changes. You initialize it with false, so the loop will not run once. If you instead check for it to be false the loop  will be infinite, since there is no possibility, that this variable changes inside the loop. Instead use n for the loop condition and run the loop as many times as you have elements in your array.
Generally your logic seems not well thought through. You are already using a for loop to measure multiple values, so why don't you just directly measure as many values, as you want to measure, by using the for loop as described above. Then you don't need all the isFinished stuff, because you will always have all the needed values, when you exit the for loop. So you also don't need to check, if there are enough values measured. And it is not clear, what the threshold check should do.


text:
Atmega328pb type casting errors
I've created a custom pcb with a Atmega328pb cpu.
It's said to be binary compatible with Atmega32p, thus i flash it with my already functioning sketches that i've developed using an arduino.
The thing is that i have a double that i try to cast to int and when i do, it crashes the processor.
The code works perfectly fine on 328p so i'm wondering whether it could be a compiler issue, hardware issue, fuse settings issue.
double globalDouble = 0.0;

void arne() {
  int stuff = globalDouble;
  // program execution halted…
}

The board manager does not include 328pb bit but https://www.pololu.com/ has board config for it, so has http://github.com/watterott/ATmega328PB-Testing, but they make no difference. Still halts.
Any clues on how to move forward? I could ask the factory to replace it with a 328p but i'de rather have my already made products work.
Thank you!

How do you know it halts because of it? Have you tried to compare assembly for both MCU's? Does it even use the same version of compiler? Maybe it's just a compiler bug.

try with AVR boards package 1.6.21