text:
analogWrite and For Loop Bug
I wrote the following code that outputs a packet data structure bit by bit.
I do this using two for loops. These two for loops should always terminate, but the presence of analogWrite() makes them not terminate.
More concretely:
#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}
void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

loops forever but this one doesn't:
#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      //analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}
void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

the difference between these two being a single commented line in testFun
My entire sketch is as follows:
#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}

void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

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

}

and its two outputs are
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
Other loop
0
1
2
3
4
5
6
7
and
0
0
0
...

Please provide also a sample serial output, since this seems to be where you sense, that the loop goes on indefinitely. Is the loop() function empty? You didn't provide it. I don't see a obvious reason, why there should be an infinite loop, but I also don't see, why this should work. You don't wait for the signal to be outputted on the pin. You restart PWM so fast, that it cannot really do a cycle. You have to wait a bit, otherwise the code will be executed way too fast

The loop function is empty. The serial output for the first snippet is always 0 (implying i is never incremented) while that for the second loop is what you would expect  and prints out “Other loop”. I tried adding a one second delay to prevent what you mentioned, and that didn’t work.

I loaded both codes (with an empty loop) on a Nano and they both worked identically.  The behavior where one seemingly unrelated line completely changes the program is often due to undefined behavior at a completely separate point in the program.  It can be really hard to find.  Please post the complete program that will exhibit the problem.  The error may be somewhere completely unrelated to this code.

Just added the entire sketch. Its pretty much identical to the first two snippets I gave. I also added the exact output I get on an Arduino Mega 2560

I get the same output as you, but only once. A bunch of 0s, a bunch of 1s, "other loop" and 0-7 - then it stops. Your code is fine.

What output did you actually expect?! The provided output is what I would expect from looking at your code...


text:
ISD 1820 using Arduino UNO
I have to play audio files using an isd1820 sound module. I am using arduino uno microcontroller but I am able to play only one file. Is there a way I can play different audio files according to need?

how are you playing one file?

Please provide a link to the exact sound module, that you have.

source: Stack Exchange

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

sort: votes


text:
Where do class files go in Sloeber Eclipse project?
I'm attempting to create a new Arduino project using Sloeber (Eclipse). Assume it's a newly-created project whose main entry file is ".\ArduinoMainClass.ino"
Now... assume I want to create a half dozen new classes:

ExecutionState-- a C++ class that's intended to be functionally equivalent to a Java Interface. If you're wondering, I'm attempting to implement the 'State' pattern.
GoodState, BadState, UglyState, WeirdState-- C++ classes that all extend ExecutionState. If they were Java, they'd technically be implementing an interface... but since this is C++ and I'm still taking baby steps, for now ExecutionState is just a class with one method that does nothing, and all of THESE classes override it to do the actual work.
StateContainer-- a C++ class whose only purpose in life is to hold single instances of GoodState, BadState, UglyState, and WeirdState. If this were Java, they'd be Singletons... GoodState (and the others) would have something like:

    private static ExecutionState instance = new GoodState();
    // ...
    public static ExecutionState getInstance() { return instance; }

... but it's obviously not Java,  and I'm nowhere close to knowing enough about C++ to properly implement static singletons yet, so for now, I'm just going to create an instance of StateContainer to create and hold those single instances.
So... I now have Sloeber/Eclipse loaded, and I've created my project. If this were Java, I'd create a subdirectory like .\src\java\com\packagename\executionstate and stick the .cpp and .hpp files for ExecutionState, GoodState, BadState, UglyState, WeirdState, and StateContainer in it, and add "include com.packagename.executionstate.*" to it.

I know C++ namespaces have no direct connection to directory names
I've gotten the impression that "Arduino"-ish C++ auto-generates the #include files for things it regards as libraries. I have a hunch that I probably want to put all of the classes I mentioned above in a directory somewhere and present them to the IDE as an Arduino "library" so they'll all get implicitly included in one go within the .ino file.
I'm completely confused about what I need to #include in the classes I mentioned above so they can mutually find each other... and whether those #includes rightfully belong in the .hpp or .cpp files.

So... getting back to the big picture. If my project is in c:\users\moi\Documents\Slober-workspace\FirstSloeberArduinoApp...

Where do the .cpp and .hpp files for ExecutionState, GoodState, BadState, UglyState, WeirdState, and StateContainer go? (Assume I'd be inclined to put them all in a directory named "executionstates" somewhere in the project's directory hierarchy, but I'm not sure where that exact directory should go).
What #includes do I need to put in ExecutionState, Good/Bad/Ugly/WeirdState, and StateContainer... and do they go in the .hpp file, or the .cpp file for their respective class?
What do I have to do so the .ino file can find StateContainer?

In case you're totally confused at this point, my actual .ino file will look something like this:
void setup() {
    // executionStates is a global variable declared higher up
    executionStates = new StateContainer();
    executionState = executionStates.getGoodState();
    // StateContainer's constructor itself creates instances of the various subclasses of ExecutionState,
   // and passes references to itself to their constructors so they can
   // get the references to the others states as they need to return them.
}

void loop() {
    executionState = executionState->doSomething();
    /* executionState holds a pointer to an instance of an ExecutionState subclass.
       Each time doSomething() executes, it returns a pointer to its new state
     */
}

... and in reality, there will be dozens of subclasses of ExecutionState, each representing a unique execution state.

''Arduino'-ish C++ auto-generates the #include files for things it regards as libraries." The Arduino IDE, being a learning tool for new programmers, does do this, but it is unique to that environment. Having graduate to a professional level tool (Eclipse/Sloeber) which will save you a tremendous amount of tedium - but not fixing your code for you - be prepared to write standards-compliant C++, even if using the Arduino IDE. You will, in the long run, make fewer opportunities for error, come to understand the language better, and your code will be portable to standards-compliant environments.

With Sloeber Eclipse plugin the ino files go to root of the project and the cpp, c and h files can be in root or in subfolders. example:

Folders created by Sloeber: core subfolder is a virtual folder with links to Arduino core files and variant files of the selected board. libraries folder is a virtual folder with links to libraries selected for the project. Release folder contains the generated make file, the .o files and the resulting elf, hex, bin files. (And sloeber.ino.cpp is a file generated by Sloeber)
Project folders: data folder in example picture is a convention for a folder with esp8266 SPIFFS files. utility is a subfolder with additional source files of the project.

I put my class files, [class].cpp and [class].h, in the same folder as my project.ino file, at least during development. Then, if they're sufficiently general, I'll move them to [workspace]/libraries/[class]/ for future use.
But even if they're only for this project (so they might as well stay in the project's source code folder), it's good organization to keep them in their own files, since by nature, classes only expose their interfaces, not their "guts".

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


text:
SIM800L is not registering on network
I'm testing SIM800L module by registering to network manually and I'm getting an error message.
Here are the commands I tried.
AT+CSQ

+CSQ: 31,0

OK

AT+CBAND?

+CBAND: EGSM_MODE,ALL_BAND

OK

AT+COPS=?

+COPS: (1,"Bharat Karnataka","CellOne","40471"),(2,"Airtel","AIRTEL","40445"),(3,"Hutch-Kamataka","HUTCH","40486"),,(0-4),(0-2)

OK

AT+COPS=1,1,"40471"

ERROR

AT+COPS=1,1,"40471"  is this command right? My
SIM card is CellOne and it's 4G.
Power supply -7.4 li-ion 1100mAh battery with an adjustable 5V-5A buck converter(3.8v is supplied to SIM800L)

For the AT+COPS command you are setting manual with long alphanumeric network name but then using the numeric network name. Try AT+COPS=1,2,"40471"
REF
//Manually select T-mobile as carrier using short format alphanumeric network name
AT+COPS=1,0,"TMO"

//Manually select T-mobile as carrier using long format alphanumeric network name
AT+COPS=1,1,"T-Mobile USA"

//Manually select T-mobile as carrier using numeric network name
AT+COPS=1,2,"310260"

AT+CSQ checks the signal strength, you can check the reply range with a question mark,
AT+CSQ=?

+CSQ: (0-31,99),(0-7,99)

OK

The first number, 31, shows you have a good signal strength locally.

AT+CBAND? shows the mobile operating band set

AT+COPS=? will search for networks, your response indicates you found a few.


text:
Problems integrating Reed Switch and Solenoid Lock in Arduino Code
I am trying to integrate solenoid lock, reed switch in my Arduino Code. The flow that I am trying to achieve is - first, the solenoid lock is set to LOW and then the program checks if reed switch is High or Low. Only if its High I want to proceed further. However, even when the reed switch is HIGH the program is not executing further. Here is my code below:
    #include<HX711_ADC.h>
    #include<math.h>

    //pins for lock
    int solenoidPin = 7;

    //pins for reed switch
    int reedSwitch = 2;
    bool reedSwitchStatus;

    //pin for led
    int led_pin= 9;

    void setup()
    {
      Serial.begin(38400);
      pinMode(solenoidPin, OUTPUT);
      pinMode(reedSwitch, INPUT);

      doorUnlock();
    }

    void loop()
      {}

    void doorUnlock()
    {
      digitalWrite(solenoidPin, LOW);
      delay(5000);
      checkReedSwitchStatus();
    }

    void checkReedSwitchStatus()
    {
      reedSwitchStatus = digitalRead(reedSwitch);

      if(reedSwitchStatus == 1)
      {
        Serial.println("Beginning Transaction");
        beginTransaction();
        }
      if (reedSwitchStatus == 0)
        {
          Serial.println("Ending trasaction");
          endTransaction();
          }
      }
      void beginTransaction()
      {
      digitalWrite(led_pin, HIGH);
      delay(500);
      digitalWrite(led_pin, LOW);
      delay(500);
      }

