text:
Issue connecting heartbeat & temperature sensor on arduino uno but working individually
So the code is working individually for temperature sensor and for heartbeat sensor but  when i combine it together it shows wrong values
for the temperature sensor
I'm using lm35 temperature sensor and powering by USB
#include <LiquidCrystal.h>

const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

int pulsePin = A0;

int blinkPin = 5;                // pin to blink led at each beat

// Volatile Variables, used in the interrupt service routine!
volatile int BPM ;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P = 512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

const int sensor = A5;
int tempc ;
float vout;

void setup()
{
  vout =analogRead(sensor);
  pinMode(sensor,INPUT);
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  Serial.begin(9600);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                  // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
                                    //   analogReference(EXTERNAL);
 lcd.begin(16, 4);
 lcd.clear();
}

//  Where the Magic Happens
void loop()
{

lcd.setCursor(0,0);
lcd.print(" T in c = ");
lcd.print(tempc);
lcd.setCursor(0,1);

delay(100);
   serialOutput();

  if (QS == true) // A Heartbeat Was Found
    {
      // BPM and IBI have been Determined
      // Quantified Self "QS" true when arduino finds a heartbeat
      serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
      QS = false; // reset the Quantified Self flag for next time
      tempc=(vout*500)/1023;

    }

  delay(20); //  take a break
}

void interruptSetup()
{
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

void serialOutput()
{   // Decide How To Output Serial.
 if (serialVisual == true)
  {
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
  }
 else
  {
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
   }
}

void serialOutputWhenBeatHappens()
{
 if (serialVisual == true) //  Code to Make the Serial Monitor Visualizer Work
   {

     int din ;
      din = analogRead(4);

     Serial.print(BPM);
     Serial.print(", ");
     Serial.print(tempc);
     Serial.print(", ");
     Serial.print(din);
     Serial.print(", ");

     Serial.println();
     lcd.setCursor(0,2);
     lcd.print("Heart-Beat Found ");
     lcd.setCursor(6,3);
     lcd.print(BPM);
     delay(100);
     lcd.clear();
   }
 else
   {
     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
   }
}

void arduinoSerialMonitorVisual(char symbol, int data )
{
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
  const int sensorMax = 1024;    // sensor maximum, discovered through experiment
  int sensorReading = data; // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
  // do something different depending on the
  // range value:
}

void sendDataToSerial(char symbol, int data )
{
   Serial.print(symbol);
   Serial.println(data);
}

ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124
{
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise
                                              //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI
    {
      if (Signal < T) // T is the trough
      {
        T = Signal; // keep track of lowest point in pulse wave
      }
    }

  if(Signal > thresh && Signal > P)
    {          // thresh condition helps avoid noise
      P = Signal;                             // P is the peak
    }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250)
  {                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )
      {
        Pulse = true;                               // set the Pulse flag when we think there is a pulse
        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat)
        {                        // if this is the second beat, if secondBeat == TRUE
          secondBeat = false;                  // clear secondBeat flag
          for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup
          {
            rate[i] = IBI;
          }
        }

        if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE
        {
          firstBeat = false;                   // clear firstBeat flag
          secondBeat = true;                   // set the second beat flag
          sei();                               // enable interrupts again
          return;                              // IBI value is unreliable so discard it
        }
      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++)
        {                // shift data in the rate array
          rate[i] = rate[i+1];                  // and drop the oldest IBI value
          runningTotal += rate[i];              // add up the 9 oldest IBI values
        }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true)
    {   // when the values are going down, the beat is over
      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
      Pulse = false;                         // reset the Pulse flag so we can do it again
      amp = P - T;                           // get amplitude of the pulse wave
      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
      P = thresh;                            // reset these for next time
      T = thresh;
    }

  if (N > 2500)
    {                           // if 2.5 seconds go by without a beat
      thresh = 512;                          // set thresh default
      P = 512;                               // set P default
      T = 512;                               // set T default
      lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
      firstBeat = true;                      // set these to avoid noise
      secondBeat = false;                    // when we get the heartbeat back
    }
  sei();
                                 // enable interrupts when youre done!
}// end isr

Code seems to lack a repeating update of tempc via
vout =analogRead(sensor);

An alternative might be changing the line for setting tempc to be
tempc=(int) (analogRead(sensor) * 500.0f/1023.0f);

thanks for your answer, I'm still a newbie can you please explain more?

Add that vout = line between QS = false; and tempc = and let me know if issue still persists.  Basically you have to update vout before you calculate tempc from it.  analogRead is a one shot read on the pin.

Thanks, I'll try and keep you updated

sorry for the late response,I've tried your suggestions but unfortunately I didn't get any result.I think the problem is due to the interrupts()  or timer2 instructions because when I add cli() (disable interrupt) before vout=analogRead(sensor); the temperature give me the right value  but the pulse sensor stop working . thats what I'm getting currently https://www.youtube.com/watch?v=dBPKmYd08U8 thanks