My issue is the beginTransaction function is never executed. Serial monitor continuously prints 'Beginning Transaction'. Attached the screenshot of the serial monitor. Please suggest me what is the error in my code. Thanks in advance!

How do you know, that the beginTransaction() function is not executed. Please include the full code. Also: Do you have an external pullup or pulldown resistor for the reed switch?

Hi Chrisl, I have used an external pull up resistor for the reed switch. I have also edited my question to add the beginTransaction() function in the code. The function is not getting executed because the LED does not blink.

The problem is, that you don't initiate the LED's pin to an output. On reset the pin is configured as input. Doing a digitalWrite(led_pin, HIGH) in this state just enables the internal pullup resistor. If you measure the voltage without the LED connected, it will be 5V, but since the pin only provides a very small amount of current through the pullup resistor, the LED cannot light up when connected.
You need to configure the LED's pin as an output through
pinMode(led_pin, OUTPUT);

in your setup() function.
So actually the beginTransaction() function was correctly executed. You just couldn't see it.

Thanks!! That corrected the issue.


text:
Control 12V power with 3 transitors to 3 seperate consumers
I have this shematic. With one electrical Pump and two solenoid valves I want to control via the arduino.
Here are the specs for the parts:

Pump: 12V max. 250mA
Valve 1: 12V max. 160mA
Valve 2: 12V max 220mA
Source: 12V max 2A

simulate this circuit – Schematic created using CircuitLab
My questions is:
Are the 4.7k resistors enough?
Do I need different resistors for the different consumers?
And I am using S8050 as transistors. Are they to small for the load?
And where do I have to connect the ground of the arduino to?

I think you mean S8050 as transistors and in the circuit I see 2N3904's

Thanks. I corrected it.

Connect the Arduino Gnd to the 12V supply Gnd.  From what I see here, https://www.digikey.com/products/en/discrete-semiconductor-products/transistors-bipolar-bjt-single/276?k=S8050 most S8050 parts need 80mA or more to turn into saturation - which is more than an Arduino can supply.  You'd be better off with N-Channel MOSFET, which takes little drive current, and with low Rds will have little voltage across the  Drain-Source.
Example: https://www.digikey.com/products/en/discrete-semiconductor-products/transistors-fets-mosfets-single/278?k=aod5

(5v/4700r) * 100hfe = 0.106A; not enough current for any of them. Try a 330R: good for 1.5A (or still 600ma at the worst-case 40hfe), while only pulling 15ma from the MCU. You can go up to 680r...


text:
Connecting Peltier module to Arduino Nano
I am a beginner to Arduino programming and started working on my first Arduino project recently to power a Peltier cooling pad. Below is the code I used and in the circuit,
I connected the positive (red wire) end of the Peltier to D12 of Nano Arduino board and the negative end( black wire) to the negative end of the 6V battery. Then I powered the Arduino board by connecting Vin(Arduino) and battery(+) using a jumper wire. The GND pin of the Arduino was connected to the battery(-) using a jumper wire.
The Peltier is not working and it would be a great help if someone can help me to understand what I did wrong.
int p=12;

void setup() {
   pinMode(p,OUTPUT);
}

void loop() {
   digitalWrite(p,HIGH);
   delay(2000);
}

Note that you set pin 12 to HIGH, but you never change it (is that intentionally?) .. In this case you could have set it high in setup and remove the delay (meaning the loop will stay empty).

Arduino cannot provide the amount of current that Peltier needs to heat up. Arduino cannot power devices it can only steer something that powers them. Try checking out a relay shield or read about MOSFET.

Hi Michel and Flip, Thank you very much for the responses. I am a beginner to electronics and Arduino and your support is highly appreciated. I found below example online, which is powering a Peltier using an Arduino and wanted to build a simple circuit with the same principle using Nano Arduino board. If I connect a resistor to the circuit will it function?

https://www.instructables.com/id/How-to-Set-Up-a-Peltier-Module/

Find a different tutorial, cause that one is terrible. I you read the comments for that tutorial, you see that they point to the same problem Michel and Filip told about.

Hi Filip and Gerben, Thank you very much for the comments. I tried making the circuit, and the Peltier is not functioning. As suggested in the comments of that tutorial, I thought of using a motor driver for the Peltier and found below article, which is a bit complicated for a beginner like me. However, I made the circuit following instructions, but the Peltier and the circuit are still not working. Please tell me whether the instructions and circuit in this article are correct?

Is there a simple method to connect Peltier to Arduino using a Motor driver.?  As suggested by Filip, I read about MOSFET, but couldn't figure out how to connect it to the circuit. It would be a great support if you guys could assist me.

https://www.instructables.com/id/Smartphone-Operated-Smart-Wristband-for-Personal-A/

I'm in a helpless situation now due to lack of my knowledge in this domain. I did a lot of reading also bit still couldn't figure out the solution. I was continuously working on this circuit and determined to find a solution and your help will be a great support for me.

You could use a motor driver, but it's overkill. See Filip's answer, using a single MOSFET transistor and a pull-down resistor. That's all you need. (Note that you may have fried the pin on your Arduino by trying to push too much current through it. An Arduino pin can only put out ≈20mA, and your peltier junction probably draws a couple of amps (100X more than the max).

Note that you COULD use a motor driver to drive the Peltier junction in both cooling and heating mode (motor drivers have "H Bridge" circuits that let you push current in either direction. If you power a Peltier junction the opposite way, it heats instead of cools.)

I prepared a little circuit that should help you safely connect the Peltier module to Arduino. It uses a single n-channel MOSFET and 1K resistor.
I couldn't find any Peltier in Tinkercad so instead I used a simple light bulb. (In previous version of this answer I used a DC motor, but it was not a good replacement for Peltier module)
When Arduino Pin12 is HIGH light is bright (high current flows through it just like it should through the Peltier) when Pin12 is LOW light bulb goes dark (no current is flowing)

One note to other readers: Don't wire a motor that way. It will fry the transistor. If you're going to power a motor you need a flyback diode to protect the transistor from back EMF from the motor's inductive coils.

Hi Filip,  Thank you very much for guiding me and the circuit diagram is very helpful. I will make the circuit and will check the functionality.  Really appreciate your help. :)

Hi Duncan,  Thank you very much for guiding me.
Regarding your last comment on ' motor', does that apply to Peltier circuit as well as I am planning on making the circuit following the diagram proposed by Filip.      Well noted your suggestion to use a motor drive to make a circuit to get both heating and cooling effect from Peltier. I will try working on that circuit after finalizing the circuit with MOSFET( proposed by Filip).

@DuncanC I changed DC motor to a light bulb. No extra circuitry is required for light bulb and Peltier module.

Filip, good idea. Indee, A Peltier junction and a  light bulb are both simple resistive loads, and don't require flyback diodes. That's only needed for inductive loads like motors and relay coils.

Indee, you could also rig 2 MOSFET transistors to run your peltier junction as either a heater or a cooler. (You'd make one MOSET feed current in one direction when it was energized, and wire the other one to feed current in the opposite direction. You'd either have to make certain that you'd never turn on both transistors at the same time, or add a high current diode to avoid a short circuit if both transistors are turned on at the same time (which would likely destroy the transistors)

Hi Filip and Duncan, I made the circuit and it worked well with the Peltier. But I had to connect the system into 1.5x4 V battery. Thank you very much for your guidance and really appreciate your support. Now I will try the circuit with 2 MOSFET transistors to get both heating and cooling.


text:
Temperature varations using ADS1115 and voltage divider to read 12v
I have an issue with reading battery voltages of three 12 volt batteries using an ESP-01 and an ADS1115.  I have been graphing the measurements and the all of the graphs have a temperature component to the readings.  As the outside temperature increases, so does the reading from the ADS1115.  I have verified that battery voltages do not change with the temperature.  I have also recreated the problem by heating up my project case and seeing a great increase in the readings.  Both of my voltage divider resistors are made of the same material, so I would have thought that the changes in resistance would affect both components and not change the reading much.  I have replaced the LD1117 with a 3.3v buck converter and the problem still exists.
Details of my project are located here: https://hackaday.io/project/167291-rv-battery-monitor
ThingSpeak data graphs: https://thingspeak.com/channels/870224
Any ideas where the temperature component error is originating?

Your resistor values are way too high. The ADS1115 can have (depending on the settings) an input resistance as low as 3MΩ. Your resistors (battery output impedance) needs to be no more than 10% of that. For the impedance of a voltage divider calculate the parallel resistance of the two resistors involved (909kΩ currently).

consider reading the 3.3v at the same time, then using any derivation from 3.3v to calibrate the 12v readings. That said, the ADS should not fluctuate very much from temp, so maybe your resistors are getting hot.

I finally received my resistors in the mail and was able to replace them with smaller values.  I decided on using 100k and 10k for the voltage divider and the temperature error component is mush less, .07 volt difference in readings between 30F and 95F.  This is sufficient for my needs.  Thanks for the recommendation Majenko!


text:
Is std::array (from the C++ STL) safe to use on arduino? Does it use dynamic memory allocation?
I'd like to use std::array on a project that will need to be very stable, and have all memory pre-allocated to avoid heap fragmentation.
I am reading in characters from the serial port, following a known protocol. Each received byte will be written to a char array of ample size to hold the longest possible string I will receive. I will then perform some minor on the fly operations, (i.e. skipping certain characters, replacing one with another, etc.) and write those out another serial port.
This device needs to function indefinitely. I will not be calling malloc or new anywhere in my code. All of my control objects are singletons, (audible gasp from the high-level crowd!) created during setup, and never being destroyed.
Is the STL array template safe to use in this context?
After reading this post, and this post, the only potential issues I can see are exception handling. As far as I'm concerned, an exception is as fatal as an access violation. I would not expect to ever attempt recovery from an exception, so I don't care that Arduinos don't support them.
But what will happen if the program tries to throw one? Will the arduino compiler even allow the use std::array if it supports exceptions? Is there an Arduino-friendly array template that uses fixed size arrays and supports iterators?
Thanks!

I don't put it as answer, because it's not directly answering your question. It seems it is dynamic memory allocation safe to use std::array, however, you still don't know what's under the hood, maybe memory consumption is an issue (stack size of local variables of nested functions called by the public functions for replacing and iterating). If you need some minor functions, I would write them myself and stay in full control of both memory and performance decisions.

"I would write them myself and stay in full control of both memory and performance decisions"
That's the eternal question. My time spent writing it myself, or my potential time spent figuring out where my memory went. I'm working on other parts of the code in the mean time, but I hope someone who has already made this mistake can chime in before I commit to one or the other.

@Michel Keijzers Also, FYI, I am running this on a Mega, so it does have more memory. But still it isn't a lot, in the grand scheme of things.

std::array does not use dynamic memory allocations to store its elements. If you use static or stack-allocated std::arrays, you don't have to worry about memory fragmentation (contrary to std::vector or String, for example).
Of course, if you allocate arrays on the stack, you can have a stack overflow if you call too many functions, either by design, or because of a bug.
That brings us to the problem of exceptions. If you look in the standard, you'll see that most of the member functions of std::array are marked noexcept, with the notable exception of the element accessors. Obviously, the at() accessor can throw, but you'd expect that operator[] doesn't.
In practice, operator[] is marked noexcept in the version of the STL (GCC9) that I have on my computer, so if you check it in the STL implementation you're using, you can be pretty confident that it won't throw. Just keep in mind that this is not mandated by the standard.
/usr/include/c++/9/array
      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

The debug version is also marked noexcept, but it can throw/abort if the index is out of bounds:
/usr/include/c++/9/debug/array
      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      {
    __glibcxx_check_subscript(__n);
    return _AT_Type::_S_ref(_M_elems, __n);
      }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      {
    return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n)
     : (_GLIBCXX_THROW_OR_ABORT(_Array_check_subscript<_Nm>(__n)),
        _AT_Type::_S_ref(_M_elems, 0));
      }

The STL implementations for Arduino I found online don't seem to have the <array> header.
Luckily, you can easily create your own array container, for example:
template <class T, size_t N>
struct Array {
    // Storage
    T data[N];

    static size_t length() { return N; }
    using type = T;

    // Item access
    T &operator[](size_t index) { return data[index]; }
    const T &operator[](size_t index) const { return data[index]; }

    // Iterators
    T *begin() { return &data[0]; }
    const T *begin() const { return &data[0]; }
    T *end() { return &data[N]; }
    const T *end() const { return &data[N]; }

    // Comparisons
    bool operator==(const Array<T, N> &rhs) const {
        if (this == &rhs)
            return true;
        for (size_t i = 0; i < N; i++)
            if ((*this)[i] != rhs[i])
                return false;
        return true;
    }
    bool operator!=(const Array<T, N> &rhs) const {
        return !(*this == rhs);
    }
};

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

  // Create an array
  Array<int, 5> myArray = {1, 2, 3, 4, 5};
  // On older compilers, use double braces:
  //    Array<int, 5> myArray = {{1, 2, 3, 4, 5}};

  // Iterate over the array
  for (int element : myArray)
    Serial.println(element);

  // Access elements of the array
  myArray[2] = 30;
  Serial.println(myArray[2]);
}

void loop() {}


text:
ADS1115, ACS712 and ESP8266
I have an ACS712 (5v sensor), an ADS1115 (5 or 3.3v) and an ESP8266 board (3.3v).
I know I can't directly use the ACS with the ESP without a voltage divider on the analog pin. So I figured I could run the ADS and the ACS off 5 volts as the ADS communicates over I2C. Does this cause any issues with the SDA/SCL lines on the ESP?
What is the correct way in going about this?

The I2C lines of of ADS1115 will use 3.3 V if you power it with 3.3 V, but then the maximum analog input voltage would be 3.6 V (VDD + 0.3 V).

i am aware, but that wasn't my question

The SDA line of of ADS1115 will use 3.3 V if you power it with 3.3 V, but then the maximum analog input voltage would be 3.6 V (VDD + 0.3 V).
The ACS712 has the middle value at 2,5 V so to read it you need the 5 V range and must power the ADS1115 from 5 V. Then the SDA line of esp8266 will be connected to 5 V logic level, but the esp8266 pins can handle 5 V TTL communication currents.
The SCL line is driven from master (esp8266) at 3.3 V and the ADS1115 is good with it.


text:
UART communication - Serial is always empty
I have a payment terminal which uses UART (or simply speaking Rx, Tx, Gnd pins) and I have an Android tablet app which is connected to the terminal using USB to DB9 adapter based on PL2303 chip. The Android app works well and it uses https://github.com/felHR85/UsbSerial to support serial communication. The protocol is very simple, basically Android sends strings like "REQINFO,4", "L2,xxx,xxx,*" etc. and recieves back a string statuses.
I'm trying to replace Android app with Arduino UNO, for which I naively assumed would be enough just to connect Tx,Rx of the terminal with Rx,Tx pins of the Arduino and also to connect Gnd pins. But I can't get it working. The only thing I noticed is when I connect Arduino Rx to terminal Tx, the terminal's screens briefly shows "Connecting..." but that's probably because it detects some incoming voltage. When it comes to reading Serial (or also I tried SoftwareSerial) nothing is ever returned.
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
    } else {
      data += c;
    }
  }
}

So do I miss anyting in order to have a proper communication? Thanks.

It seems this package supports various methods of flow control (for example rts/dts and others) these are used by the two devices to coordinate communications. If your terminal is setup to use flow control, then you will have to add more to your arduino code to support it depending upon the nature of the flow control. You should also consider the message format (parity, start/stop bits and baud rate). https://github.com/felHR85/UsbSerial/wiki/4.-Asynchronous-api

@GMc In the Android code flow control set to NONE, so I presume I can ignore that. Also, just for test I disconnected DB9 from the terminal COM port and connected just Rx,Tx pins and everything continued to function.

Check (e.g. with a multimeter) the DB9 voltages! Mostly RS-232 is used on those kind of connectors with voltages +-12Volts (there are other variants as well, up to 15V), but your Arduino's UART uses TTL levels (0V as logic low or 5V as high on a 5V Arduino). You'll need to convert these, possibly with a chip like MAX232 or similar.
Also, for reverse engineering this I recommend using an Arduino with multiple serial ports (e.g. Mega), or at least multiple software serials (with proper level shifting of course). You connect your Android tablet to your reader through your Arduino, and when you receive a byte from one device, send it to the other one, and also send it to your PC along with the information about direction. This way you can understand all the used commands if you sniff long enough. You could also use an SD card on SPI if you need your sniffer system to be mobile (walking in a warehouse scanning items).
If you have access to a logic analyzer, it can also be used as a sniffer. This has an additional advantage, you can change BAUD rates later if your guess was wrong.
(started as a comment but ran out of characters, so I thought I'll explain it a bit more)
https://www.db9-pinout.com/db9-pinout/db9-pinout.gif
If it's a standard cable for RS-232, this diagram shows which pin is which. DCE-DCE and DCE-DTE cables were different back then (one connects a PC to a modem, the other 2 PCs), so you should check both voltages from 5 (GND) to either 2 or 3. An empty line has logic high, which is 5V in case it uses TTL, and -5 or lower (like -12 or -15) for RS-232.
Test different BAUD rates as well!

I'm pretty sure that whole system functioning using 5V but indeed it's a good idea to doublecheck that. Regarding sniffing, I actually tried something similar by connecting my Arduino to the tablet and staring into monitor window. For some reason that didn't show me any info either.

So, are you suggesting to try a TTL adapter like this -https://m.ebay.co.uk/itm/MAX232-RS232-Serial-to-TTL-Converter-Board-PIC-Adapter/302506517436?ul_ref=https://rover.ebay.com/rover/1/710-53481-19255-0/1?ff3=2&pub=5575376664&toolid=10001&campid=5338268676&customid=CjwKCAjw5_DsBRBPEiwAIEDRWzVL2-w0CSoRPVgEt5tSf8n21N6NC2qCud08araW72RE16h-KPUeZBoC6nwQAvD_BwE&lgeo=1&item=302506517436&srcrot=710-53481-19255-0&rvr_id=2136994577017&rvr_ts=aa3a806616d0a16ef8f4118afffc2a78&_mwBanner=1&_rdt=1&ul_noapp=true&pageci=c3e011ca-5fb3-4b66-b4f0-c31215a3f717 ?

That hardware would do it, yes. You might need 2 of them, one to the tablet, and one for the reader. But first, check the voltages!

today I tried your suggestion with TTL converter and indeed it works well. Now I can sniff data coming from tablet to Arduino. I used Arduino Mega so I hooked terminal to Rx2,Tx2. But for some reason attaching another TTL on between these pins and the terminal didn't bring any value. I wonder do I need it at all, as without TTL for terminal I can at leat recieve some gibberish -- ⸮⸮i⸮v맧⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮u[[⸮⸮_gu}Yu⸮Yucw⸮}⸮gaqmc⸮[uya[w⸮⸮ possible there's a way to adjust something (baud rate?) to see real content. Anyway thanks, you helped me a lot!

If you have access to - even a cheap ($8) - logic analyzer, you can determine the speed. Or you can test common baud values. You can also send to your PC hex values, the data might be binary, and it'll stay gibberish, even when the settings are right.

actually I managed to achieve what I wanted, so two TTLs were necessary. Used this little app to communicate over Serial port on Windows machine: http://www.hobbytronics.co.uk/ht-comm.  And I laughed when reaized what caused the gibberish problem - weak contact. Soldering solved it completely. Thank you, mate!

There is already an answer and comment about possible hardware / flow control issues, so this answer is only dealing with your Arduino sketch. Iv’e added a couple of print statements and the FreeMemory library to test your sketch.
#include <MemoryFree.h>
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    } else {
      data += c;
    }
  }
}