Why do you compute tempc only after you print out the value in serialOutputWhenBeatHappens`? You also forgot to read the temperature continuously.
Here is how I would do it:
void loop()
{
  // read the sensor before it is printed on the LCD
  vout  = analogRead( sensor );

  // here I'm not sure what you are computing
  // you map the sensor voltage to a range from 0°C to 500°C
  // do you measure the heartbeat and temperature of a dragon? ;-)
  // this formula is the same as yours
  tempc = ( vout / 1023.0 ) * 500.0;

  // I would also clear the LCD before I write to it
  lcd.clear();

  lcd.setCursor( 0, 0 );
  lcd.print( "T in c = " );
  lcd.print( tempc );
  lcd.setCursor( 0,1 );

  // There is no need to slow down the loop here.
  // let it run ...
  // delay(100);

  serialOutput();

  // A Heartbeat Was Found
  if (QS == true)
  {
     // BPM and IBI have been Determined
     // Quantified Self "QS" true when arduino finds a heartbeat
     // A Beat Happened, Output that to serial.
     serialOutputWhenBeatHappens();

     // reset the Quantified Self flag for next time
     QS = false;
  }

  // take a break (Why?)
  // delay(20);
}

If the provided source is cut down to the lines that have to do with the temperature, it is just this. If you try this sketch it should behave equally "wrong":
const int sensor = A5;
int tempc;
float vout;

void setup()
{
    vout = analogRead(sensor);
    pinMode(sensor, INPUT);
}

void loop()
{
    lcd.print(tempc);
    tempc = (vout * 500) / 1023;
}

In loop() the value of tempc is printed before it is re-calculated from vout.
But vout is written to just one time in setup().
So the "wrong" values you are talking about are always the same value which was measured at start-up time. (You did not mention what is wrong.)

Note: Like documented in the Arduino's library reference, there is no need to set a pin to INPUT mode because it's the default.

I read your comment on @Abel's answer and even watched your video. Since it's not clear what you did I can't say anything why you have jumping values now. (Please write some prose and show the new code in your question the next time.)
If we apply his advice the source will look like this. I removed the setting of the pin mode (see above) and made the sequence of instructions in loop() more logical.
const int sensor = A5;
int tempc;
float vout;

void setup()
{
}

void loop()
{
    vout = analogRead(sensor);
    tempc = (vout * 500) / 1023;
    lcd.print(tempc);
}

This sketch will show the current temperature tracking the actual value. If not you have another problem independent of the interrupt and the heartbeat sensor.

Additional notes:

analogRead() returns an int. You assign it to a float so here is an implicit conversion.
This float is fine because you do the mapping "by hand." If you'd use map() it could be an int.
The result of the mapping expression is of type float and you assign it to an int. Here is another implicit conversion which removes the fractional part. This is OK because of the accuracy of the measurement.

Now to your assumption that the interrupts disturb the measurement of the temperature.
From the source I don't see any reason. So you might like to proceed like this:

Comment everything that has to do with the heartbeat acquisition, including the timer interrupt. You can do this with /* … */ or #if 0-#endif-pairs. The former can't be "stacked" and the latter need their own lines.
Check whether the temperature is tracked OK.

If yes, proceed.
If no, your temperature circuitry is faulty in some way. A schematic and a photo (edit your question for this) could be helpful for us. Don't proceed until this is solved.

The timer and its interrupt service routine is actived again but will execute nothing.
Check whether the temperature is OK.

If yes, proceed.
If no, I'm out of ideas for the moment.

Re-enable the heartbeat acquisition.
Check whether the temperature is OK.

If yes, proceed.
If no, I'm out of ideas for the moment.

Problem solved.


text:
Two adruino are connected to the raspberry via usb, but one is reconnected during processing code is running
I try to solve this a month..but still problem...

I want to make below led-matrix spectrum.
Thumbnail image
https://youtu.be/X35HbE7k3DA

※Environment
Device UML
One Raspberry pi 3 : 2019-09-26-raspbian-buster-full
Two arduino uno with each matrix shield and 16x32 matrix
One usb Microphone

If i attached two arduino Uno to raspberry pi and try to run Processing code(.pde) , one of them is reattached to raspberry pi.
The other one is still working well..
If i connect these arduinos to windows and running pde file...It works well.
(two matrix are showing spectrum well)
What should I do???
Is this code problem? or raspberry problem?
I really need to solve this...

I already tried....

Reloaded ino code to both arduino Uno.
(both arduino has same code)
Changed boardrate number 115200 -> other number
(but it must be 115200 to running well)
Add arduino to udev rules like below link.
https://www.intorobotics.com/how-to-setup-raspberry-pi-to-identify-two-arduino-devices/
Cross exchange each matrix and arduino.
Try to use arduino mega with same code.

Here is the arduino code(.ino) and Processing Code(.pde)
https://github.com/snskreationz/Real-Time-RGB-Matrix-Spectrum-Analyzer
arduino Uno Matrix Pin number
#define CLK 8
#define LAT 10
#define OE  9
#define A   A0
#define B   A1
#define C   A2

Main processing code
import ddf.minim.analysis.*;
import ddf.minim.*;
import processing.serial.*;

Serial port1;
Serial port2;

Minim minim;
AudioInput in;
FFT fft;

int buffer_size = 4096;
float sample_rate = 200000;

int freq_width = 250; // <-O-> set the frequency range for each band over 400hz. larger bands will have less intensity per band. smaller bands would result in the overall range being limited

//arrays to hold the 64 bands' data
int[] freq_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
float[] freq_height = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

void setup()
{
  size(200, 200);

  minim = new Minim(this);
  port1 = new Serial(this, "COM8" , 115200); // <-O-> set baud rate and port for first RGB matrix
// Here can be changed to "/dev/ttyACM0" via Raspberry pi
  //port2 = new Serial(this, "COM5" , 115200); // <-O-> set baud rate and port for second RGB matrix
// Here can be changed to "/dev/ttyACM1" via Raspberry pi

  in = minim.getLineIn(Minim.MONO,buffer_size,sample_rate);

  // create an FFT object that has a time-domain buffer
  // the same size as line-in's sample buffer
  fft = new FFT(in.bufferSize(), in.sampleRate());
  // Tapered window important for log-domain display
  fft.window(FFT.HAMMING);
}

Here are the kernel logs for Raspebrry pi
Nov 11 00:17:27 raspberrypi kernel: [ 5974.165722] Under-voltage detected! (0x00050005)
Nov 11 00:17:27 raspberrypi kernel: [ 5974.665649] usb 1-1.3: new full-speed USB device number 9 using dwc_otg
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809539] usb 1-1.3: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809556] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809566] usb 1-1.3: Manufacturer: Arduino (www.arduino.cc)
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809576] usb 1-1.3: SerialNumber: 55639313932351518040
Nov 11 00:17:27 raspberrypi kernel: [ 5974.810729] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device ---------------------> connected first arduino
Nov 11 00:17:28 raspberrypi kernel: [ 5975.685661] usb 1-1.2: new full-speed USB device number 10 using dwc_otg
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829541] usb 1-1.2: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829558] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829569] usb 1-1.2: Manufacturer: Arduino (www.arduino.cc)
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829578] usb 1-1.2: SerialNumber: 8563431373935121D0B2
Nov 11 00:17:28 raspberrypi kernel: [ 5975.830752] cdc_acm 1-1.2:1.0: ttyACM1: USB ACM device --------------------->  connected second arduino
Nov 11 00:17:33 raspberrypi kernel: [ 5980.405877] Voltage normalised (0x00000000) --------------------->  almost at this time starting processing code
Nov 11 00:17:37 raspberrypi kernel: [ 5985.121964] usb 1-1.2: USB disconnect, device number 10
Nov 11 00:17:37 raspberrypi kernel: [ 5985.122315] cdc_acm 1-1.2:1.0: failed to set dtr/rts
Nov 11 00:17:38 raspberrypi kernel: [ 5985.425669] usb 1-1.2: new full-speed USB device number 11 using dwc_otg
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569812] usb 1-1.2: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569831] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569843] usb 1-1.2: Manufacturer: Arduino (www.arduino.cc)
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569853] usb 1-1.2: SerialNumber: 8563431373935121D0B2
Nov 11 00:17:38 raspberrypi kernel: [ 5985.571468] cdc_acm 1-1.2:1.0: ttyACM2: USB ACM device --------------------->  reattached second arduino automatically
Nov 11 00:17:39 raspberrypi kernel: [ 5986.645829] Under-voltage detected! (0x00050005)
Nov 11 00:17:43 raspberrypi kernel: [ 5990.805775] Voltage normalised (0x00000000)

I really want to run both arduino spectrum via raspberry pi.

Under-voltage detected! I think it says it all. Rapsberry have many times problem to feed itself from "common power source", not mentioning attached devices. Especially, if you power your LEDs from it too.
You need better power source for Rapsberry (and maybe even power it from pins, but then you need read much more to not damage it) and other powersource for those LEDs.
On normal PC the Power Source is way more powerfull and can feed a LOT of power to each USB.

Thank you for answer my question!
Your right... it's under-voltage problem..  BOD (brown out detector)...
I given more power to arduino and it works fine:)

source: Stack Exchange

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

sort: votes


text:
Temperature and Humidity Sensor TinyShield (No device found on com5)
Hi i have recently started working on a Temperature and Humidity Sensor TinyShield (ASD2511-R-T) and faced the issue as shown in the image below: No device found on com5.

I have followed the tutorial as shown in the TinyShield webpage and worked through the steps. 1) Installed the Arduino IDE, 2) Installed the Si7021 Arduino Library, 3)Download the .zip file of the example program and open it in the Arduino IDE.
This is the following example code provided by the tutorial.
/*
  TinyCircuits Si7020 Temperature and Humidity Sensor TinyShield Example Sketch

  This demo shows the bare minimum to read temperature and humidity data from
  the Si7020 sensor using the Si7020 library written by Marcus Sorensen.

  This example is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  Written 20 March 2016
  By Ben Rose
  Modified 07 January 2019
  By Hunter Hykes

  https://TinyCircuits.com
*/

#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
}

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  Serial.print(celcius);
  Serial.print(" deg Celsius\t");
  Serial.print(relativeHumidity);
  Serial.println("% relative humidity");

  delay(500);
}

However, when I proceed to upload the program, the following error had occurred. This is the first time i am working on a TinyShield product.
Any help is appreciated! Thanks!
Do let me know if i need to provide any further information.
The options for COM 5 the only one avaliable.

why did you choose COM5 as the serial port?

The error indicate that your Arduino is NOT connected to COM5 !

Hi, that was the only options available in the port option when i connected it. I have added the screenshot in the post.

The below was the issue, i was using the wrong broad and processor.
Thanks for the help!

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


text:
I am trying to combine a button's coding and servo's coding. But it is still cannot be verified. What have I done wrong?
include
Servo myservo;
void setup(){
  myservo.attach(8);
   pinMode(buttonPin, INPUT);
}
void loop()
{
  myservo.write(0);
  delay(3);
  myservo.write(90);
  delay(3);
}
 const int inPin=8;
 const int outPin = 9;
 int currentState = LOW;
  currentState = digitalRead (inPin);
  if (currentState== HIGH)
    digitalWrite (outPin,HIGH);
   else
    digitalWrite (outPin,HIGH);
   delay(10);
 }

Do NOT use two loop() and setup() function.
You can refer to a similar combination between Servo Motor code and Potentiometer code here.

Thanks for the wonderful website


text:
Unable to use DHT11 with NodeMCU(esp8266)
I am trying to use a NodeMCU like an arduino,trying to read Temperature and Humidity using a DHT11,but when ever I check the serial monitor the it outputs : nan, Can anyone help me find the problem.(The data pin is D4 on NodeMCU)
    #include "DHT.h"

DHT dht2(2,DHT11);

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

    }

void loop()
{

    Serial.println("Temperature: ");
    Serial.println((dht2.readTemperature( )));
    Serial.println("Humidity");
    Serial.println((dht2.readHumidity( )));
    delay(5000);

}

use D1 or D2. D4 has a pullup resistor https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

Thanks manhh, you rock!!

The esp8266 boot configuration pins 0, 2, 15 require a pull-up/pull-down  to ensure the required state at boot. The board (NodeMCU in this case) has pull-up resistor on io0 and io2 and a pull-down resistor on pin 15. The MCU pins io0, io2 and io16 are the NodeMCU pin D3, D4 and D8. You can use this pins in the sketch, but only to attach devices which are not in conflict with the required boot state and are not disturbed by the pull-up/pull-down.
NodeMCU and "Wemos D1 R2 and Mini" esp8266 pins and io overview

Serial
RX io1 RX0
TX io3 TX0

boot config pins with pullup or pulldown on board
D3 io0 PULLUP (LOW for boot to flashing mode)
D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)
D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave)

untroubled GPIOs with optional function for I2C or SPI bus:
D1 io5 default pin for I2C SCL
D2 io4 default pin for I2C SCA
D5 io14 SPI CLK
D6 io12 SPI MISO
D7 io13 SPI MOSI

RTC pin for timed deep sleep wake-up (if connected to reset pin)
D0 io16 - optional internal pulldown, internal pullup not available

not useable: Sx pins io 6 to io 11 connect QIO SPI flash memory (in DIO flash mode the 2 QIO pins can be used as gpio) (in a very special setup the SPI bus can be used with other SPI device)
note: most digital IO start as INPUT_PULLUP


text:
Is there a way to read real-time port selection on Arduino IDE when using third-party toolchain and uploading program?
I am using a third-party program to build the binary file and upload it under Arduino IDE's GUI, meaning I am not using the built-in avr-gcc nor avrdude for building and uploading. As there is a on-board DAP chip, uploading binary file is done by copy&paste the binary file into the flash memory recognized as a removable storage by the OS.
However, this make reading user's current port selection very difficult because the IDE is written in Java, but the thrid-party program I am using is in C++.
Knowing which port the user has currently selected is very important to me, as sometimes I need to program multiple boards at the same time and monitor their received data on the serial port.
If someone can point me into the right direction or link me to the previously-solved similar question , it will be much appreciated!
PS: I am working under Ubuntu&Windows10 OS and using latest Arduino IDE.

I don't understand. What port does the user select if the upload target is the drive?

Hi Juraj, it doesn't matter which port the user select, the uploading program will always simply copy & paste the binary into the drive whose path already specified in the source code of the uploading program, this differs from arduino who uses serial port to upload binary instead of DAP(Debug Access Port).

yes, and then what is the question?

Hi Juraj, its ok I ve found the solution, thx :)

After someone from Github gave me a link, I think I ve found the way to read the real-time port selection even using third party uploading program.
The key is command line argument in the "Platform.txt" file located under "arduino15" folder. If you have the same issue as mine, try look up this link, where you will find loads of useful information:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification
PS: rmb, after you change the command lines in the txt file, always close and restart your arduino IDE before those changes you made take effect.

Please be a bit more specific, so that future users can learn more from your answer, and also because links might die somewhere in the future.

thanks for the reminder, but I think my case is kinda rare so not many will run into the same problem as ours unless their dev board uses DAP chip for uploading as well.

anyway, this key is to get the serial port through command lines arguments written in "Platform.txt" (you can find it in your C drive).


text:
Compute the size of an array that was passed as a parameter to a function
When passing an array to a function, you usually pass the length of the array along with it. You can compute the size of the array with sizeof(myArray)/sizeof(myArray[0]), which works just fine.
However, if you try to do this within the function that you pass the array to, this doesn't return the length of the array - eg. if it is an int array, it returns 1, if it is a double array, it returns 0.
Why is that so and is there any way to compute the size of an array that was passed as a parameter?

If you don't use it often (every different type/size makes new instantiation od f function), then you can use templates like: template <typename T, size_t N> void f(T(& myArray)[N])

You can't. You are passing a pointer to the array, and sizeof will give you the size of that pointer (2 on an 8-bit Arduino).
Instead the normal way is to pass the size of the array as a parameter to your function.
myFunction(myArray, sizeof(myArray) / sizeof(myArray[0]));


text:
How do change my Arduino Uno from an unknown device to a port?
I have an Arduino Uno that I have connected to a servo motor. I used an adapter to plug it into my computer and my computer said "Setting up a device, this will only take a minute". When it was done setting up, I downloaded Arduino IDE and I wrote a code. When I clicked "Upload", I was told that a serial port was not selected. I went to Tools>Port>Arduino Uno. The program then uploaded, I unplugged it and began its process. After I uploaded, I wanted to make a change to my code so I plugged it back in and I heard the Windows beepboopbeep sound. I edited the code and tried to upload again and it said that a serial port was not selected. I went to Device Manager and found it under another tab, something like Amtek USB ports. It was labeled as "Unknown Device". I tried to select it but it told me that it couldn't update driver. I looked it up and people said to unplug and replug in another USB port. I tried that 7 times yet it was still "Unknown Device". Am I doing something wrong?
Edit: I am using a HP AMD Radeon 7 Processor laptop running Windows 10 and my Arduino is not a copy, it is authentic.

All USB devices have 1) a manufacture ID & 2) a device ID.  A computer read these and picks a driver to load in.  On a Linux computer (and probably on a Mac) the command "lsusb" will return these ID for all connected devices.  You did not say what type of computer you are using.    Also, you did not say if your Arduino Uno board is  authentic or a copy.   This information may help others find an answer.  Although this is sometimes a tricky subject.  Especially when Windows gets involved.

Does the arduino IDE show a different COM port to select. The time it worked you said you had selected  Tools>Port>Arduino Uno. This is new to me. I would expect a port like COM13 or COM15 or such. Does Windows 10 name their serial ports other than Win7 for example?  What programmer did you choose?  Did you select the right board? (UNO)

I used an adapter to plug it into my computer What kind of adapter? The Ardino Uno just plugs directly into your computer with a USB cable. There should be no "adapter" needed.

@Majenko I used a USB type B to A adapter.

@PeterPaulKiefer i do not remember the COM, the Arduino IDE software that I have open says it is COM3 but won't let me select the port anymore. It automatically chose AVRISP mkll as my programmer.

it started working now that I found a better USB cable, only problem is that now when I upload the code, it does not run

Then,  if the upload ends with no error messages, the code itself may have errors. Do you understand, how the code works? If you copied it from the internet, try to understand, what the code does. Hopefully there is a little explanation coming with it. If you are complete new to programming, look at the basic sides (e.g. https://www.arduino.cc/reference/en/ ). -- Perhaps you'll find the error. If not, it's a good opportunity to ask here a new question. People can help you the most, if you add your code, explain what you've done and say what you expect and what not works as you expected it.


text:
Error: invalid application of 'sizeof' to incomplete type 'int []' when trying to compute the size of an array in a library
I have created a library that contains an array. This is the .h file:
class Lib {
  public:
    static int arr[];
};

And this is the .cpp file:
#include "Lib.h"

int Lib::arr[] = {0, 1, 2, 3};

When trying to compute the size of this array from within the library, it works just fine. When trying to do this from a sketch, I get the error mentioned in the title. This is the sketch I'm using:
#include <Lib.h>

void setup() {
  sizeof(Lib::arr);
}

void loop() {}

What is the problem here?

Maybe you can try to add a constant integer inside your library containing the sizeof of the array and in your sketch use that integer.

@LukasFin I added an answer.

It seems as if the static initializer has not been executed when the sketch is started.  That seems strange to me. Did you tried to access the first array element (for example) from within the sketch? I would also use some uncommon values to initialize the array e.g. 53, 33, 4, 12 to be sure you do not access the 0 initialized memory at Lib:arr[0].  If you find the correct value, then at least the initialization  works. But then, I have no better explanation. Btw: the correct C++ initialization aof static vars is int Lib::arr[4] = {0, 1, 2, 3};. Perhaps that matters.

Sorry, my former comment is nonsense. As this is a compiler error and 'sizeof' is a compiler function that works on declared types, the error is of cause explainable. In the header file the array is not initialized and its size is not specified. The header file is the only thing the compiler knows when compiling the sketch. The cpp file is compiled to an object file in another step. The object file is linked after the compile runs.  So all things that happen in the cpp File are unknown to the compiler when it compiles the sketch. If you declare the array with a size it will work. I'm so ...

The reason is that in your sketch you import only the header file (which is good). However, there it is an array (int[]), not the initialized array.
For that you would need to include the cpp but that is bad practice (if even possible).
So instead, create a new (constant) variable, and assign it.
(more or less pseudo code, due to lack of a compiler):
Lib.h:
class Lib {
  public:
    static int arr[];
    static int arr_length;
};

Lib.cpp:
#include "Lib.h"

int Lib::arr[] = {0, 1, 2, 3};
int Lib::arr_length = sizeof(Lib::arr);

Sketch:
#include <Lib.h>

void setup() {
  Lib::arr_length;
}

void loop() {}

See also the comment of LukasFun below. It is also possible to set the size of the array in the header file.
My advice though is keeping all assignments in the implementation (cpp) file. The header file is for defining items, the implementation file for initializing/assigning. But it works too, to initialize items in the header file.

I just tried setting the size of the array directly in the .h file. If I do this, the sketch compiles without any errors. Maybe you could add this to your answer.

@LukasFun True, I added the comment, however, it's still better to do initializations in the implementation file.


text:
Creating an array with the length coming from a library
When creating an array like in the sketch
#include <Lib.h>

int myArray[Lib::len];

void setup() {}

void loop() {}

the variable len must be an integer constant that is known at compile time. Like shown in the sektch, I want to put the length of the array into a library and get it from there. The problem is that for this to work, you have to initialize the constant already in the .h file, which is against proper library standards. This is how you would do this (.h file of the library):
class Lib {
  public:
    static const int len = 4;
};

The .cpp file doesn't even have to contain anything in this case. The proper way to do things in a library would be like this though:
The .h file:
class Lib {
  public:
    static const int len;
};

The .cpp file:
#include "Lib.h"

const int Lib::num = 4;

But if done like this, len doen't have a value at compile time since the sketch only includes the .h file and not the .cpp file.
Is there any way to intitialize an array in a sketch with its length coming from a library while maintaining proper library design?

Header files are there to define stuff that is used by the library functions as well as by the consumer code. So if both need access to the length variable, why should it be improper library design to define the length in the header file? For example all information of MCU registers  and their name to number mapping are declared in headers.

There is absolutely nothing wrong with putting it in the header.

§9.4.2/4 If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Since you're just using it as a simple constant "integral" value there is nothing wrong with putting it in the header.

So the answer is "Just do it this way, even though the initialization is not in the .cpp file as with everything else"? Or is there any other way?

The answer is "Just do it this way since this is the right way to do it as you have a static const integral type"

@LukasFun You can define a constant in the header and use this to initialize the static member in the cpp File. You can also use this constant in the sketch at compile time. But that would be a worse solution (IMHO at least).


text:
Is the LGT8F328P legal?
Since some months, everyone can buy a board with this IC.
It is compatible with the ATMega328 and has some features like 12bit ADC (instead of 10 bit), DAC, unique ID and also 32MHz.
But I can't find it in the "normal" shops. Also on the LCSC it is not available. Only in this shop:
https://www.electrodragon.com/product/5pcs-logicgreen-lgt8f328p/
For 0.68$ compared to the 2$ for the atmega326P-AU of the other electronic parts shops (it is cheaper than the cheapest attiny with ADC!)
So the question. Is this chip just a clone for private use or can it be used as official alternative to the more expensive and original ATMega328?

My understanding is that it is legal since it is just engineered to be (somewhat) compatible with ATmega328p but their difference are substantial if you deep dive.
It has a RISC core and its core instructions are quite different from ATmega328p. Most multi-cycle instructions are replaced by single-cycle instructions or less cycle instructions. And the core runs at 32Mhz from 1.8V-5.5V.
The peripheral registers are largely (backward) compatible with ATmega328. However, LGT has more or advanced peripherals.

2 16-bit timers, with capture and compare output
ADC has 12 bits instead of 10.
DAC, so you don't need PWM to emulate DAC.
9 high current PWM. 3 complementary PWM with dead band control.
PGA 1x-32x differential amp. Which saved me 1 op-amp.
16 bit computing accelerator/Co-processor.
High and adjustable current GPIO (so you can light up LEDs without current limiting resistors).
These peripherals provide lots of additional registers for control and status reporting that don't exist on ATmega.

Development environment is also different. The best way for hobbyists to develop on this chip is either using LGT Arduino Core but not ATmega328 Arduino Core:
https://github.com/dbuezas/lgt8fx  (Arduino IDE)
or
https://community.platformio.org/t/how-to-add-lgt8fx-board/13294 (PlatformIO) Or you can use their official SDK for development which is very different from AVR's environment.
LGT8F328p also has SSOP20 and LFP48 package offering smaller or larger number of GPIOs, which are not so well known by DIY community since they are not similar to ATmega328p.
So in general LGT is a different, forward engineered chip and highly unlikely a direct silicon clone copied by reverse engineering.
In general having peripheral registers and pin compatibility are not illegal, unless the IP core of the peripherals are stolen from ATmega328p. And since CPU instructions (and clock trees) are quite different, if assembly language is used for development, developer would likely feel they are two distinct MCUs. It is just that a C compiler and Arduino framework can hide those details and make them similar.
However, the laws and regulations differ across countries and states so I am not sure if that applied to all markets. And there is natural murkiness in what is an IP and what is not. In software, API similarity could result in infringement but in the world of MCU pin compatibility would not, despite they are both "interface similarity" issues.

Legal or not, I DO NOT reccomend this clone. It is similar and compatible to some extend but it lacks features like an EEPROM. With fuses you can only reserve some FLASH to emulate an EEPROM. Thus have less space for your code.
Also the manual is only available in chinese. There are english translations but those are hard to read as the layout got screwed up.
It has some new features that sound great but I would not see them as replacement for the ATmega328P from Atmel/Microchip.
I bought an Arduino clone with LGT8F328P by accident. I find it barely usable as there are itches here and there which I don't want to deal with.

time has passed and this alterative has become more and more popular, documentation and even Arduino support appeared. Having successfully used it in a product with no more headaches (including after-sales) than the Ex-Atmel Microchip counterparts, I think this answer could use some updates.

As legal as any other clone CPU / MCU.  See

Intel vs The World

In short:  if you copy the silicon design it's illegal. If you create it yourself from the ground up it's legal.
However, IANAL, so don't quote me on that.

Yes, I can remember the Cyrix fight! If I remember it correctly, it was not 100% compatible and a "Windows bug" made the OS working only on Intels, right? It would be nice to find out why this processor is only sold by this seller and not from digikey, farnell or mouser.


text:
command keeps echoing because web page tries refreshing
I want to execute a action only once when I press web page button but as the page tries refreshing the action gets executed in a loop.
I am using the wifimanualwebserver example for esp8266.
Please suggest what should I do?

Not sure if it possible in your case, but you might send and ID with it which you increase every time the button has been (really) clicked (thus not refreshed). On the receiver side, check if the ID is already received, if yes, do not execute it.


text:
Any advice you can give me on my step motor code?
I'm very new to Arduino, currently undertaking a uni project in which my team wish to create a sort of slot machine-esque device that uses a step motor to rotate a drum (like one of the cylinders in a slot machine).
What I've currently tried to do is merge some code that uses a counter variable and button to enable a servo to rotate round multiple times with a single button, with code I found that i think is used to test a step motor? In my mind the code I have should allow me to rotate my stepper by 45 degrees after each button press, but I have no idea if my code makes any sense. Could you guys tell me if im close or is it a load of rubbish. if it does work ok, id look to set the speed higher and have the motor perform multiple full rotations before each stop, to make it work more like an actual slot machine spinner. any advice you could offer would be great, apologies in advance if i don't quite understand certain things  you may explain as I am new to coding, as I mentioned.
Here's the code:

#include <Stepper.h>

//variables
int counter = 0;
const int buttonPin = 8;
const int stepsPerRevolution = 90;

Stepper myStepper(stepsPerRevolution,1,2,3,4);

void setup() {

 pinMode(buttonPin, INPUT);
 myStepper.setSpeed(60);

}

void loop() {

  int buttonState;

  buttonState = digitalRead(buttonPin);

   if (buttonState == LOW)
  {
    counter++;

 delay(150);
  }

if(counter == 0)
   myStepper.step(0);

 else if(counter == 1)
   myStepper.step(45);

 else if(counter == 2)
  myStepper.step(90);

 else if(counter == 3)
    myStepper.step(135);

else if(counter == 4)
   myStepper.step(180);

 else if(counter == 5)
  myStepper.step(225);

else if(counter == 6)
    myStepper.step(270);

else if(counter == 7)
  myStepper.step(315);

else if(counter == 8)
    myStepper.step(360);

  else
   counter = 0;

}

The event of a button press is not deterministic in your case. Generally, your delay()-approach combined with reading the current button state is not how sth. like this works.
Instead, you have to detect when a button is pressed/released.
One way to do that is the following:
#define buttonPin 8
bool last_state=false;

void loop(){
  if(!digitalRead(buttonPin)) {
    if(last_state) {
      //button has been released
      //increment your counter here
    }
    last_state=false;
  } else {
    last_state=true;
  }
}

First understand that myStepper.step(x) method is relative steps not absolute. So if you want the motor to do two rotations of 45 steps back to back you should write
myStepper.step(45);
myStepper.step(45);    /// NOT myStepper.step(90)  <-- that's 90 MORE steps

Second, it looks like your code will increase steps taken by 45 while HOLDING the button down but should also rotate the motor 45 steps for each button press as long as the subsequent presses do not occur while the motor is in mid rotation.
Furthermore, your can delete the following extra else if statements and it should still work.
else if(counter == 2)
  myStepper.step(90);

 else if(counter == 3)
    myStepper.step(135);

else if(counter == 4)
   myStepper.step(180);

 else if(counter == 5)
  myStepper.step(225);

else if(counter == 6)
    myStepper.step(270);

else if(counter == 7)
  myStepper.step(315);

else if(counter == 8)
    myStepper.step(360);


text:
DS3231 + button to trigger light
please can someone help me with code, i want to have automatic trigger on specific hour, also i want to have button switch if needed, in my code i can press the button to trigger light relay, but my specific time trigger just flash at start time and does nothing, here is code:
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc(SDA, SCL);
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5 ;

void setup() {
 lcd.begin(20,4);
 rtc.begin();

 pinMode(relay_3,OUTPUT);
 pinMode(8, INPUT_PULLUP);
}

void loop() {
  int button_4 = digitalRead(8);
  t = rtc.getTime();
  lcd.setCursor(0,1);
  lcd.print(rtc.getTimeStr());

  if(t.sec == OnSec)                                  //if is hh.mm.30 - just for 1 sec trigger relay
  {
  digitalWrite(5,HIGH);
  }
    else if(t.sec == OffSec)                         //if is hh.mm.05 - release relay
  {
  digitalWrite(5,LOW);
  }
      else if (button_4 == HIGH)                     //if button is pressed - trigger relay
  {
  digitalWrite(5,HIGH);
  }
        else
  {
  digitalWrite(5,LOW);
  }

  lcd.clear();
}

i would be gratefull for any advice :)

the indentation of the code in the if ... else block is really messed up

the last else command is the culprit .... think very carefully about the whole if ... else block

The else case is executed every time the other if and else if conditions are not true. That means if it is not 5 sec and not 30 sec and no button is pressed, the relay is switched off.
To achieve what you want is not that easy, because you have to synchronize button press and button release with the timer actions. First you must specify what you exactly want to do. e.g What happens if you have already pressed the button and release it in the time interval between 30 and 5. Releasing the button would switch off the light but should it stay on because you are within the on-time? This is just an example of what to think about.
I wrote a little code for fun doing the things as I would do it:
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc( SDA, SCL );
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5;

int timerPhase = -1;
int relayState = LOW;

void setup()
{
 lcd.begin( 20, 4 );
 rtc.begin();

 pinMode( relay_3, OUTPUT );
 pinMode( 8, INPUT_PULLUP );
}

void loop()
{
  t = rtc.getTime( );

  int button_4 = digitalRead( 8 );

  lcd.setCursor( 0, 1 );
  lcd.print( rtc.getTimeStr( ) );

  // this only works if the off time is
  // less than the on time. (OffSec < OnSec)
  timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

  if ( button_4 == HIGH )
  {
    // a button overrides the timer phase
    relayState = HIGH;
  }
  else
  {
    if ( timerPhase == 0 )
    {
      relayState = LOW;
    }
    else
    {
      relayState = HIGH;
    }
  }

  digitalWrite( relay_3, relayState );

  lcd.clear();
}

I could not try the code because I don't know which libraries you used and therefor got compiler errors. So there might be syntax errors in my code but I hope I wrote correct code. It would be nice if you report errors here, if you find one/some ;-).
The line
timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

uses a ternary operator. It means if the condition ( (t.sec > OffSec) && ( t.sec < OnSec ) ) is true, take the first alternative 0 and assign it to the variable timerPhase, if it is false choose the second alternative '1'.


text:
Using Arrays and LED's to represent Piano Scales
I am trying to use addressable LED's to show various piano scales using the semi notes formula for each scale as an array and an input to indicate the starting note.
int MajorScale[] = {2,2,1,2,2,2,1}; //represents the semi notes in a major scale
int t= 8 //represents the led number that represent the first C on the keyboard

The following leds should light up -
(8, 8+2, 8+2+2, 8+2+2+1, 8+2+2+1+2, 8+2+2+1+2+2, 8+2+2+1+2+2+2 , 8+2+2+1+2+2+2+1)  // This is first C Major Scale on the Piano
so..
(8,10,12,13,15,17,19) // This is first C Major Scale on the Piano where 8 is the first c
Then light up all the other C Major scales available on the piano limited by the number of keys on the piano in this case 76 keys
As there are 12 notes for each octave , add this to the array
if i take just the C note
8, 8+12, 8+12+12 ,8+12+12+12, 8+12+12+12+12  etc
My code so far just lights up the semitone that i set up in the array
enter code here
#include "FastLED.h"
#define DATA_PIN 5
#define NUM_LEDS 76
#define BRIGHTNESS 10
CRGB leds[NUM_LEDS];
int MajorScale[] = {2,2,1,2,2,2,1};
int delayValue = 1000;

void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
FastLED.clear();
}

void loop() {
for(int i = 0; i <=6; i++)
{
    leds[MajorScale[i]] = CRGB::BlueViolet;
    FastLED.show();
     delay(delayValue);

}

FastLED.clear();
}

And what is your question? What is the specific problem, that you have with coding the rest?

How do i make this happen .. From the initial array {2,2,1,2,2,2,1} to the first set of LED lights (8,10,12,13,15,17,19) . I cannot visualize the formula that adds each element of the array to its next element.  Feels like a running sum with an addition of a constant

Your current code will not show all notes of a scale. Only the notes at 1 and 2 will light up, since you don't sum up the numbers, that you have stored in MajorScale. But I think it is not a great idea to sum them up programatically, since this is a constant and you don't win much by representing the data this way. Instead you should directly initiate the MajorScale variable with the summed up values:
int MajorScale[] = {0, 2, 4, 5, 7, 9, 11};

Then you can enclose your for loop with another for loop, that adds an offset corresponding to the octave:
for(int j=0; j<NUM_LEDS; j+=12){
    for(int i=0; i<=6 && MajorScale[i]+j<NUM_LEDS;i++){
        leds[8+MajorScale[i]+j] = CRGB::BlueViolet;
        FastLED.show();
        delay(delayvalue);
    }
}

So we set the LED number 8+MajorScale[i]+j. 8 for the offset to C, MajorScale[i] as the position of the note in the current octave and j for the offset of the current octave relative to the C.
Note, that this is not tested in any way.

A fear you forgot to sum the MajorScale values. e.g.  leds[MajorScale[ 0 ]+j] ==  leds[MajorScale[ 1 ]+j] are pointing to the same LED. And must also be an poffset of 6 for each j. IMHO ;-)

Ah, you are right. I got that mixed in my head. I will change the answer

As I saw the edit, I realized that I did also a mistake. The idea of modyfing the MajorScale array is better than the offset of 6 (good idea).. I was wrong when I said that each j needs an offset of  6 This first MajorScale starts at LED no 8 but the second scale starts with the next LED; I guess. So if the first C is at LED 8 start with j=8 and add 0. The next LED is the D -> add 2 then E add 2 then F add 1 ... the next octave j++ the , 11} must be removed because j++ jumps to the next octave C where you add 0. and so on. Sorry for this "for each". Party fail ;-)

The position 11 corresponds to the B, which is still 1 half tone under the next octaves C. After that the number of i doesn't matter anymore, since the inner for loop wil exit. But I guess I should initialize i to zero in the for loop.

If you've seen my last comment. I removed it because it was complete nonsense. You're right the code is correct.

@chris thanks that worked.  I want this program to light up the LEDs required and then stop. Leave them on. I updated the for loop and when i did that the LED stopped blinking. I added 8 to the for loop    for(int i=0; i<=6 && MajorScale[i]+j+8<=NUM_LEDS;i++)  I don't quite know why it worked ?


text:
can I program a nano over SPI with another nano?
I'm fairly new to arduino, but I want to program a nano over SPI to skip the bootloader. I know I can program the nano with an uno as a programmer to do this, but I don't have an uno, but I do have a couple of nanos. Can I set up one as a programmer, connect it to another over SPI, and program the 2nd?

from software side there is no difference between Uno and Nano 2018 with new bootloader. older Nano can have old bootloader. Wire over ICSP headers one to one except of the reset pin which should be wired to pin 10 on programmer board

Yes, you can. They use ATmega328 / Atmega328P microcontrollers, which are basically the same.
(The differencies of those microcontrollers are about Brown Out Detection - how they could be set to react on too low voltage. No problem in nearly any Arduino operation.)
The boards differ mainly in the board size and places for pins.

Nano has 328p too. Arduino doesn't use ATmega328

The better then - I do not have one at hands now, so I cannot check it physically. I found the Atmega328 (without P) was mentioned in Tech Specs here https://store.arduino.cc/arduino-nano so I kinda trusted them, but they may did typo or had more verssions historically. Anyway even if they would differ, it would work, if they are both the same, it would work too :)


text:
I have to make an LED with an ultrasonic distance sensor, where the LED blinks faster when getting closer than a specific distance
I already have this code, but I do not know how to make the LED blink.
CODE:
const int ledPin = 6; // The pin of your LED, D06
const int trigPin = 5; // The pin to which the TRIG is connected, D05
const int echoPin = 4; // The pin to which the ECHO is connected, D04
const int ledOnTime = 1000;
// The time that the LED stays on, after detecting the motion (in milliseconds, 1000ms = 1s)
const int trigDistance = 40;
// The distance (and lower than it) at which the sensor is triggered (in centimeters)
//
int duration;
int distance;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  delay(1);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  if (distance <= trigDistance) {
    digitalWrite(ledPin, HIGH);
    delay(ledOnTime);
    digitalWrite(ledPin, LOW);
  }
  delay(100);
}

I corrected the formatting and also added indention. You should really use indention. It makes the code way more readable. The Arduino IDE even has an autoformatting function to introduce correct indention

I would say the way to go is using non-blocking code with millis(). Look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It doesn't use delay(), which is considered bad coding practice, since it is just busy waiting. Nothing else can happen during a delay, except for interrupts. Instead of waiting it is better to regularily check the clock, if it is time to do something (much like you would do in real life for example for baking a pizza).
The clock is provided by millis(), which returns the number of milliseconds since startup. Below you see the BlinkWithoutDelayexample. The variable interval controls the blink frequency. If you remove the const keyword before it and change it according to the measurements from the ultrasonic sensor, you will get a changing blinking frequency with changing distance.
Try to combine the codes into one. Remove all delay() calls, except for the delay(1) (it is needed to trigger the ultrasonic sensor and it is small enough to not matter greatly).
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

The rest is up to you. If you need more information about the BlinkWithoutDelay example, you should google it. There are tons of tutorials. This is a great coding excerise, so have fun :)

step 1: define your MIN_DISTANCE, MAX_DISTANCE
step 2: get distance from sensor
step 3: rescale the distance value to a value in between 0 and 255
step 4: fade led according to the rescaled value.
Note that: you should not use delay() to blink LED. Use analogWrite() instead. See  the example. We can change frequency of PWM to make LED from fading to blinking by using setPwmFrequency() function


text:
I2C code working on Mega 2560 but not on Uno and nano
I have recently purchased this Heart rate sensor and was trying to make it work. I used this MAX30100 library I found on Github. For some reason when I use any of the given examples, they seem to work well when I use a Mega2560 I have but not on the Uno or Nano. Does this have to do with the processor? I don't think so because the README on Github mentions that they tested it on an Uno. But if it is so, how could I change the code to make it work with the Uno and nano?
Example Code I used:
// This example can be used to test connectivity and operation of the sensor
// check the README file on the repo's root for a troubleshooting guide in casem
// any of the tests running fail

#include <Wire.h>
#include "MAX30100.h"

MAX30100 sensor;

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

    Serial.print("Initializing MAX30100..");

    if (!sensor.begin()) {
        Serial.print("FAILED: ");

        uint8_t partId = sensor.getPartId();
        if (partId == 0xff) {
            Serial.println("I2C error");
        } else {
            Serial.print("wrong part ID 0x");
            Serial.print(partId, HEX);
            Serial.print(" (expected: 0x");
            Serial.println(EXPECTED_PART_ID, HEX);
        }
        // Stop here
        for(;;);
    } else {
        Serial.println("Success");
    }

    Serial.print("Enabling HR/SPO2 mode..");
    sensor.setMode(MAX30100_MODE_SPO2_HR);
    Serial.println("done.");

    Serial.print("Configuring LEDs biases to 50mA..");
    sensor.setLedsCurrent(MAX30100_LED_CURR_50MA, MAX30100_LED_CURR_50MA);
    Serial.println("done.");

    delay(1000);

    Serial.print("Lowering the current to 7.6mA..");
    sensor.setLedsCurrent(MAX30100_LED_CURR_7_6MA, MAX30100_LED_CURR_7_6MA);
    Serial.println("done.");

    delay(1000);

    Serial.print("Shutting down..");
    sensor.shutdown();
    Serial.println("done.");

    delay(1000);

    Serial.print("Resuming normal operation..");
    sensor.resume();
    delay(500);
    Serial.println("done.");

    uint32_t tsTempSampStart = millis();
    Serial.print("Sampling die temperature..");
    sensor.startTemperatureSampling();
    while(!sensor.isTemperatureReady()) {
        if (millis() - tsTempSampStart > 1000) {
            Serial.println("ERROR: timeout");
            // Stop here
            for(;;);
        }
    }

    float temperature = sensor.retrieveTemperature();
    Serial.print("done, temp=");
    Serial.print(temperature);
    Serial.println("C");

    if (temperature < 5) {
        Serial.println("WARNING: Temperature probe reported an odd value");
    } else {
        Serial.println("All test pass.");
    }

    Serial.println();
    Serial.println("Press any key to go into sampling loop mode");
    while (!Serial.available());

    sensor.resetFifo();
}

void loop()
{
    uint16_t ir, red;

    sensor.update();

    while (sensor.getRawValues(&ir, &red)) {
        Serial.print("IR=");
        Serial.print(ir);
        Serial.print(" RED=");
        Serial.println(red);
    }
}

What code are you using? Please show us. Also: Have you connected it correctly? As I remember the I2C hardware is on different pins for Uno/Nano and Mega

Also: What does not work well on Uno/Nano? What error do you get? Have you checked for the result of the tester example of the library?

I have added the example I was using in the question. For the connections, I simply connected Vin to 3.3V, SDA to SDA, SCL to SCL and GND to GND.

The main difference is that Arduino mega has pull up resistors on SCL/SDA lines.

Please test with the tester example of the library. It might show, what problem we have here exactly. Have you tried adding pullup resistors to the lines as mentioned in the troubleshooting section of the libraries readme?

I added pull-up resistors to the board and it started working. Turns out that the boards weren't well designed and the I2C lines were pulled up to 1.8V instead of Vin. By removing the pull-ups and adding pull-ups to Vin, the circuit started functioning. The circuit worked with Mega because it has in-built Pull-up Resistors.

And this can be done because those pins can be pulled up to 6V (absolute max).


text:
Is it possible to connect from esp8266 module over HTTPS protocol?
Before I will implementing some server application for Arduino client I should know:
Is it possible to connect from esp8266 module to end-point over HTTPS protocol?
Any links of tutorials are welcome.
Thank in advance.

yes, it is possible. there are examples in IDE Examples menu

Yes it's possible. Try this one tutorial.
https://circuits4you.com/2019/01/10/esp8266-nodemcu-https-secured-get-request/


text:
no matching function to call for SoftwareSerial::SoftwareSerial(int&,int&)? How to rectify this problem
#include <LiquidCrystal.h>

#include <SoftwareSerial.h>

float pulse = 0;

float temp = 0;

SoftwareSerial ser(9,10);

String apiKey = "U5AGYVQT5JRJPSDR";

//  Variables

int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin 0

int blinkPin = 7           ;                // pin to blink led at each beat

int fadePin = 8;                  // pin to do fancy classy fading blink at each beat

int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

LiquidCrystal lcd(13, 12, 6, 5, 4, 3);

// Volatile Variables, used in the interrupt service routine!

volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS

volatile int Signal;                // holds the incoming raw data

volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!

volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not
 a "live beat".

volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

// Regards Serial OutPut  -- Set This Up to your needs

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino
Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values

volatile unsigned long sampleCounter = 0;          // used to determine pulse timing

volatile unsigned long lastBeatTime = 0;           // used to find IBI

volatile int P = 512;                      // used to find peak in pulse wave, seeded

volatile int T = 512;                     // used to find trough in pulse wave, seeded

volatile int thresh = 525;                // used to find instant moment of heart beat, seeded

volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded

volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM

volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void setup()

{

  lcd.begin(16, 2);

  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!

  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!

  Serial.begin(115200);             // we agree to talk fast!

  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS

                                    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,

                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

                                    //   analogReference(EXTERNAL);

  lcd.clear();

  lcd.setCursor(0,0);

  lcd.print("Engineers Garage");

  ser.begin(9600);

  ser.println("AT");

  delay(1000);

  ser.println("AT+GMR");

  delay(1000);

  ser.println("AT+CWMODE=3");

  delay(1000);

  ser.println("AT+RST");

  delay(5000);

  ser.println("AT+CIPMUX=1");

  delay(1000);

  String cmd="AT+CWJAP="EngineersGarage","egP@$$w0rd?"";

  ser.println(cmd);

  delay(1000);

  ser.println("AT+CIFSR");

  delay(1000);

}

//  Where the Magic Happens

void loop()

{

   serialOutput();

  if (QS == true) // A Heartbeat Was Found

    {

      // BPM and IBI have been Determined

      // Quantified Self "QS" true when arduino finds a heartbeat

      fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED
 with pulse

      serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.

      QS = false; // reset the Quantified Self flag for next time

    }

  ledFadeToBeat(); // Makes the LED Fade Effect Happen

  delay(20); //  take a break

  read_temp();

  esp_8266();

}

void ledFadeToBeat()

{

   fadeRate -= 15;                         //  set LED fade value

   fadeRate = constrain(fadeRate,0,255);   //  keep LED fade value from going into negative numbers!

   analogWrite(fadePin,fadeRate);          //  fade LED

}

void interruptSetup()

{

  // Initializes Timer2 to throw an interrupt every 2mS.

  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE

  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER

  OCR2A  = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE

  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A

  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

}

void serialOutput()

{   // Decide How To Output Serial.

 if (serialVisual == true)

  {

     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer

  }

 else

  {

      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function

   }

}

void serialOutputWhenBeatHappens()

{

 if (serialVisual == true) //  Code to Make the Serial Monitor Visualizer Work

   {

     Serial.print("*** Heart-Beat Happened *** ");  //ASCII Art Madness

     Serial.print("BPM: ");

     Serial.println(BPM);

     lcd.clear();

     lcd.print("BPM: ");

     lcd.print(BPM);

   }

 else

   {

     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix

     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix

   }

}

void arduinoSerialMonitorVisual(char symbol, int data )

{

  const int sensorMin = 0;      // sensor minimum, discovered through experiment

  const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data; // map the sensor range to a range of 12 options:

  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the

  // range value:

  switch (range)

  {

    case 0:

      Serial.println("");     /////ASCII Art Madness

      break;

    case 1:

      Serial.println("---");

      break;

    case 2:

      Serial.println("------");

      break;

    case 3:

      Serial.println("---------");

      break;

    case 4:

      Serial.println("------------");

      break;

    case 5:

      Serial.println("--------------|-");

      break;

    case 6:

      Serial.println("--------------|---");

      break;

    case 7:

      Serial.println("--------------|-------");

      break;

    case 8:

      Serial.println("--------------|----------");

      break;

    case 9:

      Serial.println("--------------|----------------");

      break;

    case 10:

      Serial.println("--------------|-------------------");

      break;

    case 11:

      Serial.println("--------------|-----------------------");

      break;

  }

}

void sendDataToSerial(char symbol, int data )

{

   Serial.print(symbol);

   Serial.println(data);

}

ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124

{

  cli();                                      // disable interrupts while we do this

  Signal = analogRead(pulsePin);              // read the Pulse Sensor

  sampleCounter += 2;                         // keep track of the time in mS with this variable

  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

                                              //  find the peak and trough of the pulse wave

  if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI

    {

      if (Signal < T) // T is the trough

      {

        T = Signal; // keep track of lowest point in pulse wave

      }

    }

  if(Signal > thresh && Signal > P)

    {          // thresh condition helps avoid noise

      P = Signal;                             // P is the peak

    }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT

  // signal surges up in value every time there is a pulse

  if (N > 250)

  {                                   // avoid high frequency noise

    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )

      {

        Pulse = true;                               // set the Pulse flag when we think there is a pulse

        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED

        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS

        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat)

        {                        // if this is the second beat, if secondBeat == TRUE

          secondBeat = false;                  // clear secondBeat flag

          for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup

          {

            rate[i] = IBI;

          }

        }

        if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE

        {

          firstBeat = false;                   // clear firstBeat flag

          secondBeat = true;                   // set the second beat flag

          sei();                               // enable interrupts again

          return;                              // IBI value is unreliable so discard it

        }

      // keep a running total of the last 10 IBI values

      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++)

        {                // shift data in the rate array

          rate[i] = rate[i+1];                  // and drop the oldest IBI value

          runningTotal += rate[i];              // add up the 9 oldest IBI values

        }

      rate[9] = IBI;                          // add the latest IBI to the rate array

      runningTotal += rate[9];                // add the latest IBI to runningTotal

      runningTotal /= 10;                     // average the last 10 IBI values

      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!

      QS = true;                              // set Quantified Self flag

      // QS FLAG IS NOT CLEARED INSIDE THIS ISR

      pulse = BPM;

    }

  }

  if (Signal < thresh && Pulse == true)

    {   // when the values are going down, the beat is over

      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED

      Pulse = false;                         // reset the Pulse flag so we can do it again

      amp = P - T;                           // get amplitude of the pulse wave

      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude

      P = thresh;                            // reset these for next time

      T = thresh;

    }

  if (N > 2500)

    {                           // if 2.5 seconds go by without a beat

      thresh = 512;                          // set thresh default

      P = 512;                               // set P default

      T = 512;                               // set T default

      lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date

      firstBeat = true;                      // set these to avoid noise

      secondBeat = false;                    // when we get the heartbeat back

    }

  sei();                                   // enable interrupts when youre done!

}// end isr

void esp_8266()

{

   // TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80

    String cmd = "AT+CIPSTART=4,"TCP","";

    cmd += "184.106.153.149"; // api.thingspeak.com

    cmd += "",80";

    ser.println(cmd);

    Serial.println(cmd);

    if(ser.find("Error"))

    {

      Serial.println("AT+CIPSTART error");

      return;

    }

  // prepare GET string GET https://api.thingspeak.com/update?api_key=LHAG4NSIYJ5UWS6U&field1=0rnrn

  String getStr = "GET /update?api_key=";

  getStr += apiKey;

  getStr +="&field1=";

  getStr +=String(temp);

  getStr +="&field2=";

  getStr +=String(pulse);

  getStr += "rnrn";

  // send data length

  cmd = "AT+CIPSEND=4,";

  cmd += String(getStr.length());

  ser.println(cmd);

  Serial.println(cmd);

  delay(1000);

  ser.print(getStr);

  Serial.println(getStr);

 //thingspeak needs 15 sec delay between updates

  delay(3000);

}

void read_temp()

{

  int temp_val =  analogRead(A1);

  float mv = (temp_val/1024.0)*5000;

  float cel = mv/10;

  temp = (cel*9)/5 + 32;

}

Align your code (select and press ctrl-k), and also make the minimal sketch that shows the program.

Sorry can you brief it clearly?

I see now the code is already aligned (if you didn't do it, someone else did)

I don't see anything wrong in the SoftwareSerial declaration … can you recheck you are using the correct library? Check the constructor of the SoftwareSerial class you are using.

you are on esp8266. they changed the constructor an moved the parameters to begin()

I just copied the code from web ..should i add any other function or header file to this code

yes i'm using esp8266, can you explain what should i change in that code

can we use this code for nodemcu wifi module ?

the sketch is not for NodeMCU. it is for Uno with esp8266 wired to pins 9 and 10

The sketch in the question is not for NodeMCU. It is for Arduino with esp8266 wired on pins 9 and 10. But the error in title is a current error for esp8266 Arduino boards package 2.6.0. The EspSoftwareSerial bundled with the esp8266 Arduino boards package version 2.6.0 has a compatibility breaking change.
The problem was immediately reported and the EspSoftwareSerial maintainer added the legacy API back to EspSoftwareSerial. The fixed version will be available with esp8266 boards package 2.6.1, which will be available soon because of multiple problems with 2.6.0.

2.6.1 is released


text:
Creating a sine with PWM Arduino DUE
I've been trying to create a sine wave using the pwm function of the Arduino DUE.
The sine wave has te be at higher rates than the analogWrite() function can handle, so I've been using the native capabilties of the SAM3X8E.
To test it, instead of creating sinus I've been doing it linear. The code to do that is:

  REG_PWM_ENA = REG_PWM_SR | B11111111; //enable output
  REG_PWM_CMR3 = 0x00000; //deadtime 0
  REG_PWM_CPRD3 = value;
  REG_PWM_CMR2 = 0x00000; //deadtime 0
  REG_PWM_CPRD2 = value;
  int i =0 ;
  waittime = 100;
  value = 30

  while (!Serial.available()) {
    REG_PWM_OS = 0x0000C;

for (i = 0; i < value; i++) {
      pwmc_duty(i);
      pwmc_duty4(i);
      wait(waittime);
    }

for (i = value; i > 0; i--) {
  pwmc_duty(i);
  pwmc_duty4(i);
  wait(waittime);
}
REG_PWM_OS = 0xC000C;
wait(1);
pwmc_duty(value);
pwmc_duty4(value);
REG_PWM_OS = 0xC0000;

for (i = value; i > 0; i--) {
  pwmc_duty(i);
  pwmc_duty4(i);
  wait(waittime);
}

for (i = 0; i < value; i++) {
  pwmc_duty(i);
  pwmc_duty4(i);
  wait(waittime);
}

REG_PWM_OS = 0xC000C;
wait(1);
pwmc_duty(0);
pwmc_duty4(0);
}

inline void pwmc_duty(unsigned short duty0) {
   // REG_PWM_CPRD3 = duty0;
    REG_PWM_CDTY3 = duty0;
}
inline void pwmc_duty4(unsigned short duty0) {
   // REG_PWM_CPRD3 = duty0;
    REG_PWM_CDTY2 = duty0;
}

void wait(int times){
  for (int i =0;  i < times; i++){
    __asm__("nop\n\t");
  }
}

I expect the code to gradually increase the duty cycle of the signal and than slowly decrease. And that works!
The problem is that i do not get a normal PWM signal out of it.
I've attached one of the previous test signals to this post, with a bit different code, to show the problem.

i've expected the pwm more clear like demonstrated in this paint picture:

How do I get from these spikes to a more normal block signal?

"I expect the code to gradually increase the duty cycle of the signal and than slowly decrease. And that works! The problem is that i do not get a normal PWM signal out of it." - what exactly doesn't work?! Or, how do you know that incrementing the duty cycle works?

Maybe its just an aliasing problem, can you configure a lower pwm frequency?

@SimSon I saw on the scope that the pwm increased and decreased as expected. The picture is not really showing it, but it does show the problem.
It could indeed be an aliasing problem, but I have tried slowing it down and it was without a different result.

Or play with the scope settings. Zooming into a signal that strong probably won't work... also, I still don't understand: if you see the pwm increase and decrease, what is "the problem" then?!

why you don't use the DAC of DUE?

By "create a sinus" I assume you mean that you want to generate a sine wave?

The scope works with 12.5 kS/sec so according to Pete (ahh no) according to Nyquist you can measure signals up to 6.25kHz (sinus wave). That's a theoretical limit, the scope must also be capable of reconstructing the original wave.  As you have a rectangle PWM wave, there are much higher frequencies in the signal than the PWM frequency. So I would say, you have aliasing problems. Can you configure the oscilloscope to a higher sampling rate? e.g 500 kHz?  It is also possible that your PWM Frequency is too low for the sinus wave you want to modulate on it.

As @Juraj mentions - the DUE has a real 12-bit DAC built in. Use that to create an actual analog waveform rather than trying to emulate one with PWM.

@DuncanC I meant sine wave, yes.


text:
How can I clear the memory of my Arduino in this case?
I have made a code using involving HID control. But it seems that I messed up, but I can't upload a new sketch(nor edit the wrong code), because my Arduino is constantly doing things like Ctrl+Alt+Delete, Alt+F4... etc.
It seems that the only way is erasing the code in the memory, but how can I do so?

Use a hardware programmer (USBASP, etc, or an Arduino as an ISP).

Do the "button dance" - hold the Arduino in reset, releasing just you see the download start in the IDE. This may (will!) take a little practice to get just the right timing.

or

Use an external programmer connected to the ICSP connector. This could be a commercially made one, a DIY, or another Uno programmed and connected as an ICSP programmer. How-to's abound on the web.

You can't do the "Button dance" on the Leonardo. Holding it in reset will not give you a serial port to start the upload to. Depending on the bootloader version you may get a few seconds after releasing the reset where it presents a COM port before the sketch runs (good luck on Windows - it may take too long to enumerate...), or pressing reset twice rapidly may put it in the bootloader. Best to have a programmer on hand anyway though as a general rule regardless.


text:
Bad Data : Arduino Mega & NodeMCU Serial Communication
Currently I am working on an Arduino project. The project required to establish communication between Arduino Mega and NodeMCU ESP8266. Here are some details about the project:

NodeMCU Rx Pin is connected to Arduino Mega Pin 14 (Tx3), while NodeMCU Tx Pin is connected to Arduino Mega Pin 15 (Rx3), Jumper Wires is used to connect NodeMCU and Arduino Mega
Both Arduino Mega and NodeMCU are using baud rate 115200

Code for NodeMCU ESP8266 (Send The Data to Arduino Mega):
void loop(){
       esp.println("0000");

       esp.flush();
}

Code for Arduino Mega (Receive Data) :
 if(Serial3.available()){

  data = Serial3.readStringUntil('\n');

  Serial3.flush();

  Serial.println(data);

}

The result :

The intented and expected result is "0000", however, the result shown in serial monitor is not accurate. Anyone could advise?

Is that a 3.3V Mega  or did you use a level shifter? You know that the 5V of a normal Mega can fry your ESP? And the other thing is: Why do you flush Serial3  but have not written to it? That is a hight baud rate, so event the quality of the wiring could be a problem.

did you connect grounds?

the spaces are \r. maybe the buffer overflows while you print the received string so you get incomplete 0000. try a small delay in esp8266

@PeterPaulKiefer, the esp8266 has no problems with 5 V serial communication on UART, SPI, I2C and similar. And I run Mega to ESP-12F UART with 500000 baud on jumper wires

@Juray I uv your comment questioning the grounds because I think that is the best idea and the most probable. -- As long as the arduino does not try to write to the ESP you're sure. But I had to bury one of the little esps I once owned after I tried to establish a 5V power connection ;-) So it may work or fail, but if it fails the part sails on the styx. The baud rate is not the problem. Want I meant is if you use a higher baud rate, lower parasitic capacitance can distort the communication. So if the connection are of bad quality, that could be a problem. But the gnd idea is still my favorit.

@PeterPaulKiefer, 5 V to Vcc is a different topic

Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help


text:
How to Measure many voltages (Uno) - Analog extenders a good option?
I am trying to make a battery capacity tester (3.7v li-ion 18650 battery) using arduino uno. If possible i'd like to test 20 or more batteries at the same time. I need to measure the voltage of each battery every 1 second.
The uno has 6 anolog inputs iirc so too little for this application.
I think using analog multiple extenders (connected using I2C) chained together to create enough analog inputs.
For example this one: https://nl.aliexpress.com/item/32858973834.html?spm=a2g0o.productlist.0.0.57206143DNgWKp&algo_pvid=526d42f2-f7ee-4781-932b-947744ac631e&algo_expid=526d42f2-f7ee-4781-932b-947744ac631e-0&btsid=89c452fa-1d7c-4ae9-9dd5-ed8fc9bff128&ws_ab_test=searchweb0_0,searchweb201602_8,searchweb201603_52
Do you think I'll be able to get relatively accurate voltage measurements using this approach?
The purpose of the circuit is to measure the amount of mah (battery capacity) of the 18650 battery which is being discharged via the 10Ohm resistor. The battery will be discharged from 4.2volt (fully charged) to approx 2.5V using the 10ohm resistor, each second the voltage drop over the resistor will be measured and using it and the time passed the integral of time*current will be calculated to determine the capacity.
This is the basic circuit used to connect each 18650 battery, the ANALOG1 pin will be connected to the input of the analog extenders:

(I based it off of the circuit from this video: https://www.youtube.com/watch?v=WScPyfQz_f8)
The idea is to measure the voltage drop over the 10Ohm10W power resistor and calculate the current using the known resistance value, calculate the integral of current*time to get a capacity value for the battery.
Is this a good approach? Would you recommend using analog extenders for this? If not what would be a better solution? Thank you very much!

@jsotola My mistake I don't indeed, only need 1, will edit post

I'd go for a set of 8-input ADCs, such as https://www.digikey.com/product-detail/en/microchip-technology/MCP3208-BI-P/MCP3208-BI-P-ND/319443  8 channels, 12-bit resolution, fast SPI access.  That 10 ohm resistor may get pretty warm. How will you disconnect the battery when it gets low on charge so that it doesn't become damaged from over-discharge?

Your circuit will draw about 360 mA from each battery through your 10 Ω resistor. Do you have a way to disconnect the batteries when they are not being tested?

@Duncan C For disconnecting the battery i will use a mosfet which i will turn off using arduino when battery voltage gets too low. I forgot to draw it in the circuit

@Crossroads thank you for the suggestion i will look inyo using that approach. The battery will be disconnected using a mosfet which is controlled by arduino which turns off the mosfet when the battery voltage gets too low

I personally made good experience with using analog multiplexers (that's the same thing that the arduino does to provide 8 analog inputs while only having 1 ADC, but of course CrossRoad's approach is fine, too. The circuit you provided doesn't work, you measure the battery's voltage directly which potentially can destroy the arduino. Take a look at the circuit shown in the video again. you need 2 analog inputs to measure the voltage drop over the shunt (current) and at least a voltage divider to measure the voltage

So you're going to have a 10 Ω power resistor wired into your circuit at all times? That means you'll be draining almost .4 A of current from your battery at all times. If it's a 4 Ah battery, your measurement resistor will drain your battery in 10 hours, with no actual load. Seems to me that you should have the MOSFET off by default, turn it on for an instant, measure the input into your analog pin, then turn the MOSFET back off.

@ Duncan C Thank you for your concern. I have not explained the purpose of the circuit properly, sorry. The purpose of the circuit is to measure the amount of mah (battery capacity) of the 18650 battery which is being discharged via the 10Ohm resistor. The battery will be discharged from 4.2volt (fully charged) to approx 2.5V using the 10ohm resistor, each second the voltage drop over the resistor will be measured and using it and the time passed the integral of time*current will be calculated to determine the capacity.

Actually it is two separate questions and I answer your first question of reading multiple analog values using one ADC and the answer is Yes you can use this approach but  you should give enough time for each channel to charge internal ADC capacitor when you change channel .so if you use more independent ADC you get more time for each channel and result is better


text:
Measuring 12 V via voltage divider: choosing the right resistors
I want to measure a 9 V battery via one of the analog input ports of my Arduino Nano. From all the schemes of this great answer, I choose the simplest one, the voltage divider. Assuming the maximum input voltage to be 12 V (just to be safe) and maximum divider's output voltage to be 5 V, I've solved it against R₂:R₁ proportion. It turns out that R₂:R₁ = 5:7.

simulate this circuit – Schematic created using CircuitLab
With the values above, the input of A0 pin will be exactly 5 V.
The problem is that it could be any values. 5 Ω and 7 Ω or 5 MΩ and 7 MΩ!
I understand, that there should be another equation to take into account that will give me the values of those two resistors. Another brilliant answer demonstrates, that the values depend on the current I want to flow through the branches:

So the point is when determining the resistance of the resistors, we should take into account the input resistance of the load and the two voltage divider resistors should be as small as possible.
On the other hand, let's compare the current going through the divider in the circuit with large resistors on the divider and the circuit with small resistors on the divider. As you can see, the large resistors have current of just 2.5 μA going through them and the small resistors have current of 25 mA. The point here is that the current is wasted by the voltage divider and if this was for example part of a battery operated device, it would have a negative impact on the battery life. So the resistors should be as large as possible in order to lower the wasted current.

9 V batteries are known to have a little of energy canned inside, with the most popular 6LR61 having only about 550 mA·h. I do not want to waste it on heating the resistors, so, probably, I need to use large resistors. But how large? Too large R₁ will let only a little current to flow to the A0 pin and I've read somewhere that small currents may lead to analogRead measurement errors (underestimations?) due to ADC's internal capacitor.
Trying to find the right answer, I've read on the Arduino's forum that:

The ATmega328P datasheet has this info way in the back: Table 28-16 (page 328). The analog input resistance is claimed to be 100 Mohms.
During an actual sample, the input resistance is temporarily a lot lower as the sampling capacitor is charged up so it is recommended that whatever you connect to the A/D have an output impedance of 10k or less for best accuracy.

And here, I am stuck. I understand that I am connecting a voltage divider to the A/D, but what is it's "output impedance"? It should depend on R₁ and R₂ somehow, and solving that equation (F(R₁, R₂) == 10 000) will give me the exact value…
P.S. I saw some cunning schemes in the Internet with capacitors, diodes and op-amps (everybody say it's super easy and safe to use them for this task), but, please:

I am just trying to understand the basics and making my first steps with electronics.
The device I'm making should be lightweight and compact (although I should be able to compose it without any PCB magic). Two resistors seems to be fine.
I'm going to read the voltage only once when the device is turned on, so I don't actually need super-fast op-amp's speed.
I'll try not to plug negative voltage, so I do not need a protection. Yet.

Wow that's a long question.  I did a quick search and "noise" is not in there. So, here's yet another consideration: If the resistances are too large and the environment is noisy enough, nose may leak into your measurements and cause false readings.  You can mitigate this by using lower resistances. You can also mitigate this in your firmware.  You can also mitigate this by controlling the noise source.  Oh, and chances are that you will always make multiple measurements to mitigate noise.  It is common a 12 bit ADC to not have 12 bits (maybe only 8 bits) of resolution if no averaging is done.

Thanks, @st2000! I indeed read about large resistors "catching" the noise. I thought to mitigate that by reading the value, say, 10 times and averaging it. As I've said, it's only done once and need not be extra-fast.

And, yes, I've tried to put everything I've learned so far in the question, because there is so much information on the Internet and so many parameter. Like your consideration about the noise.

One more advice I saw, is just using ~10 kΩ as R₂ and never bother, but I want to understand the math.

Another general consideration: Never apply a voltage to any pin on a logic chip (microprocessors included) which is higher than the supply voltage.  So, if the micro is actually a 3V3 device, you should not apply a 5V signal to any of its pins.  In fact, many designs have clamping circuits to avoid accidental high voltages.

@st2000, but Nano seems to have 5 V operating voltage. And I am going to apply 9 V (12 V) via a voltage divider, that will drop it to less than 5 V, so I am safe?

Some Arduino processor run at 3v3, others at 5v.  Spot checking, I see schematics where the Nano's processor's VCC pins are connected to 5v.  Fresh batteries are sometimes a little higher than their labeled voltage.  Also, mistakes can happen.  Connecting a 12V battery to a voltage divider designed to convert 9V to 5V.

That's why I'm calculating 12 V divider for a 9 V battery :)

What you are looking for is called the Thévenin equivalent source.
For the schematic you are showing, and assuming you can neglect the
output resistance of the battery itself, the output resistance of the
voltage divider is the same as the two resistors in parallel. If you
want the maximum allowed resistance (minimum current) you have then to
solve:
1/R1 + 1/R2 = 1/(10 kΩ)
R2 / (R1 + R2) = 5/12
which gives:
R1 = 12/5 × 10 kΩ = 24 kΩ
R2 = 12/7 × 10 kΩ ≈ 17.1 kΩ
You can then round the values down to the closest standard values,
taking care that the rounding does not impose more than 5 V on the
analog pin. For example, if you restrict yourself to the E6 series, you
could choose
R1 = 22 kΩ
R2 = 15 kΩ
which would give you a Thévenin equivalent output resistance of
8.9 kΩ, and a maximum output voltage of 4.86 V.

Thank you. So, basically, I need to cross out the batteries and calculate the resistance of the divider between the points I used to attach the Arduino (ground and between the resistors)?

@madhead: Yes. That's basically what Thévenin's theorem tells you.