When I repeatedly enter the following text in the serial monitor "1234567890", here is the results of the print statements:
REQINFO,4
1234567890
freeMemory()=1770
1234567890
freeMemory()=1770
12345678901234567890
freeMemory()=1760
12345678901234567890
freeMemory()=1760
123456789012345678901234567890
freeMemory()=1750
123456789012345678901234567890
freeMemory()=1750
1234567890123456789012345678901234567890
freeMemory()=1740
1234567890123456789012345678901234567890
freeMemory()=1740
12345678901234567890123456789012345678901234567890

Every time you receive new data, it is appended to the data string, causing the string to grow and available memory to disappear. Using the String object should be avoided.
Here is a simple sketch that uses a char array as a buffer for the incoming data:
// Set the buffer size to accomodate the largest
// "chunk" of data you will be receiving.
const byte bufferSize = 64;
char inputBuffer[bufferSize + 1];

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

void loop(){
  if(Serial.available() > 0){
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    Serial.print("inputBuffer=");
    Serial.println(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}

Ah, yeah that sketch is just to test the communication is possible in general. But nonetheless, appreciate your input.


text:
Can I connect esp32 to a phone USB charger?
I have a USB charger. Is it ok to connect it as a power supply for esp32?
Edit: i have a dev board esp32

In principle yes (see also comment in update).
The voltage is ok (5V), typically USB, and it doesn't differ from the output of a computer USB port.
The output current is max 2000 mA, so check if your project (ESP + related hardware powered by this USB), is not exceeding 2000 mA. The ESP needs much less than 2000 mA, so if you didn't have a lot of external components or motors than you will be safe.
Update
Important omment from Sim Sson: The bare esp32 is not 5V-tolerant, so using a usb-charger is only ok for esp modules that have a voltage regulator onboard.

I think you might have missed a zero there. The charger says "2000mA".

@hooskworks Thanks for the notification, and yes I did (updated my answer).

The bare esp32 is not 5V-tolerant, so using a usb-charger is only ok for esp modules that have a voltage regulator onboard.

@SimSon I was assuming he will connect the USB cable into the plug (thus having some kind of development board). But I will add it to the answer, thanks a lot.

@yuria Hopefully he does, but he didn't tell. Thanks for adding that point, it might be useful for others having this question in future!

@SimSon True, a year ago I possibly wouldn't realize it myself

@SimSon Bare esp32 is only the rectangle right?if i have a micro usb,then it is the dev board?

@yuria yes, a device with usb socket is always supposed to be 5V tolerant as that's part of the standard


text:
LCD screen won't stop printing the same characters twice
I'm hoping that someone might be able to help me figure out how to prevent my LCD from giving me double digits (i.e. 55, 66, 77 - instead of 5,6,7);
I have 2 functions that are printing, so I'm expecting the issue to be related to this.
Here's the code:
#include <Wire.h>

#include <Adafruit_LiquidCrystal.h>
#include <Keypad.h>

unsigned int deBounce = 100;
int curs = 0;

Adafruit_LiquidCrystal lcd(8, 9, 3, 10, 11, 12, 13);

const byte numRows = 4; //number of rows on the keypad
const byte numCols = 4; //number of columns on the keypad

char keymap[numRows][numCols] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'.', '0', '#', 'D'}
};

char keymap2[numRows][numCols] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'.', '0', '#', 'D'}
};

//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = {25, 27, 29, 31};
byte colPins[numCols] = {17, 19, 21, 23};

//initializes an instance of the Keypad class
Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
Keypad myKeypad2 = Keypad(makeKeymap(keymap2), rowPins, colPins, numRows, numCols);

char enteredDigits[10]  = " ";//null terminated character array to hold entry
char enteredDigits2[10]  = " ";//null terminated character array to hold entry
boolean entryComplete = false;
boolean entryComplete2 = false;
boolean first = 0;

float result; // Create an integer for the result of 'A' and 'B' (in this case, it will be the 'Inductance' x 'Capacitance')
float power = .5; // Used in the equation
float r1; // Result 1
float r2; // Result 2
float r3; // Result 3
float r4; // Result 4
float fc; // Result 5
float power2 = 6; // Used in the last part of the equation
float result2 = 10; // Also used in the last part of the equation
#define TWO_PI 6.283185307179586476925286766559 // two Pi (:
float num1;
float num2;

void setup()
{
  myKeypad.setDebounceTime(deBounce);
  myKeypad2.setDebounceTime(deBounce);

  lcd.begin(16, 2);
}

void loop()
{
  getNumber();
  if (entryComplete)
  {
    entryComplete = false;
    lcd.setCursor(0, 1);
    num1 = atof(enteredDigits);
    first = 1;
  }

  if (first == 1) {
    getNumber2();
    if (entryComplete2)
    {
      entryComplete2 = false;
      lcd.setCursor(0, 1);
      num2 = atof(enteredDigits2);
      values();
      first = 0;
    }
  }
}

void getNumber()
{
  static byte index = 0;
  char key = myKeypad.getKey();
  if (key != NO_KEY)
  {
    switch (key)
    {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9': case'.':
        lcd.print(key);//print entry on top row
        enteredDigits[index] = key;//build character string
        index++;
        enteredDigits[index] = '\0'; //null terminate
        break;

      case '#':
        lcd.setCursor(8, 0);
        lcd.print(F("= Ind."));
        delay(1000);
        entryComplete = true;
        index = 0;//reset for next entry
        break;

      case 'D'://clear entry and display
        memset(enteredDigits, '\0', 10); //clear buffer
        lcd.clear();
        index = 0;
        entryComplete = false;
        break;
    }
  }
}

void getNumber2()
{
  static byte index2 = 0;
  char key2 = myKeypad2.getKey();
  if (key2 != NO_KEY)
  {
    switch (key2)
    {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9': case'.':
        lcd.print(key2);//print entry on top row
        enteredDigits2[index2] = key2;//build character string
        index2++;
        enteredDigits2[index2] = '\0'; //null terminate
        break;

      case '#':
        lcd.setCursor(8, 1);
        lcd.print(F("= Cap."));
        delay(1000);
        entryComplete2 = true;
        index2 = 0;//reset for next entry

        break;

      case 'D'://clear entry and display
        memset(enteredDigits2, '\0', 10); //clear buffer
        lcd.clear();
        index2 = 0;
        entryComplete2 = false;
        break;
    }
  }
}

void values() {

  result = num1 * num2; // If a 'comma' key is pressed (in this case, the # key on a 4x4 keypad)

  lcd.clear(); // Clear the writing from the LCD
  lcd.setCursor(0, 0); // Set the cursor position to the first block on the first line
  lcd.print(F("Ind. =")); // Display 'Ind. =' onto the LCD Screen
  lcd.setCursor(7, 0); // Set the cursor position to display after the previous text
  lcd.print(num1, 4); // Display the number value given to num1
  lcd.setCursor(0, 1); // Set the cursor for the first block on the second line
  lcd.print(F("Cap. ="));// Display 'Cap. =' onto the LCD Screen
  lcd.setCursor(7, 1); // Set the cursor position to display after the previoust text
  lcd.print(num2, 2); // Display the number value given to num2
  delay(2500);

  r1 = pow(result, power);
  r2 = r1 * TWO_PI;
  r3 = 1 / r2;
  r4 = pow(result2, power2);
  fc = r3 * r4;
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(F("Res. Peak =")); // Display the answer onto the LCD Screen
  lcd.setCursor(0, 1);
  lcd.print(fc);
  lcd.setCursor(9, 1);
  lcd.print(F("(Hz)"));
}

I fear it's related to debounce time and the duration of pressing a keypad button. Is it always exactly duplicating the entries?  What about a debug output (Serial) to see more, what's going on?

Hmm, I didn't notice anything after changing the debounce settings. Even with a relatively high debounce (500 milliseconds), it still prints double.

If I take out this line from the getNumber2 function:

I had to remove this line from the getNumber2 function!
lcd.print(key2);
works now (:

keymap2 is not useful at all and just a duplicate. But having both keypads act on the same pins is your issue. Or don't you intend to have two keypads ?

You need to break your code into parts and debug it part by part. Start by printing a single character to the LCD once, and setting a bool so you don't do it repeatedly. If that works, the LCD is not your problem.
As DataFiddler suggested, bounce problems with your switch seem like a likely culprit. Add serial print statements to your button handling code and see if it's being triggered more than once. If so, research debouncing code.


text:
Bootloader and AtmelStudio
I am having issues getting the main program to run after flashing via BOSSA with a bootloader. Jump to the bottom for my question and TL;DR.
Here is my current situation:

UF2 bootloader successfully compiled for SAMD21G18A
Bootloader flashed with ATMEL ICE and runs correctly upon reset
Device shows up as external storage and also as a CDC device in BOSSA
Flashed a hex file successfully in BOSSA (with offset applied) and then reset device
Program on hex file doesn't ever run

The program is just the Arduino "Blink" example, converted to an AtmelStudio solution. The linker script has been modified to have the origin at 0x2000 (as expected by the bootloader).
Other things I've tried to no avail:

a variety of offsets
many different bootloaders of CDC and MSD variants
uploading the compiled program with the Arduino IDE, BOSSA, AtmelStudio etc

Other points worth noting:

The AtmelStudio solution contains two projects as is standard when importing an Arduino sketch. 1) ArduinoCore 2) Blink
LEDs on my board work as expected (breathing to indicate in the bootloader)
When I import the Arduino sketch into AtmelStudio and flash it to the device the device mounts as a CDC device (via the native USB port) to my computer. I don't know why this is happening as the linker script doesn't include any provisions for a bootloader and the program itself doesn't instruct the hardware to enable the USB port. I have no idea why this is happening.
it seems like the bootloader never detects a program as it always runs upon startup. This is the behaviour when a program cannot be found.
The .hex file generated by the Arduino IDE doesn't ever launch either
If flashed from Arduino IDE or AtmelStudio directly the program does run

TL;DR:
Known working main program/sketch never gets run with bootloader on SAMD21G18A.
My question:
What would cause the bootloader to not find the main program and hence never run it?
Any other insights as to why I have not had any success here would be greatly appreciated too. My suspicions are that this has something to do with the way the main program is being compiled and linked.
Cheers!

and upload over the mass storage works?

the file transfer succeeds but the program never runs. The goal is to use CDC to upload though so I haven't put much energy into this


text:
Brownout detector triggered
I'm running a pretty basic setup. When I run a small program just doing some serial.println, it works fine, when I try to do operations that needs more power, the brownout detector gets triggered. I'm running my chip on an ok buff power supply so I don't get what the problem is.

The ESP typically runs on 3.3 Volt, not 3.0 Volt.
Secondly, it looks like the board has a voltage regulator, all power goes through the voltage regulator. If that's the case the voltage you need to supply must be lower that the drop-out voltage of the regulator (which is typically around a volt).

the thing you see on the PCB is a 10k resistance, from power to the EN pin as required, i havent added any voltage regulators

(the big blue thing is just the USB to UART, it doesnt draw any power or provide any power)

and btw the operating range of the ESP32 is 3v to 3.6v,

I mistook the 3-pin part in the schematic for a linear voltage regulator. I know the ESP can run on a lower voltage. But since you were having power related problems it might be a idea to at least check whether the problem remains when supplying 3.3V. 3.0 is the minimum voltage the ESP runs at, and there might be some resistance in the wires, and breadboard, that could cause a high enough voltage drop when the ESP is drawing more current for the ESP to brown out.

Why is the USB to serial board connected to your 3 volt supply? Also make sure your breadboards power rails (blue and red) don't have a split in the middle. Some breadboards have this "feature".

for some reason the usb to uart need power suply,

im not home atm but running it on 3.3v will probably not change anything

tho the weird thing is that it consistently brownout evry second time


text:
How to fetch the com port or any id I can use to upload specific program to a specific arduino? e.g. "a.ino" to arduino micro
My project is a head mouse for which I am using two arduino boards . I want to upload a specific program to a specific arduino. How can I do it? And if I need to use a pid or com port id about which the official arduino forum people suggested, how can I retrieve this id? I'm using an Arduino micro and a pro micro if it helps any.
I need some suggestion on how to load the sketch to arduino through code without actually opening the arduino ide directly.Because it's a client project. And how can I make a specific program upload to the specific arduino one at a time. e.g. "a.ino" to arduino micro and "b.ino" to arduino pro micro. How should I identify the arduino boards through code.As for the OS, I am using Windows 10 64 bit.

What OS are you using?

I am using windows @majekno. And yes, I need some suggestion on how to load the sketch to arduino through code without actually opening the arduino ide directly.Because it's a client project. And how can I make a specific program upload to the specific arduino one at a time. e.g. "a.ino" to arduino micro and "b.ino" to arduino pro micro. Hpw should I identify the arduino boards through code.

done @jsotola. Please, help me solve it.


text:
Relay controller with IO expander
found this
http://www.zevendevelopment.com/relayexpander.html
I was looking to control 48 relays in sequential order with external controls for duration and frequency. How do I properly communicate to the boards? Sorry new to this setup.

Looks like you communicate via the IOExpander board.

Their IO expander gets controlled via Serial (UART). From there all the relay expanders are controlled. Have you already bought these boards?

I guess what I’m really saying is I’m not clear on how to properly code this. I have not bought these boards yet but they seem like the perfect solution. Would you recommend anything else?


text:
Have I fried my arduino uno?
I made a smart dustbin using arduino, servo motor, & ultrasonic sensor. It worked pretty well for a few number of days. But once I don't know how but the Arduino 'ON' light started to become dim and switched off. I used a 9V HW battery. So I decided to plug in my arduino with a 7V AC charger, still no luck, the arduino did not turn on nor the ON light. Then I plugged the arduino to my PC, the ON light turned on for 2 to 4 seconds and switched off. I realized it became too when I touched the usb port. The ATMEGA chip did not become hot. Please help?

why do you expect the chip to become hot?

Unplug everything (servos and sensors) and try again.

If the USB chip is hot, you are out of luck.


text:
Extending pulses of a square wave signal
My idea is to modify a diesel injection system to increase the fueling into the engine.
The signal to an injector is a series of 0.1-1.5ms pulses. I would like to analyse the pulses and then send out my own pulse to extend some of the injection pulses. I want to do this all in real time.

Is this possible on an arduino? I have never used one before so I'd like to know if it is possible and what product would be suitable.

What kind of diesel engine are you using? Have you looked at the injector waveform with an oscilloscope? If you have "Peak and Hold" style injectors: http://autoditex.com/page/peak-hold-injector-53-1.html, then you may have to replicate the "current limiting" phase of the injector "on time". Please edit your question and add some details about the diesel engine / injector you are using.

Yes, assuming the calculations are not that time consuming.
The Arduino is 16 MHz, so this is in the us scale which is way within limits. I don't know how critical the rise and fall times are, but even that should be possible.
You need some additional circuitry though, because the Arduino itself cannot handle 12V signals. For the input, you need so called level shifting (from 12 V to 5 V), see A-Quick-Guide-on-Logic-Level-Shifting for more explanation.
For the output, you need a 12 V signal (or use a voltage booster to 12V), and a transistor (and probably some resistors) that is connected to the Arduino for the signal and to the 12V and the diesel injection system for the 12V.

Wonderful I'll order a nano and take a look at it!

If it helps, consider upvoting and accepting the answer.


text:
About boot-loader ic used in DEV boards
I have problem with Arduino MEGA, Arduino Deu etc...  Those Development board are having separate MCU except main MCU... Why? For what purpose are they used for?
as FTDI or bootloader chip or protection for main MCU or  what other purpose?
I don't have an idea about that?
what are they called?
Please any one clarify me this?

question 1, question 2.

There are two different reasons for a second MCU on a development board.
1) If the main MCU has a bootloader for serial upload, but doesn't include USB peripheral and the dev board should have for convenient development an USB port, then the board must include a USB-to-TTL-Serial adapter ('FTDI'). The adapter can be an FTDI USB chip, some other manufacturers USB chip (most common is CH340) or an MCU (with a USB peripheral) programed as USB-to-TTL-Serial with a firmware. Original Arduinos use ATmega 8u2 or 16u2 for this.
2) Some dev boards include a programmer for upload without bootloader. The programmer is a second MCU running a programmer firmware and is wired to programming pins of the main MCU. For example Arduino Zero, M0 Pro or Uno WiFi Rev 2, Nano Every have this concept.


text:
How can I receive signal from remote control using tcrt5000 sensor module
how can I use tcrt5000 sensor module instead of TSOP31238 (TSOP1738) IR receiver to get signal from remote control? I want to create remote control for my PC to navigate through my slide shows. Thanks in advance.

why do you want to use the tcrt5000? ... how is the Arduino used in your project?

@jsotola, because I have only this sensor :) and haven't other

what are you using for remote control?

@jsotola usual ir remote control

there is no such thing as "usual ir remote control" ... there are differences between brands in the way that keypresses are encoded

The TCRT5000 and the TSOP31238 are very different. The TCRT5000 is actually a reflective distance sensor. It has an IR LED and a simple IR phototransistor, not more. The TSOP31238 in contrast is meant to receive data from IR remotes. IR remotes work with modulation of IR light. The IR LED is pulsed with a frequency of 38kHz (in the case of the TSOP31238). This frequency is modulated with the actual data, meaning there are different time lengths were there is no IR signal and where there is a 38kHz IR signal.
The TSOP31238 detects the IR light with a phototransistor, like the TCRT5000 has. But then the signal is processed with an amplifier, a band pass to filter out all frequencies but the 38kHz and then demodulated, so that you don't see the 38kHz signal on the output, but only the pulse lengths.
The demodulation should actually be the least complex part to build yourself. That can be even done by code. But to get good results, you also need the other parts. You would have to build an amplifier circuit with an opamp. And would have to build the bandpass (for example with an LC element).
You can build these things yourself, but: The sensor, that you have, is not meant for receiving IR remote signals. The parts, that you would need to make the signal usable, will cost way more, than just buying a TSOP. Also it will be a lot easier and most likely better working (processing the signal from a phototransistor can be tedious). I suggest, that you buy a TSOP chip fitting to your remote control.

Thanks a lot for extended answer. In this case that I use many triggers in remote control maybe I agree with you. So if  will used TSOP it simple way to make scratch and take a goal. I found another solution to use 2 pin IR led. link
link2

Yes, such things are possible. I didn't include it, because mostly these solutions will have a worse performance and are way more difficult to use (The standard libraries don't work for this). It may be suitable for you, especially, if you want to do it for the sake of learning. If you want to achieve a specific target, then I would advice to use the easiest solution.


text:
pin going high not allowing analog read to change
I have the following problem:
My arduino takes analogRead(A0) from a potentiometer whose position I can't adjust directly.
When analogRead(AO) goes to a value X,  I want pin 8 to go HIGH, this causes the circuit to open. and stop A0 getting higher . so I do an if statement:
if(analogRead(AO)> X) {

digitalWrite(pin, HIGH)  \\opens the circuit}

else {
digitalWrite(pin, LOW)  \close the circuit
 }

The issue I have here, is when then circuit is open,  I would like to change the value of the potentiometer (A0) which is controlled by a motor which is also in the circuit: but doesnt depend on the arduino board.  Given I can't control A(0) then the circuit will remain on A(0) >X forever.
The system going to LOW pin or close circuit, after it reaches HIGH pin for 2 seconds would be great, but then the program goes to the beginning and realizes that still A(0)> X , and goes back to a open circuit state, therefore not allowing me to have the close circuit anymore in order to make A(0) < X  and leave the circuit closed . Maybe something that cyclically turns pin on an off for t mseconds? but this is not ideal as it would cause high wear on the system
Edited the post to be more precise. I hope now its clearer
thanks

thank you for your answers, but after playing for a while with your codes, and the ideas behind it, still cannot get it to work.
for instance, Chrisl with your first:
when potentiometer is at > X, It cuts the circuit which is good, but still doesn't go off until both potentiometer goes to < X and 3 seconds lapse , but this is not going to be possible to achieve anyways    because the value of the potentiometer is fixed on X
THis is what Id need-
if (PinState == HIGH)
after 3 seconds go low,
and not turn HIGH until at least these two conditions are met; analogRead has gone to < X and then analogRead > X ,and in that moment we are back at
PinState HIGH
is  even possible to achieve something like this?
the circuit is something like this:

simulate this circuit – Schematic created using CircuitLab
UPDATE:
I have using this code, which does almost what I want:
         if(analogRead(A0) > X) {
      unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {

   pinState = !pinState;
   digitalWrite(pin, pinState)
   // save the "current" time
   previousMillis = millis();
}}

When it gets to analogRead(A0)> X the problem of this code is that it switches the pin On and OFF continuosly,
but instead of switching it off/on after the interval time , I want it to be LOW always. Of course as long as time  is more than interval,and not get to a HIGH, until It has gone back to  analogRead(A0)> X and time is less than interval. And repeat the process... When time is more than interval it will go from where it was digitalWrite(pin, HIGH) to the new state digitalWrite(pin, LOW)
I made this table to be more clear
Table: analogRead(A0) > X?
1-yes -->now check if time in this state is less than interval = 3000:
1.1-YES, ---> digitalWrite(pin, HIGH)
   1.2- if no ( time is more than interval ) --->  digitalWrite(pin, LOW)
2-  No, analogRead(A0) < X . So -->  keep  digitalWrite(pin, LOW)
NEW UPDATE:
The state diagram for the new ranges should be something like this. I hope it is clear. I also removed the delays and replaced  (V < X ) for (V < Y )  , it works great. Thank you Edgar.
Z in the diagram being the variable for the new range, Z << X

LAST UPDATE:
Question Solved by Edgar Bonet

Its difficult to understand, what exactly the code should do. Please try to explain it more clear. Timed things can be best done using millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE

thanks, i tried to use it, but didnt work on what was trying to achieve, i edited the post hoping its more clear now.

So you want to physically turn the potentiometer with the motor to adjust the value to be lower than X? Then the motor must be controlled from the Arduino

maybe this way could work, everytime the system goes to a HIGH, it will remain there for 3 seconds , then it  makes circuit close or pinLOW. on the background however the variable A0 will keep reading but not affecting pin8 or the close circuit situation , and when the system goes more than X , it does the IF..else statement again, HIGH(3 seconds) stop the IF..ELSE,  reads A0 on the background and if more than X all repeats

it's a problem to control the motor directly because it depends on another parts of the circuit.

It is unclear, what you mean by "pinstate High". Please mske a clear table with everything that should happen. We need a clear and detailed description of the desired behavior

@chrisl I updated the original post, thank you very much for your time

The description you give for the desired behavior is very unclear and
hard to follow. I am going to rephrase what I think I understood in
terms of a finite state machine, which is the correct way of
describing this kind of systems. Please, review the description below,
as chances are I did not completely understand what you really want.
Let's say the system can be in any of these three states:

In the V_LOW state, the input voltage is below the threshold X and
the output is LOW. If the input raises above X, we set the output
to HIGH and transition to the V_HIGH state.
In the V_HIGH state, the input is above the threshold X and the
output is HIGH. If the input falls below X we go back to the
V_LOW state. If we remain in V_HIGH for three seconds, we switch
the output to LOW and go to the TIMEOUT state.
In the TIMEOUT state, the input is above the threshold, yet the
output is LOW. When the input falls below X we go to the V_LOW
state.

Below is a state graph for this machine. The states with a gray
background have the output LOW, whereas the state with a white
background has the output HIGH. Each possible transition is drawn as
an arrow, labeled by the condition that triggers the transition:

Is this the behavior you have in mind? If no, try to describe the
behavior you want in terms of a finite state machine, as I have done
here. If yes, then I suggest you follow chrisl's advice and implement
some hysteresis, by having different thresholds for going into and out
of V_LOW.
Anyhow, below is a translation of the FSM above in C++. It may not be
the most efficient way to write it, but I believe it is straightforward
enough to not require any additional explanation:
void update_output()
{
    static enum { V_LOW, V_HIGH, TIMEOUT } state;
    static uint32_t time_entered_v_high;
    int V = analogRead(A0);

    switch (state) {
    case V_LOW:
        if (V >= X) {
            digitalWrite(pin, HIGH);
            state = V_HIGH;
            time_entered_v_high = millis();
        }
        break;
    case V_HIGH:
        if (V < X) {
            digitalWrite(pin, LOW);
            state = V_LOW;
        } else if (millis() - time_entered_v_high >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V < X) {
            state = V_LOW;
        }
        break;
    }
}

Edit 1: Here is how to implement the hysteresis: you need to choose a
second, lower threshold, for going back to the state V_LOW. Let's call
it Y, which is smaller than X. Then, both on the diagram and the
code, replace every instance of “V < X” by “V < Y”. That's it. There is
absolutely nothing more to change.

Edit 2: Addressing the updated question. Now the output should go
HIGH when the input is out of a defined range. I'll add hysteresis
right away by using four thresholds
V0 < V1 < V2 < V3:

the input is in range if it is within
[V1, V2)
the input is out of range if it is not within
[V0, V3)
the ranges [V0, V1)
and [V2, V3) provide hysteresis.

Note that for consistency I like to have all the intervals closed on the
same side. I will also rename the states V_LOW and V_HIGH to
IN_RANGE and OUT_OF_RANGE respectively. Here is the updated code:
void update_output()
{
    static enum { IN_RANGE, OUT_OF_RANGE, TIMEOUT } state;
    static uint32_t time_exited_range;
    int V = analogRead(A0);

    switch (state) {
    case IN_RANGE:
        if (V < V0 || V >= V3) {
            digitalWrite(pin, HIGH);
            state = OUT_OF_RANGE;
            time_exited_range = millis();
        }
        break;
    case OUT_OF_RANGE:
        if (V >= V1 && V < V2) {
            digitalWrite(pin, LOW);
            state = IN_RANGE;
        } else if (millis() - time_exited_range >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V >= V1 && V < V2) {
            state = IN_RANGE;
        }
        break;
    }
}

Dear Edgar, I cannot thank you enough. That is exactly what I wanted, so thankful to you.  This problem has driven me crazy.   I just added a few delays at the end of each case and now it works perfectly without any flickering when switching states. As per your suggestion about the hysteresis .

Just a question, In case I wish to add a range, for example ( case V_LOW , case V_HIGH , case TIMEOUT ) going from ( ( (V >= X) , (V < X) , V < X)) to (( V >= X && V <= X ), ( V < X && V > Y ), ( V < X && V > Y ))  with Y being a minimum value, How that could work? . I tried adding the ranges, more if's , more cases, but neither would work. I also tried creating a function: e.g. bool inRange(int V, int minimum, int maximum) and replacing the range ( V >= X && V <= X ), ( V < X && V > Y ), ( V < X && V > Y ) ) with inRange(V, X, Y) functions but didn't work either .

@Fraunhofer: 1. Flickering is expected with this FSM whenever the input is noisy and close to the threshold. Hysteresis is the usual way to fix it. Delays are a stop gap solution that should better be avoided. 2. I couldn't understand your ranges thing. Could you draw your idea as a state diagram similar to the one I drew? You can then add it to the question.

I added the state diagram . Thank you very much

Thank you so much for all your help and explanations.  Now it's perfect.

Using different threshold values to switch states - a higher threshold to go HIGH and a lower value to go LOW - is called hysteresis. It makes a dead-zone between the two switching values that prevents jitter, or flickering the LED in this case, that would happen with a single switch-point and the analog value was very close to it.
To do that, you just need the second clause of your if block, now an else, to become an else if. So it would look like this (in pseudo-code):
if analog > 5,
   open the circuit;
else if analog < 4
   close the circuit;
// else must be >4 but <5, so do nothing.

for 3 seconds I make circuit close ... when the system goes more than X again, it does the IF..else
  statement again

Update:
So instead of hysteresis, you want close the circuit for a fixed amount of time? Then try something more like this:
if millis() - stop_time > 0 && analog > 5,
   save stop_time = (millis()+3000);
   open the circuit;
end

i did that but still not what I want.  what if, I keep the if statement, and for 3 seconds I make circuit close goes to LOW,  on the background however the variable A0 will keep reading but not affecting pin8 or the close circuit situation  , and when the system goes more than X again, it does the IF..else statement again

As I wrote in my comment, you can use millis() to solve your problem. First you should ditch the else statement, since you don't want the analog signal to turn the output of.
unsigned long timestamp=0;
unsigned long interval = 3000;

void loop(){
    if(millis() - timestamp > interval){
        digitalWrite(pin, LOW);
        if(analogRead(A0) > X){
            timestamp = millis();
            digitalWrite(pin, HIGH);
        }
    }
}

This code will check, if the time difference between now and the last activation is over 3s. If yes, it will first set the output to LOW. Then it checks, if the analog input is above X. If yes, the output will be set to HIGH and the timestamp will be set to the current time. On the next loop iteration the time difference will be lower than 3s (since we just set the timestamp to now). Thus nothing will change, keeping the output to HIGH for 3s. After that the output will be set to LOW and the code will be sensible to A0 again.
If you the output to just trigger once ever, you can use a simple flag.
unsigned long timestamp=0;
unsigned long interval = 3000;
byte flag=1;

void loop(){
    if(millis() - timestamp > interval){
        digitalWrite(pin, LOW);
        if(flag && analogRead(A0) > X){
            timestamp = millis();
            flag = 0;
            digitalWrite(pin, HIGH);
        }
    }
}

The flag is initially set to 1, which actives the analogRead() part. Then it is set to zero, which deactivates it.
Note that this code is relatively simply and comes with some caveats, that might or might not matter to you:

The code will not react to changes in the first 3 seconds after startup, since the timestamp is set to zero initially.
After about 50 days runtime, the millis() counter will overflow. So, if the inner if statement doesn't get triggered for this long, the code will again not be able to react for 3s (until the time has run 3s after the timestamp).


text:
Control 5V from ESP8266 Wemos D1 mini
I am making a simple heater with the help of ESP8266 wemos d1 mini. Heaters will use 12V DC power suply and ESP8266 must turn the heater on and off with the help of 5V DC relax. I want to avoid the use of anything else then ESP8366 and relay. I will need 2 such relays. So the question is, can i control 5V output on ESP8266 ? Or do i need to find a 3V DC relay and use that ? If the latter is the case, can i get some ebay link to 3V DC relay ?

is it a relay or a relay module with separate power input and signal input? some of the relay modules work wit a 3.3 V signal and you can power them from 5 V pin of Wemos

I was thinking of simply using standalone relay, basicly square thingy with tiny legs. I already have 2 of them that is why i am asking. I would like my project to be as simple as possible.

ditch the relay and use a logic-level mosfet, like the irlz44n; cheaper, longer-lasting, faster switching, higher current, lower resistance, smaller footprint, negligible power consumption. The only downside it that they don't galvinically isolate or handle AC, but you don't care about that.

Voltage is only part of what a relay uses.  Check the current requirements for the relay coil/input as well.
For example the common result for "3V relay arduino" will produce results for relay MODULEs that contain something akin to a SRD-03VDC-SL-C relay (labeled on the relay itself).  Spec for the RELAY (separate search by relay part no) yields a data sheet that says the coil resistance is 25 ohms for a 3V and would use 120 mA at that voltage (25 Ohm * .120A = 3).  Note if the same coil were run on 5V it would draw 200 mA (25 Ohm * .200A = 5V).
120 mA is bloody high to be coming from a logic pin which is why the MODULE has more than just the relay.  What the MODULE likely contains is an additional gate device that takes less current that then supplies the relay (with 120mA) from another port.
You might also be looking at a solid state relay that uses less input current but generally has some slight leakage when "Off"

Do NOT try to drive a simple relay from an MMU like a ESP8266, Arduino, or Pi. That would likely destroy the digital pin on the MMU, and might destroy the whole processor.
You want a "digital relay module" which has a driver circuit to control the relay, plus some form of isolation to protect the digital pins.
A relay like this would be perfect: https://www.amazon.com/Icstation-3-3V-Optocoupler-Trigger-Development/dp/B01300ZY5M
Note that those come in 1, 2, 4, and 8 channel modules. Such a relay needs an external power supply, and your ESP8266 may or may not be able to provide enough current for the relay from its voltage regulator. Check the current requirements on the relay and the output specs on the ESP8266's voltage regulator.


text:
difference between the nano and the nano every
So I wondered what the difference between the nano and the nano every is and why the nano every is so much cheaper than the nano.
I'm new to the microcontroller business and I would like to know what would be better for what situation.

The classic Nano has ATmega 328p MCU, same as Uno. The 328p is classic AVR ATmega as used in Arduinos from the start and before in many AVR MCU projects for over 20 years now. There is large knowlege base for this MCUs, many ready codes in form of libraries, snippets, tutorials.
The Nano Every and Uno WiFi Rev 2 use a modern version of the AVR based MCU a so called megaAVR_0-series, an ATmega4809. It uses the same AVR CPU architecture in core of the MCU so the compiler is the same as for 328p and co., but the MCU peripherals configuration is very different then in the classic ATmegas. So the old knowledge base about AVR MCU peripherals doesn't help here.
The lower price is not related to manufacturing costs. The possible reasons are:

better price by MCU manufacturer at introduction of the new MCU family to market
higher price of classic Nano because it is popular and together with classic Uno founds Arduino as company
getting the new chip to Arduino power users to build up the knowledge and code base for the new MCU

To mention some more differences of classic Nano and Nano Every: Nano uses a bootloader for sketch upload and an external USB chip for USB communication. Nano Every doesn't use a bootloader, it has an on board UPDI programmer in form of a small SAMD MCU which serves as USB adapter for serial communication too.


text:
Made a light controller for the holidays
I am a new the world of Arduino. I found on YouTube, how to build a light controller (https://www.youtube.com/watch?v=WvG9c84ApFA&t=39s). I follow every step but it doesn't work. Here are some pictures and a rough schematic. (I don't have a Arduino, it is a Egeloo mega 2560)enter link description here

Could you be more specific as to what doesn't work? Where do the orange and black dashed lines go to? What relay boards are you using? What power supply are you using for the relay boards? What code did you use? You might want to try testing with only a single board.

"It doesn't work" is a poor problem description, like asking "my car doesn't work. Whats wrong?". Please describe, what you did, what you expected and what happend instead. Also remove the images of your big wiring (we cannot see anything on that). Include a link to the used relay boards and your code.


text:
how to convert date to timestamp?
How should I convert date format(dd-mm-yyyy) to timestamp value . Can anyone suggest code how to convert and where to put code .

What do you mean by "timestamp value"? And how should we know where to put that resulting code? And what have you tried so far? Where do you use it with Arduino?

It is good for you?
struct tm tm;
time_t fecha;
if ( strptime(timestamp, "%Y-%m-%d %H:%M:%S", &tm) != NULL )
  fecha = mktime(&tm);
else

// Another thing

Welcome to Arduino.SE. To increase the benefit of all users looking at your post, you should add some explanation to your code. Consider a lot of the users here newbies. At least add some comments in your code.


text:
Mapping values from analog input giving unexpected values?
Mega 2560
I am reading in values from 3 pots then mapping them to values between 0 - 255
#define REDPIN   7
#define GREENPIN 8
#define BLUEPIN  9

int red_pot   = A0;  // analog pin used to connect the potentiometer
int green_pot = A1;
int blue_pot  = A3;

void setup() {

  pinMode(REDPIN,   OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN,  OUTPUT);

  Serial.begin(38400); //Debug port
  Serial.setTimeout(50);
}

void loop() {

  int red, green, blue;

  red   = analogRead(red_pot);
  green = analogRead(green_pot);
  blue  = analogRead(blue_pot);

  Serial.print(" r = ");
  Serial.print(red);

  Serial.print(" b = ");
  Serial.print(blue);

  Serial.print(" g = ");
  Serial.print(green);
  Serial.print("\n\n\n");

  // map values
  red   = map(red,   20, 650, 0, 255);
  green = map(green, 20, 570, 0, 255);
  blue  = map(blue,  20, 570, 0, 255);

  Serial.print("red map : ");
  Serial.print(red);

  Serial.print(" green map : ");
  Serial.print(green);

  Serial.print(" blue map : ");
  Serial.print(blue);
  Serial.print('\n\n\n');

  analogWrite(REDPIN,   red);
  analogWrite(GREENPIN, green);
  analogWrite(BLUEPIN,  blue);
}

red & green behave as expected but blue is not, from the serial monitor...
When blue is at its lowest value,

When blue is at its highest value,

I have changed blue's analog pin assignment but the same issue.
Any clues what's happening?
EDIT #1
I thought it might be some int sign error so I changed the map operation to,
blue  = map(abs(blue), 20, 670, 0, 255);

It made no difference.

In your print statement first r, b and g are printed but in your output it shows first the mapping. Are you sure the boxed values belong to each other?

yes if I leave the pots at a setting the values are stablish +/-5 on the input but pretty much the same values

Note that the Arduino function "map" is really this:
long map(long x, long in_min, long in_max, long out_min, long out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

...so, if you pass a "minimum from" value which is less than the actual value you are mapping from you will get a negative number given your "minimum out" is zero.
In several of your examples you have set the minimum to 20 but pass a value of 19.  If your program is intolerant of negative numbers (for instance, how would a negative number effect the PWM hardware), consider testing for lower than minimum and higher than maximum values before using the map function.

I realize this does not directly address your example code combined with your output.  However, it is obvious the output is not directly from the code as it is printed in reversed order.  Try running your code again and verifying the output.  If it indicates something different, please modify your question.  If it confirms your original post - then I'll have to think this over a bit more and revise my answer.

its definitely the output from the code, I have no idea why the serial monitor is outputting in the format as it is. Also can confirm that min(blue) == 22 but to make sure I lowered the range from 20 to 10 but still the same ouput.

@DrBwts - The constrain() function can be used to ensure the proper range of "numbers" is passed to the map() function: https://www.arduino.cc/reference/en/language/functions/math/constrain/

But in the code you print r, b, g before you print red map, green map then blue map.  In addtion there should be 3 lines in-between.  So the order you print values out in your question makes the reader think the r, b & g values relate to the next set of red map, green  map & blue map values.  Not previous red map, green map & blue map values as you are indicating with your red and yellow boxes.   I would try to lower the "minimum map from" value to zero just to make sure. If the problem persists, I then would simplify the code and only process the "blue" POT's input.

weirdly I amended the code to get a sensible serial output literally changing "\n\n\n" to '\n' & now its working fine

That is good news!  I will have to check my Arduino setup to be sure, but "\n" is normally just a carriage return while "\r" is a line feed.  Combined they give you both a return to the beginning of a line and advance to the next line.  But Unix (aka Linus, Android, Solaris, ect) and Windows pulls a fast one on us.  In Unix the "\r" is assumed and not needed while in Windows the "\n" is assumed and not needed.   Confused?  Most everyone was.  So, over the ensuing decades, much software was written to automatically (badly) deal w/this.  So may be true with the Arduino Serial Monitor.


text:
Are there any alternatives to Tinkercad Circuits that is PC application based instead of web app based?
I have been using Tinkercad's Circuits web application to create my Arduino circuits and apply my Arduino code (c++) for testing.
Despite the amazing product they have and the fact it's free, I find myself very disappointed at times.  Don't get me wrong, Tinkercad has a bunch of great products that I use all the time (like "3d Designs").  I just feel like "Circuits" needs work or maybe even a different dirrection.
I have been dealing with some of the following issues...

An extremely slow interface creating my circuit:
I have seen it do a bunch of random things that could use some TLC in the interface.  Sometimes objects get stuck and you have to disconnect them from everything before you can move them.  Sometimes using a breadboard, objects that seem connected to a pinhole does not make a connection and need to be connected to the breadboard using a wire.  There are a bunch of little quarks I see.  None are a show stopper and I can work around them but the slow interface makes me hate dealing with a web app.  It makes me really want a PC app instead.
The lack of support updating the Arduino compiler:
It's a very old version and they are not in a hurry to upgrade it.  I have contacted support a bunch about issues with the compiler not compiling code that works perfectly fine in the Arduino IDE.  Classes need to be defined in a specific way, enums need to be defined in an old way that makes the source look ugly etc.  Also, I have let them know when debugging it's about impossible to find out where your bug is because it does not tell you a line number it had a problem on.  It tries to highlight the line with little success in my tests.  I have suggested to them that maybe they could introduce a new option to choose the compiler version to use for each project this way old designs do not break etc.  I didn't get any feedback on the feedback I submitted.  So I guess that is a no go.
The simulation time:
This is the worst offender by far!  This is the main reason I want to look for different software to replace Tinkercad Circuits.  When simulating code on my circuit design the simulation runs in milliseconds (NOT real-time).  I have my code set to do something in 15 seconds.  Seems like it will happen in no time...  NOPE!  I have to wait about 15 minutes to see the results!!

So back to my original question...  Is there a PC application out there that does the same thing as Tinkercad Circuits?  I want to be able to design an Andrino circuit and then test code with it.

I've not had the same issues, but i haven't used it as much as it sounds like you have. Emulation will always be relatively slow, so make sure you're using as beefy a computer as possible (no tablets/laptops) to run it. Emulation will also slow as the code size increases, perhaps even exponentially. I have seen it get better since launch, so give it time. Meanwhile, I would try to isolate and test smaller pieces, mocking up the "non-moving parts" to avoid overhead. I've not seen anything better...

Don't use simulation. Use a real Arduino and the IDE. Simulation often gets it wrong and you find that things that "worked" in the simulation don't in real life. Skip simulation altogether and save yourself the headache of things not working later.

@Majenko that should almost be an answer...  I totally agree!  After some testing yesterday on some source code, Tinkercad would run something just as I expected and when it was flashed to my ATtiny85 it was like NOPE!  bool resetButtonIsPressed = (digitalRead(PB_BUTTON) == HIGH ? true : false); works fine in c++ (also TinkerCad).  But the only way to get it to work on the ATtiny85 is to use bool resetButtonIsPressed; if (digitalRead(PB_BUTTON) == LOW) { resetButtonIsPressed = false; } else { resetButtonIsPressed = true; }.

I work with the wokwi Arduino simulator

It is faster
It uses the latest Arduino IDE for compilation
It almost runs in real-time. For example, your job of 15 seconds might get executed at about the 17th or 20th second.

Please give it a try. here are some references

Links: https://wokwi.com and https://wokwi.com/arduino/libraries

Thanks for the suggestion!

I'll try to find such PC app, but I can't find anyone. When I give up to find such app, I wrote my own arduino emulator via qt. My app is include arduino app and compile them as part of the qt app. Thank's to #ifdef macros i'm change the arduino.h . My emulator is not let you add scheme elements, but add you advantage to watch pin states and sets values to them. You can correct your project and emulate your own functions and algorithms. There it is https://github.com/ravenclawprog/arduino_mobil


text:
Error when compiling code NODE MCU ESP8266-12E module in Arduino ide
Here is my sketch:

#include<ESP8266WiFi.h>

char* ssid = "xxxxxxxx";
char* pass = "xxxxxxx";

void setup() {
 WiFi.begin(ssid,pass);
 Serial.begin(9600);
 while(WiFi.status()!=WL_CONNECTED)
 {
  Serial.print(".");
  delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
}

Here is the error:
Traceback (most recent call last):   File "C:\Users\ASUS\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2/tools/upload.py", line 25, in <module>
    esptool.main(fakeargs)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 2653, in main
    esp.connect(args.before)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 460, in connect
    last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 440, in _connect_attempt
    self.sync()   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 379, in sync
    timeout=SYNC_TIMEOUT)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 322, in command
    self.write(pkt)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 285, in write
    self._port.write(buf)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/pyserial\serial\serialwin32.py", line 323, in write
    raise writeTimeoutError serial.serialutil.SerialTimeoutException: Write timeout the selected serial port
serial.serialutil.SerialTimeoutException: Write timeout  does not
exist or your board is not connected

does the code "verify"?

This looks more like an error while uploading than on compilation to me. Have you selected the correct board settings?

The section
void loop() {
}

Is missing in the code, add it and recompile and.....