message:
Can't Upload Sketches to Arduino Nano Every

first-time builder here.  I just got my Arduino Nano Every in the mail from Mouser, and I'm trying to upload a modified version of the blink example to my new brand-new board.  However, every time I try to upload a sketch, the IDE just spins its wheels for around 5 minutes before giving up.  I've been trying to look through similar questions and haven't found anything that has solved my issue.  My OS is Windows 10.

Here's a snippet of the log (I've turned on verbose reporting for compilation and upload):

    Arduino: 1.8.13 (Windows 10), Board: "Arduino Nano Every, None (ATMEGA4809)"
    …
    Forcing reset using 1200bps open/close on port COM1
    …
             Using Port                    : COM1
             Using Programmer              : jtag2updi
             Overriding Baud Rate          : 115200
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    avrdude: jtagmkII_getsync(): sign-on command: status -1
    An error occurred while uploading the sketch

Here are the settings I'm currently using:

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

Here's what I've tried so far:

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

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

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


sender: user

message:
Simple ModBus Master function 15

I have a simple setup with arduino Nano as slave and a arduino Mega as master
Can anyone explain how the function 15
FORCE_MULTIPLE_COILS
Works

i have been running some test on this
and cant figure out how to use the
local_start_address

is this the data to read from
or
is it a pointer to another File

modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 1021);

dec 8 = (no_of_registers = packet->data)  // number of coils

so frame 6 = 1 (frame[6] = no_of_bytes;) // number of bytes more

dec 1021 = (packet->local_start_address)
the dec 1021 and 65565 seams to work ????
but makes no sense to me in binary format ?

Here is
part of CPP file:

    enter code here

    unsigned char construct_F15()
    {
       // function 15 coil information is packed LSB first until the first 16 bits are completed
      // It is received the same way..
      unsigned char no_of_registers = packet->data / 16;
      unsigned char no_of_bytes = no_of_registers * 2;

      // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad
      if (packet->data % 16 > 0)
      {
        no_of_registers++;
        no_of_bytes++;
      }

      frame[6] = no_of_bytes;
      unsigned char bytes_processed = 0;
      unsigned char index = 7; // user data starts at index 7
       unsigned int temp;

      for (unsigned char i = 0; i < no_of_registers; i++)
      {
        temp = register_array[packet->local_start_address + i]; // get the data

    frame[index] = temp & 0xFF;

        bytes_processed++;

        if (bytes_processed < no_of_bytes)
        {
          frame[index + 1] = temp >> 8;
          bytes_processed++;
          index += 2;
        }
      }
       unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes
       return frameSize;
    }

sender: assistant

body:
i found it

it is the

 temp = register_array[packet->local_start_address + i]; // get the data
 in the ccp file

register_array[packet->local_start_address + i]

its pointing to the wrong location... register_array??

supersized no one has noticed this as long as the simple modbus master for adruino
has been used ?

or i have a bad CPP file ?

i have temp corrected this by replacing with

    unsigned char construct_F15()
    {
        // function 15 coil information is packed LSB first until the first 8 bits are completed
        unsigned char frameSize = 10;
        unsigned char temp;
        frame[6] = 1;
        frame[7] = packet->local_start_address ^ 0XFFFF;
        return frameSize;
    }

works (0 = off / 255 = on)

modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 0); // 1 thru 8 = off

modbus_construct(&packets[PACKET2], 1, 15, 1, 8, 255); // 1 thru 8 = on


message:
Arduino + Codeblocks C++

I'm writing the code for my Arduino board using Code::Blocks editor. When I create a new project, there is **AVR Project** and **Arduino Project** under Projects category. Which one do I select?

body: You can select, what you want. If you want to build an Arduino Project, you should choose "Arduino Project". If you don't want to use the Arduino Framework, you can choose "AVR Project".


message:
why is "if" slow?

I am new to the Arduino world and I hope I can find a solution here. The code below functionally works ok. The problem I have is, at line 45 I've inserted an `if` statement to change `dac_value`. It is very slow while serial and all that is outside `if` works fast/fine... What would be a solution to make it fast? Tried `if` - `else if` and also `while`... result is the same. Hope someone can help. Thank you.

    {
    #include <Arduino.h>
    #include <Wire.h>
    // #include <LiquidCrystal_I2C.h>
    #define MCP4725 0x61
    #define MCP4725B 0x60
    unsigned int val;
    byte buffer[3];
    byte buff[3];

    int ClockPinV = PB1;
    int ClockPinA = PA6;
    const int currsensPin = PA3;
    const int voltsensPin = PA2;

    void setup()
    {
      Serial.begin(115200);
      pinMode(currsensPin , INPUT_ANALOG);
      pinMode(voltsensPin , INPUT_ANALOG);
      pinMode(ClockPinV , INPUT);
      pinMode(ClockPinA , INPUT);
      Wire.begin();
    }

    int val0 = 1024;
    int val1 = 4096;
    volatile int dac_value = 0;

    void loop()
    {
      analogReadResolution(12);

      volatile int svolt = analogRead(ClockPinV);
      volatile int scurr = analogRead(ClockPinA);
      volatile int set_voltage = (3.3/4096)*svolt;
      volatile int set_curr =  (3.3/4096)*scurr;
      volatile int securr = analogRead(currsensPin);
      volatile int real_curr = (3.3/4096)*securr;
      volatile int sevolt= analogRead(voltsensPin);
      volatile int real_output2 = (3.3/4096)*sevolt;

    if(real_curr < set_curr){
        if(set_voltage > real_output2)
        {
          dac_value = dac_value + 1;
        }
        if(set_voltage < real_output2)
        {
          dac_value = dac_value - 1;
        }
      }
      else if(real_curr > set_curr)
      {
        dac_value --;
      }

      dac_value = constrain(dac_value, 0, 2673);
      buffer[0] = 0b01000000; //control byte
      buffer[1] = dac_value >> 4; //MSB 11-4 shift right 4 places
      buffer[2] = dac_value << 4; //LSB 3-0 shift left 4 places

      Wire.beginTransmission(MCP4725); //address device
      Wire.write(buffer[0]); //pointer
      Wire.write(buffer[1]); //8 MSB
      Wire.write(buffer[2]); //4 LSB
      Wire.endTransmission();

      // val1 = constrain(val1, 0, 2673);
      buff[0] = 0b01000000; //control byte
      buff[1] = svolt >> 4; //MSB 11-4 shift right 4 places
      buff[2] = svolt << 4; //LSB 3-0 shift left 4 places

      Wire.beginTransmission(MCP4725B); //address device
      Wire.write(buff[0]); //pointer
      Wire.write(buff[1]); //8 MSB
      Wire.write(buff[2]); //4 LSB
      Wire.endTransmission();

      Serial.println("=============================");
      Serial.println("=============================");
      Serial.println("========= Volt Test =========");
      Serial.println("test: " + String(set_voltage));
      Serial.println("      " + String(real_output2));
      Serial.println("======== Current Test =======");
      Serial.println("test: " + String(set_curr));
      Serial.println("      " + String(real_curr));
      Serial.println("=============================");
      Serial.println("=============================");
    }
    }

body:
The `if` statements (plural) you [posted on GitHub][1] are a lot different to the one you posted above. They contain a lot of of `print` commands to the LCD, so I think this is what is slowing your code down. It's a fair effort at nicely formatting the output on the display, but is rather convoluted.

Here is a simplified version which writes to the LCD as little as possible (2 cursor moves and 2 prints). The formatting of the string is done in Arduino memory before sending it out to the LCD as one complete string.

I couldn't understand your variable names, so I've renamed them.

setup()
=======
I moved the `analogReadResolution(12)` from `loop()` to `setup()` for a slight performance gain.
```c++
void setup()
{
  pinMode(currsensPin , INPUT_ANALOG);
  pinMode(voltsensPin , INPUT_ANALOG);
  pinMode(voltPin, INPUT_ANALOG);
  pinMode(currPin, INPUT_ANALOG);
  Wire.begin();
  lcd0.begin(20, 4);
  lcd0.backlight();

  analogReadResolution(12);  // Moved from loop(). Only need to call it once.

  Serial.begin(115200);
}
```
loop()
======
I've grouped the analogue reads together to give a smaller sampling window. Since it's for a control loop, these values should ideally be sampled at exactly the same time and synchronised to a clock (e.g. in hardware).
```c++
float real_current_offset = 0;

void loop()
{
  //
  // Obtain data samples as close together as possible with no interrupts.
  //
  cli();  // Disable interrupts.
  int svolt = analogRead(voltPin);
  int scurr = analogRead(currPin);
  int raw_voltage = analogRead(voltsensPin);
  int raw_current = analogRead(currsensPin);
  sei();  // Enable interrupts.

  // Calculate set voltage and current.
  float set_voltage = (3.3 / 4096) * svolt;
  float set_current =  (3.3 / 4096) * scurr;

  // Calculate real voltage and current.
  float real_voltage = (3.3 / 4096) * raw_voltage;
  float real_current = raw_current * (3.3 / 4096) - real_current_offset;
  float real_current_ma = real_current * 1000.0;

  int dac_value = dac_value
              + (real_current <= set_current) * (set_voltage > real_voltage)
              - (real_current < set_current) * (set_voltage < real_voltage)
              - (real_current > set_current);

  buffer[0] = 0b01000000;
  buffer[1] = dac_value >> 4;
  buffer[2] = dac_value << 4;
  Wire.beginTransmission(MCP4725);
  Wire.write(buffer[0]);
  Wire.write(buffer[1]);
  Wire.write(buffer[2]);
  Wire.endTransmission();

  DisplayDataOnLcd(set_voltage, set_current, real_voltage, real_current);
}
```
DisplayDataOnLcd()
==================
I created a new function for displaying the data on the LCD. It's good practice to break the code down into smaller functional blocks.
```c++
void DisplayDataOnLcd(const int set_voltage, const int set_current, const int real_voltage, const int real_current)
{
  Serial.println("\nLCD Data Display");

  // Define the formats for printing to the LCD.
  const char *data_format_set  = "Set : %s V %s mA";
  const char *data_format_real = "Real: %s V %s mA";
  char voltage_str[10];
  char current_str[10];
  char data_str[30];

  // Format the set voltage and current, and display on the LCD.
  dtostrf(set_voltage, 6, 3, voltage_str);
  dtostrf(set_current, 6, 3, current_str);
  sprintf(data_str, data_format_set, voltage_str, current_str);
  lcd0.setCursor(0, 0);
  lcd0.println(data_str);
  Serial.println(data_str);

  // Format the real voltage and current, and display on the LCD.
  dtostrf(real_voltage, 6, 3, voltage_str);
  dtostrf(real_current, 6, 3, current_str);
  sprintf(data_str, data_format_real, voltage_str, current_str);
  lcd0.setCursor(0, 1);
  lcd0.println(data_str);
  Serial.println(data_str);
}
```

  [1]: https://github.com/mariusdp/psu_test/blob/master/main.cpp


message:
Saving a value with a click

I have a rotary encoder and 2 buttons to a. Store the encoder value b. Reset the encoder value to 0. The reset buttons work fine the issue is with the set/store button. Where the value changes without pressing the button as well. Any help is appreciated.

    int encoderPin1 = 2;
    int encoderPin2 = 3;

    volatile int lastEncoded = 0;
    volatile double encoderValue = 0;
    long lastencoderValue = 0;

    int lastMSB = 0;
    int lastLSB = 0;

    // buttons
    int resetPin = 43;
    int settPin = 22;
    int val = 0;
    int val2 = 0;

    //reset-set
    double setValue = 0.0;
    double resetValue = 0.0;

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

      pinMode(encoderPin1, INPUT);
      pinMode(encoderPin2, INPUT);

      digitalWrite(encoderPin1, HIGH);
      digitalWrite(encoderPin2, HIGH);

      attachInterrupt(0, updateEncoder, CHANGE);
      attachInterrupt(1, updateEncoder, CHANGE);

      //buttons
      pinMode(resetPin, INPUT);
      pinMode(settPin, INPUT);

      pinMode(LED_BUILTIN, OUTPUT);

    }
    void loop(){
      //Serial.println(encoderValue); //print
      delay(1000);

      //
    val = digitalRead(settPin);
    if (val == HIGH){
      set();
      digitalWrite(LED_BUILTIN, HIGH);
    }

    /*val2 = digitalRead(resetPin);
    if (val2 == HIGH){
      //reset
      encoderValue = resetValue;
      Serial.println(encoderValue);
      Serial.print("reset");
      delay(100);
    }*/

    }

    void set(){
      //set the value
      setValue = encoderValue;
      Serial.println(setValue);
      Serial.print("setValue");
      delay(100);
    }

     void updateEncoder(){
      int MSB = digitalRead(encoderPin1);
      int LSB = digitalRead(encoderPin2);

      int encoded = (MSB << 1) |LSB;
      int sum = (lastEncoded << 2) | encoded;

      if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
      if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

      lastEncoded = encoded;
      }

body: thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!


message:
My motor driver gets stuck in either high or low with a certain speed super randomly. Motor output stops going based on accelerometer input

Running a DC motor(6.5A max input), motor driver (MD10C 7Amp peak output), and arduino Mega.
Basically, I am creating a stabilized object based on the accelerometer's input. It works great but all of a sudden, very randomly, it glitches and gets stuck in whatever mode it was in last, so if it was motor A HIGH and motor B LOW at speed 200, itll just do that and I have to unplug it, put in a blank code, then my code again, then start it, itll work great then do it all over again. The time it takes for it to glitch out is random, I can't seem to find any patterns to it.
here is my code

```
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19,18);

//I2C address of the MPU-6050
const int MPU_addr=0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 200 Hz              = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR
volatile bool isr_flag = false;  //Used to flag when the ISR when triggered
volatile unsigned long isr_time = 0;  //Input updated by ISR
volatile byte isr_motor_direction; //Output calculated and updated in loop()
volatile byte isr_motor_speed = 0; // Output calculated and updated in loop()

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral=0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//change speeds of the motor
#define MOTOR_SPEED_PIN    3
//change direction of the motor
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);

  pinMode(MOTOR_SPEED_PIN, OUTPUT);
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
    //Begin critical section
    //

    cli();
    bool flag = isr_flag; //Copy the ISR flag
    isr_flag = false; //Reset the ISR flag
    sei();

    //
    //End critical section

    if (flag == true)
    {
      DebugMsgTime("PID algorithm begin");

      //Begin critical section
      //

      //Getting a copy of the data that has been modified by the ISR
      cli();
      unsigned long time = isr_time;
      sei();

      //
      //End critical section

      static unsigned long previous_time = 0;
      previous_time = time;

      //Wire reading

      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);

      //reading each of the 6 axis's of the MPU6050 and the temp
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      //Only using AcY
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();

      //mapping AcY to yAng from accel units to degrees
      yAng = map(AcY, -17000, 17000, -90, 90);

      //Calculate motor parameters locally
      long pos = PID(yAng);
      byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW //make sure that this is correct
      pos = abs(pos);
      pos = constrain(pos, 0, 100);
      byte motor_speed = map(pos, 0, 100, 0, 200);

      //Begin Critical Section
      //

      // Update the ISR data ready for output at the next interrupt.
      // This keeps the outputs locked to each other and synchronised to the interrupt.
      cli();
      isr_motor_direction = motor_direction;
      isr_motor_speed = motor_speed;
      sei();

      //
      //End Critical Section

      DebugMsgTime("PID algorithm end");
    }
}

ISR(TIMER1_COMPA_vect)
{
  //Output
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  //Input
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
    error = setpoint - currentTheta;
    integral = integral + error*dt;
    deriv = (error-previousError)/dt;
    long output = 1.9 * error; + .8 * integral + 40 * deriv; //2.8,.7,70 //1.3,.8,40
    previousError = error;
    return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}
```

body:
What happens if the `while` condition fails? i.e. if `millis() - time` is greater than or equal to 20. Is this what you intended? If there's too much other stuff in the `while` loop, it may quit it **and never re-enter it**.

loop()
======
I've added a call to a function that prints debug information.
```c++
unsigned long time = 0;

void loop()
{
  DebugMsgTime("loop() begin");

  while (millis() - time < 20)
  {
    DebugMsgTime("while begin");

    time = millis();

    //delay(10);  // Short delay OK.
    delay(20);  // Long delay causes while loop to quit.

    DebugMsgTime("while end");
  }
  DebugMsgTime("loop() end");
}
```

DebugMsgTime()
==============
This function prints a message along with the current time and the delta time since it was last called.
```c++
void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = millis();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}
```

Debug Output
============

> It works great but all of a sudden, very randomly, it glitches and
> gets stuck in whatever mode it was in last

```none
Basic Encoder Test:
loop() begin
0
0
while begin  // It works great...
1
1
while end
2
1
while begin
12
10
while end
34
22           // but all of a sudden, very randomly, it glitches...
loop() end   // and gets stuck in whatever mode it was in last
54
20
loop() begin
74
20
loop() end
97
23
loop() begin
118
21
loop() end
```
As you can see, using this `while` loop is a very inaccurate way to generate regular sampling times.

loop() FIX
==========
As @FerryBig pointed out in the comments, you need to change the time comparison `<` at the start of the loop. You also don't need the `while` loop because `loop()` is already called cyclically. Instead, put the time comparison in an `if` statement, something like this which gives you a rough 20 ms:

```c++
void loop()
{
  static unsigned long previous_time = 0;
  unsigned long time = millis();
  unsigned long delta_time = time - previous_time;

  if (delta_time >= 20)
  {
    previous_time = time;

    // Do PID algorithm.
  }
}
```
However, for a PID controller you may need more accuracy.

Timer Interrupt
===============
A better method would be to use a timer interrupt to call an Interrupt Service Routine (ISR) at regular intervals. This ISR would do two simple things in this order:

 1. Output: `digitalWrite(motor_direction);` and `analogWrite(3, mtr2);`
 2. Input: set a flag that indicates that the gyro Wire needs reading.

Then, when the flag is set, the main `loop()` would read the gyro Wire, and calculate `motor_direction` and `mtr2` in readiness for the next interrupt.

```c++
const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 10 Hz              = 25000
const uint16_t t1_comp = 25000;

volatile bool isr_flag = false;       // Used to flag when the ISR has updated the data.
volatile unsigned long isr_time = 0;  // The data.

void setup()
{
  // Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Serial.begin(9600);
}

void loop()
{
  //
  // BEGIN CRITICAL SECTION (Atomic)
  //

  cli();
  bool flag = isr_flag;  // Copy the ISR flag.
  isr_flag = false;      // Reset the ISR flag.
  sei();

  //
  // END CRITICAL SECTION
  //

  Serial.println(flag);

  if (flag == true)
  {
    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Get a copy of the data that has been modified by the ISR.
    cli();
    unsigned long time = isr_time;
    sei();

    //
    // END CRITICAL SECTION
    //

    static unsigned long previous_time = 0;
    Serial.println(time - previous_time);
    previous_time = time;
  }

  delay(25);
}

ISR(TIMER1_COMPA_vect)
{
  //TCNT1 = t1_load;  // No need to reload here because it auto reloads.
  isr_time = micros();
  isr_flag = true;  // Indicate that new data is available.
}
```

PID Controller
==============
This is the full implementation of the PID controller. It should give you a solid foundation to develop the PID algorithm for your motor, and to filter the gyro inputs.
```c++
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19, 18);

//I2C address of the MPU-6050 idk if i need
const int MPU_addr = 0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 10 Hz              = 25000
//const uint16_t t1_comp = 25000;

// If the PID algorithm takes less than 5 ms, it's possible to run Timer1 at a maximum of about 200 Hz.
// 16 MHz          / 64        / 200 Hz             = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR.
volatile bool          isr_flag = false;            // Used to flag when the ISR has triggered.
volatile unsigned long isr_time = 0;                // Input updated by ISR.
volatile byte          isr_motor_direction = LOW;   // Output calculated and updated in loop().
volatile byte          isr_motor_speed = 0;         // Output calculated and updated in loop().

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral = 0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//this is the enable pin (PWM) to run speeds to the motor
#define MOTOR_SPEED_PIN         3

//change direction of the motor
// TODO: Check whether LOW and HIGH are correct.
#define MOTOR_DIRECTION_PIN     2
#define MOTOR_DIRECTION_CW      LOW
#define MOTOR_DIRECTION_CCW     HIGH

void setup()
{
  // Disable global interrupt.
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);
  Serial.println("Basic Encoder Test:");

  //pinMode(MOTOR_SPEED_PIN, OUTPUT);  // Not needed for analogWrite().
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
  //
  // BEGIN CRITICAL SECTION (Atomic)
  //

  cli();
  bool flag = isr_flag;  // Copy the ISR flag.
  isr_flag = false;      // Reset the ISR flag.
  sei();

  //
  // END CRITICAL SECTION
  //

  //Serial.println(flag);

  if (flag == true)
  {
    DebugMsgTime("PID algorithm begin");

    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Get a copy of the data that has been modified by the ISR.
    cli();
    unsigned long time = isr_time;
    sei();

    //
    // END CRITICAL SECTION
    //

    static unsigned long previous_time = 0;
    //Serial.println(time);
    //Serial.println(time - previous_time);
    previous_time = time;

    //
    // Read gyro Wire.
    //

    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true);

    //reading each of the 6 axis's of the MPU6050 and the temp
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    //Only using AcY
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read();

    //mapping AcY to yAng from accel units to degrees
    yAng = map(AcY, -17000, 17000, -90, 90);

    //
    // Calculate motor parameters locally.
    //

    long pos = PID(yAng);
    byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW;  // TODO: Check whether defines are correct.
    pos = abs(pos);
    pos = constrain(pos, 0, 100);
    byte motor_speed = map(pos, 0, 100, 0, 200);

    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Update the ISR data ready for output at the next interrupt.
    // This keeps the outputs locked to each other and synchronised to the interrupt.
    cli();
    isr_motor_direction = motor_direction;
    isr_motor_speed = motor_speed;
    sei();

    //
    // END CRITICAL SECTION
    //

    DebugMsgTime("PID algorithm end");
  }

  //delay(1);
}

ISR(TIMER1_COMPA_vect)
{
  // Output.
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  // Input.
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
  error = setpoint - currentTheta;
  integral = integral + error * dt;
  deriv = (error - previousError) / dt;
  long output = 1.9 * error + .8 * integral + 40 * deriv; //2.8,.7,70 //1.3,.8,40
  previousError = error;
  return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}
```
And I think there might be a typo in your PID controller:
```c++
long PID(int currentTheta)
{
    ...
    long output = 1.9*error; + .8*integral + 40*deriv;
                           |
                         typo?
```
This is equivalent to:
```c++
    long output = 1.9*error;
```
Which is not a PID controller.


message:
Converting from Float to Int yielding weird results. What am I doing wrong?

So I am trying to take GPS data with a Neo 6M gpsmodule (that is what is covered up by the square for privacy sake) and process it by adding/multiplying to get large integers representing the GPS data. This is using Arduino nano. When I try and convert the float numbers to integers, it gives me totally different numbers. 1242895 turns into -2289, and 611194 turns into 21370. I have tried so many things, but am stumped as to what is going on. Is it related to pointing? It's been awhile since I learned about pointers in my C++ class. X and Y are initialized as int global variables.

[![float to int issue][1]][1]

  [1]: https://i.stack.imgur.com/7ecjz.png

body:
On an Arduino board with the 328 processor, an INT is stored as a 2 byte value, so the max number is 32,767.

You want to use a LONG which is a 4 byte number which has a max of 2,147,483,647.

When the variable you are using is not big enough, the number rolls over, which is why you end up getting a negative number.


message:
Maintain constant PWM voltage with changing Vcc

I am making an arduino project with a single lithium ion battery, and want to be able to maintain a constant PWM voltage, even when the battery goes from 4.2-3.2v. I have been able to read the Vcc using the internal 1.1v reference, so I am wondering if I can make some sort of feedback system to increase the duty cycle when the battery discharges, in order to keep the same average voltage on the PWM. I want to be able to make it 3.2v constant, which should be attainable on Vcc from 4.2-3.2, with 100% duty cycle when the battery is at 3.2v.

body:
Simple:
```duty =  (3.2 / vcc) * 255;```


message:
Problem with programming digispark ATtiny85 board with Arduino IDE

I have bought a Digispark ATtiny85 board to learn about that microcontroller. So I tried using internal register names in the code rather than using Arduino in built functions. I can get the board to work when comes just input and output operations. For example the below code works and I can get the on board LED to turn ON and OFF

    #include<avr/io.h>
    void setup()
    {
      DDRB |=(1 << PB1);  //set PB1 as output
    }
    void loop() {
     PORTB |= (1 << PB1);    // Turning ON LED connected to PB1
     delay(1000);            //Using Arduino IDE inbuilt delay function to generate delay of 1 second
     PORTB &= ~(1 << PB1);   //Turning the LED off
     delay(1000);
}

I have tried using Timer0 of ATtiny85 module to generate time delay of one second. But unfortunately I couldn't get it to work.

    #include<avr/io.h>
    #define F_CPU 16500000UL
    #include<util/delay.h>

    void timer_config()
    {
     DDRB =0b00000010; // set PB1 as output
     GTCCR|= (1<<TSM);      ///Halt the timer for configuration
     TCCR0A=0x00;             //Normal mode
     TCCR0B=0x00;
     TCCR0B |= (1<<CS00)|(1<<CS02);   //prescaling with 1024
     TCNT0=0;
     GTCCR&=~(1<<TSM); //Start the timer
    }

    void tmdel()
    {
     int i=0;
     while(i<=6)
     {
      while((TIFR & (1 << TOV0) )==0);        //Waiting for 0-255 and flag to raise
      TIFR|=(1<<TOV0);      //Clear the flag
      i=i++;                          //increment by one
     }
    }

    int main()
    {
     timer_config();
     while(1)
     {
      PORTB|=(1<<PB1);     //PortB1 high
      tmdel();                         //Delay of 1 second
      PORTB&=~(1<<PB1);     //PORTB1 low
      tmdel();
     }
    }

I have used the overflow flag to identify TCNT0 register status. I have uploaded the above code but the LED isn't responding as anticipated.

When searching the internet I have got few suggestions that this might be because Arduino IDE uses timer registers for delay function. When user attempts to access timer registers it might not work as intended.

But am not sure about the validity of above opinion. Can anyone help me with it? Since am learning this controller, practicing core programming is quite important. If I cannot program ATtiny85 using Arduino IDE this way, can someone suggest a way or alternate hardware setup to program ATtiny85 and access its registers without a problem.

body:
>      i=i++;                          //increment by one

The result of the above statement is **not defined**. That is, it is not necessarily "i + 1".

See:

* http://en.wikipedia.org/wiki/Sequence_point
* http://c-faq.com/expr/seqpoints.html

Instead use:

    i++;

Or:

    i = i + 1;

A note about "undefined behavior":

http://en.wikipedia.org/wiki/Undefined_behavior

> When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.


message:
Error "cstddef: No such file or directory" on use AzureIoTHub

Good Morning
I'm trying to integrate with Azure IoT with Arduino Mega 2560.
I imported the AzureIoTHub and AzureIoTUtility lib.

I just created this part of the code

     #include <AzureIoTHub.h>

    void setup() {
      // put your setup code here, to run once:

    }

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

    }

however, when I compile, I get the following error message.

> In file included from
> C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/platform.h:7:0,
>                  from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/AzureIoTUtility.h:7,
>                  from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTHub\src/AzureIoTHub.h:7,
>                  from D:\Documents\Dev\Pocos\Arduino\ArduinoSolution\ArduinoSolution.ino\WiFiPoco\RoboCore\azureHub\azureHub.ino:3:
> C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/strings.h:8:10:
> fatal error: cstddef: No such file or directory  #include <cstddef>

I imported ArduinoStl and the problem continued.

what am i doing wrong in this case?

thanks

body:
Azure IoT is only supported on ESP8266 and ESP32. As stated in the [README](https://github.com/Azure/azure-iot-arduino/blob/master/README.md) for the library:

> Currently supported hardware:
>
> - ESP8266 based boards with [esp8266/arduino](https://github.com/esp8266/arduino)
>
>   - SparkFun [Thing](https://www.sparkfun.com/products/13711)
>
>   - Adafruit [Feather Huzzah](https://www.adafruit.com/products/2821)
>
> - ESP32 based boards with [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
>
>   - Adafruit [HUZZAH32](https://www.adafruit.com/product/3405)


message:
Will Setting Interrupt Pin High Damage Bluetooth Module?

I want my HC05 Bluetooth Module to trigger an interrupt when it receives a signal. So I've followed suggestions from the Arduino Forum and connected the Bluetooth TXD pin to the Arduino RX Pin and the Interrupt Pin (2), which I set to high. It is set to detect a `FALLING` voltage, presumably when BT transfers data. When I connected it this way a funny thing happens. I can clearly see that the interrupt is being called because power consumptions goes way up when Android sends a message to BT module, meaning the device wakes up. However the serial port no longer appears to work on the Nano. I think I narrowed down the possible cause to me damaging the board by removing lineage regulator or damaging serial port somehow with the interrupt. Is the way I wired up the interrupt pin as described correct? Your help would really help me narrow down my problem.

    #include <avr/sleep.h>

    #define ledPin 7
    #define intPin 3
    int state = 0;
    int stateData = 0;
    int ultraPin = 10;
    int trigPin = 11;    // Trigger
    int echoPin = 12;    // Echo
    long duration, cm;
    unsigned char inches;
    unsigned long timer;

    void setup() {
      pinMode(ultraPin, OUTPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(intPin, INPUT);
      digitalWrite(intPin, HIGH);
      attachInterrupt(digitalPinToInterrupt(intPin), interrupt, FALLING);
      digitalWrite(ultraPin, LOW);
      Serial.begin(9600); // Default communication rate of the Bluetooth module
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sleep_cpu();
    }

    void interrupt(){
      Serial.println("interrupted");
      sleep_disable();
      Serial.write(50);
      delay(500);
      timer = millis();
      digitalWrite(ultraPin, HIGH);
      while (true){
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2);
          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(trigPin, LOW);
          pinMode(echoPin, INPUT);
          duration = pulseIn(echoPin, HIGH);
          cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
          inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
          Serial.write(inches);
          delay(50);
          stateData = Serial.read();
          if (stateData != 49){
            // receipt from android
            unsigned long timeElapse = millis() - timer;
            if (timeElapse > 5000) {
              break; // exit and SLEEP
            }
          }
          else {
              // reset the timer
              timer = millis();
            }
          }
        sleep_enable();
        sleep_cpu();
    }

    void loop() {

    }

body:
I'm not sure, if you can rule out the hardware damage (you wrote, that you removed the linear voltage regulator, but didn't explain more there). But with that code you won't get what you want.

I see multiple issues, all boiling down to the same problem: You cannot do that inside of an ISR:

- `delay()` relies on interrupts to happen during its execution. As of my knowledge this leads to `delay()` never ending, blocking your code. Also it is very bad design to have a long running ISR. So much is depending on interrupts to work and when you have something long running, you can just easily do that inside the main code, triggered by an interrupt flag variable.
- `millis()` will not increment during the run of the ISR.
- `delayMicroseconds()` will work, but you still should keep the ISR very short. Reading an ultrasonic sensor is a no-go.
- `Serial.write()` will fill the libraries internal TX buffer, but the actual transmission of the data also relies on interrupts. You won't get your data that way.

Instead of doing all that inside the ISR, you should just let the Arduino wake up, then set a (single byte) flag variable. In your main code you need to check for that flag with an if statement. In that if statement, you are doing all what you need to do and at the end you are resetting the flag and going to sleep again.


message:
How to wire a three-pin on-off-on switch for reading input?

I would like to read the output of an on-off-on switch with my Leonardo board, but I have very little knowledge of electronics and don't know how to wire it up.

This is the switch in question: [E-Switch 200MSP4T1B1M1QE][1]

The switch has three pins. Generic three-pin SPDT wiring diagrams I've found suggest that the two outer pins should be connected to separate lights and the middle pin should be connected to the power source. Those lights also have a ground connection.

I don't want to power anything in a literal sense, I only want to have the Leonardo read the output of the switch. The end goal is to have the two ON positions read as separate button presses (eventually using a joystick library, in case that changes how the switch needs to be wired).

My questions are:
1. Is the above wiring example correct for my use case?
2. Is the output of the switch considered digital or analog?
3. Is a wire from the switch to GND not required?

One final note - I'm not using a breadboard, but connecting the wires directly from the switch to the board.

  [1]: https://www.digikey.ca/en/products/detail/e-switch/200MSP4T1B1M1QE/3777910

body:
You talk about wiring a switch to control lights directly. Instead, you want to use your switch to send information to your Arduino.

You link to an SPDT (single pole, double throw) switch. When flipped one way, it connects the center pin to one of the outside pins, and when flipped the other way, it connects the center pin to the other outside pin.

If you want the Leonardo to read the state of the switch as 2 separate switches/button presses, wire the 2 outer pins of the switch to 2 separate digital inputs on the Arduino.

You need to force each input to either ground or +5V when it's not connected to anything, or it will "float" and you'll get semi-random high and low readings.

I suggest setting the Arduino input pins to INPUT_PULLUP mode. That connects the inputs internally through a resistor to +5V. If you don't connect anything to the pin, it reads as HIGH. When the button is pressed/switch is closed, it reads LOW. That might seem a little confusing, but it means you don't need external resistors.

You'd then attach those to pins to the two outer pins of your switch, and attach the center pin to ground (GND).

If you flip the switch one way, it would connect one outer pin to the center pin. That would connect that Arduino pin to ground, and the reading on the pin would drop from HIGH to LOW. Flip the switch the other way and it would connect the other pin to ground, at that other pin would drop from HIGH to LOW.

It is also possible to wire your switches using INPUT mode, not INPUT_PULLUP, and have them read LOW when the switch is open, and HIGH when closed, but to do that you'll need external pull-down resistors. (And wiring it will be a little painful without a breadboard or PC board.)

To answer your questions:

1. Is the above wiring example correct for my use case?

You don't show a wiring example. You talk about how to wire a switch to switch power to a pair of lights directly, without using a microcontroller. That's not relevant here.

2. Is the output of the switch considered digital or analog?

It would make sense to use it as a digital input, since you need it to give you 2 states, open and closed.

3. Is a wire from the switch to GND not required?

You need to connect the center pin to either ground +5V, as discussed above.


body:
I suggest this simple circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/qzj4K.png)

<!-- End schematic -->

Set both inputs to `INPUT_PULLUP`. If the input reads `LOW`, that means it has been grounded by the switch.

---

**Edit**: Per Duncan’s request, here is the alternative circuit with the polarities inverted. With the switch’s common connected to Vcc, the inputs should be set to `INPUT_PULLDOWN`. However, most Arduinos do not support this mode, for lack of internal pull-downs. Then one has to use external pull-downs instead, and set the pins to `INPUT`.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/nMBOZ.png)

<!-- End schematic -->

With this circuit, a pin reads `HIGH` when it is connected to +5V by the switch.


message:
Passing a time_t array as a function parameter

I'm trying to log reconnections and disconnections of a network. For that I've created 2 `time_t` arrays to store such occurances:

    const int logSize = 10;
    time_t conLog[logSize];
    time_t disconLog[logSize];

Now, down the road, I have some manipulation and time calculation to do, and for that I wish to pass those log as a variable.

For example - zeroing its values:

    void initLog(time_t log[], time_t init_val = 0)
    {
            int sizeLog = sizeof(log) / sizeof(log[0]);
            Serial.print("size: ");
            Serial.println(sizeLog);
            for (int i = 0; i < sizeLog; i++)
            {
                    log[i] = init_val;
            }
    }

in order using it in a simple way : `initLog(conLog);`
But unfortunately this is wrong.

I've tried to replace `time_t log[]` with `time_t &log` - but still no luck.

What do I do wrong ?

body:
When you pass an array to a function it "collapses" the array into just a pointer. All the receiving function knows is the type of the contents of the array (`time_t`) and where it starts in memory - it knows nothing about the size of the array.

The `sizeof()` call just gives you the size of that pointer, not the size of the memory it points to.

`sizeof()` is not actually a function, it's a compile-time construct. It can't know anything about runtime values, only what is there at compile time.

Instead you must pass the length of the array with the array as a separate parameter, which can only be calculated in the same scope as where the array is defined, and then only by using the original name of the array.  It is typical to create a macro to do this for you at the time you make the array:

```
time_t conLog[logSize];
#define CONLOG_SIZE (sizeof(conLog) / sizeof(conLog[0]))
```

Then pass that to your function:

```
initLog(conLog, CONLOG_SIZE);
```

Alternatively, since you already have the size in a constant in this case, you could just use that:

```
initLog(conLog, logSize);
```


message:
Wave file will not play with Teensy 3.5

I am attempting to play a wav file from an SD card using a Teensy 3.5. I am using [this buzzer][1] and I have the following code currently:

    #include <Audio.h>
    #include <Wire.h>
    #include <SPI.h>
    #include <SD.h>
    #include <SerialFlash.h>

    // GUItool: begin automatically generated code
    AudioPlaySdWav           playSdWav1;     //xy=557,157
    AudioOutputPWM           pwm1;           //xy=889,184
    AudioConnection          patchCord1(playSdWav1, 0, pwm1, 0);
    AudioConnection          patchCord2(playSdWav1, 1, pwm1, 0);
    // GUItool: end automatically generated code

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

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println("Play");
      playSdWav1.play("sound.wav");
      delay(100);
      while (playSdWav1.isPlaying()) {
        delay (100);
      }
    }

I don't know which pin is supposed to be outputting the PWM signal. I tried searching "patchCord1" to see what the parameters for it are, but was unsuccessful. The code was generated by [The Audio System Design Tool.][2]

As for the hardware configuration, I am attempting to wire the `I/O` pin to various PWM pins (to check for output) with no success. I have `GND` to Analog Ground and `VCC` to 3.3V (250 mA max). This is according to [this diagram][3].

Which PIN is the Teensy supposed to output the pulses to?

Edit:

I can get the buzzer to work by using manual PWM (analogWrite), so I know that it functions.

  [1]: https://www.amazon.com/gp/product/B085XQM69Z/
  [2]: https://www.pjrc.com/teensy/gui/index.html
  [3]: https://cdn-shop.adafruit.com/970x728/3267-04.jpg

body:
The documentation implies you have to combine pins 3 and 4.

Here is a circuit diagram:

https://www.pjrc.com/teensy/gui/img/pwmdualcircuit.jpg

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/41zMc.jpg

Source:

https://www.pjrc.com/teensy/gui/?info=AudioOutputPWM


message:
BJT - BC547 not working with LED strip

I'm connecting an LED strip that takes 12V input to an `Arduino Uno R3`'s `5V` VCC using a `B547` transistor.

Here's my circuit:

    Base -> 1K ohm resistor -> DO13
    Collector -> -ve of LED strip
    Emitter -> GND
    VCC 5V -> +ve of LED strip
Nothing happens when I try to turn on the LED strip. However if I remove the 1K resistor and turn on the LED, Arduino's built in LED gets dimmer but the LED strip does not turn on.

What am I doing wrong?

TIA!

body:
Ok. First off, if you have a 12V LED strip then you have to power it from 12V. Powering the Arduino from 12V and then powering the LED strip from the 5V pin of the Arduino is *not* powering the LED strip from 12V, it's powering the Arduino from 12V and the LED strip from 5V.

The LED strip's anode (+) must be connected to the + of the 12V supply or, if it's only a very short LED strip then you can use VIN on the Arduino.

LED strips typically have a number of LEDs (eg 3) in series with a resistor to make one "segment", and many "segments" in parallel. This gives a total forward voltage of typically 9V or more - so you must provide *at least* that to get the LEDs to light.

Secondly the BC547 is not a good transistor to use for switching an LED strip.  It has a maximum continuous collector current of 100mA. That means that you can only have a maximum of 100mA going through your LED strip before the transistor blows.

For reference, 100mA is the equivalent of 5 "normal" (5mm, of the kind you'd use in a breadboard) LEDs at full current and brightness. A typical LED strip (depending on length) can use many hundreds or thousands of mA.

Really you should be using an N-channel MOSFET that is rated for *at least* as much current as your LED strip requires to run. For safety, and to reduce heat dissipation, you ideally want it to be many times more powerful than the LED strip needs.

A common choice is the IRF530, which is rated at 10A with a switching voltage (the "threshold" voltage) that is low enough for a 5V Arduino to control (there are more suitable ones, but these seem to be the "go-to" component for many Arduino users - they're adequate for most uses).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/hSkWC.png)

<!-- End schematic -->


message:
How to turn the digital pin to analog pin?

I am using a 10 IR sensor array and they use analog pins. I am using a motor shield for the Uno. So I cannot use the Mega. I have only five analog pins I need 8. How can I do it?

body: You can use an external A/D converter, there are a lot of varieties in a lot of price ranges for the Arduino. Check your favorite online source. That will require two of your existing analog pins for the I2C interface but you will gain back many more depending on your choice. If you choose to use SPI that will take 4 pins.


message:
I am getting an error while trying to set up the U8g2 library

I am just trying to set up the U8g2 library to use an OLED. I read through the documentation and tried copying and pasting the code block example for the constructor, but switched out their information for my OLED's information. After trying to verify, the IDE returned this error:
exit status 1
expected ')' before ',' token
```#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C(U8G2_R0,A5,A4);```

I saw a similar post about this problem from four years ago, but the only suggestion on there was to capitalize the "A" in the analog pins. I tried this and nothing changed. Any help would be much appreciated!

body:
I figured out what I was doing wrong. I was copying the name from the Constructor Reference and immediately inputting the arguments in parentheses. I needed to put u8g2 after the constructor name and then put the arguments. Thanks!

The corrected code is as follows:
```
#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0,A5,A4);
```


message:
8266 analogRead(A0) always 1024

dear member.
I have 4 ESP-12 averything OK but one chip behave weird.
always return 1024 on analogRead(A0);
once use ADC_MODE(ADC_VCC) and reflash using ADC_MODE(ADC_TOUT); and never back to normal, is my Chip Error..?

FM 4MB

ArduinoIDE 1.8.13

BR 115200

PS 80MHz

    int iVal = 0;
    void setup() {
      Serial.begin(115200);
      delay(999);
      pinMode(A0,INPUT) ;
      pinMode(LED_BUILTIN, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      iVal=analogRead(A0);
      Serial.println(iVal);

      if (iVal > 900) digitalWrite(LED_BUILTIN,HIGH);
      else   digitalWrite(LED_BUILTIN,LOW);
      delay(720);
    }

body: First be sure your voltage on the analog input is less then 1V and greater then zero, that is the range for the input. If nothing connected no guarantee what you will get. Just guessing, no circuit or definition.


message:
Make the Arduino read data from the PC

I will be brief. There is as windows PC running a program. This program has live updating data on it. Without modifying the PC or adding any programs to the PC, is it possible to program an Arduino to read specific data from this program. In other words the Arduino would be connected to the PC via a USB port and it would need to actively read specific data from this program without having to modify the PC in any way, software or otherwise. I do have access to the PC and can learn almost anything I need to about the program during the development of this system, however in practice, I need the Arduino to simply be plugged into this PC and begin reading its data. Is this possible?  I am not asking for a tutorial however if you could point me in the right direction that would be great.
Thanks

body:
As the comments already stated: No, not possible. For multiple reasons:

- USB is a master/slave protocol. The slave (here the Arduino) cannot do anything without the master. It can just expose it's data endpoints and hold data ready to read at these endpoints for the master or wait for data from the master on these endpoints. When the application on the PC is not programmed to speak over USB, you cannot get the data over USB.

- Even directly on the PC you cannot simply extract data from a different program. That would be a very huge security risk. Even more, when just initiated via an USB device. There are USB devices, which use certain behaviors of some OS's (like auto execution of specific types) to install a virus on the PC. But even then you cannot "just read" the data. It would be way more elaborate and not possible with a simple Arduino, thus off topic here. (And you might frown upon hacking your own PC this way)

From our point of view (means leaving the hacking off limits), I would aggree with Majenko in the comments. Using the visual output is the most viable and easy solution, though your results might vary.

For that you would need a camera pointing at the screen (check if you get a good image. It might be distorted due to slow refreshing...) and use a Raspberry Pi or similar to connect it. On the Pi you can then take pictures of the screen and use an OCR tool, which will read the text from the image. Then you need to extract and structure the relevant information. (Maybe it will be easier to create subimages in your program and let the OCR tool run over these to distiguish between the different data parts). Results will hardly depend on the quality of the image. If you can live with an additional program running the PC, you could instead make the images of the screen as screenshots, which will be way better quality. Though at that point you can also put the rest of the logic on the PC and just remove the Pi.

This way will still be hard to do for a beginner, but possible.


message:
how to ignore a sensor being tripped the first time and start recording millis on the 2nd time it is tripped

I am building a timing system that has a start, split and finish beams with this I am using a start gate that will drop when the race starts. when it drops it will trip the 1st sensor starting to count the millis which I am using to calculate the time. I am using IR sensors to that give me the 3 times based on the millis and then I do a calculation in excel that will give me the split and finish time.

Where I am running into issues is that after the person goes through the 3 timer sensors I have to close the start gate which trips the first sensor which messes up my times for the next person.

So I need to adjust my sketch so it takes this into consideration when it starts counting the millis. Basically I am thinking it needs a line of code to have the 1st sensor == LOW once and do nothing and then on the 2nd time that same sensor is == LOW it records the millis from that point.

Below is the sketch I am working on.

    //timer
    unsigned long start, reaction, push, elapsed;

    void setup()
    {
      Serial.begin(115200);
      pinMode(2, INPUT); // start switch
      pinMode(3, INPUT); // split sensor
      pinMode(4, INPUT); // finish sensor
    }

    void loop(){

    if (digitalRead(2) == LOW)
      {

        start = millis();

      }

      if (digitalRead(3) == HIGH)
      {

        reaction = millis();
     //   delay(200); // for debounce

      }

         if (digitalRead(4)==HIGH)
          {

           push=millis();
           delay(500); // for debounce

        Serial.print(start);
        Serial.print(",");
        Serial.print(reaction);
        Serial.print(",");
        Serial.print(push);
        Serial.println();

      }

    }

body:
The start time will default to zero, so you could change it to:

    if (digitalRead(2) == LOW && start == 0)
      {

        start = millis();

      }


message:
Why do we declare constant lat and lon value

static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

What does this mean?

https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino

The above link contains the full example program of that line.

This line is from tinygps++ library for extracting the coordinates and displaying in a table format. I'm using arduino uno, GSM module and GPS module to extract the coordinates and transmit it as message. Can anyone explain what dies this constant value mean and why do we use this?

body:
It's a good idea to declare variables the strictest possible way. So if you don't intend to change the value of LONDON_LAT at runtime, declare it as **const**.

This allows the compiler to alert you if your code tries to modify it, and it often allows the compiler to optimize the code.


body:
Static variables are allocated storage only once in a program lifetime
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it and you can't change const variable's value
and i guess you know double is a data type that can save floating point numbers
that line declare two variables with names `LONDON_LAT` and `LONDON_LON` and both of them are in one line
and because london's latitiude and longtitude doesn't change the `const` keyword is used

also i guess because those variables are constants you can use `#define` visit https://www.arduino.cc/reference/en/language/structure/further-syntax/define/


message:
Noise in Analog Read Serial from an instrumentation amplifier(ina122p)

I am trying to read the values from a simple EMG circuit (with an INA122P) using the analogRead() and plotting in the plotter using an Arduino nano v3. I am powering the ina1222p from the 5v pin of the Arduino. But no matter what I do, the signal comes out very noisy most of the time(i can rarely make out the EMG). The bandpass filter is also not really helping. I am using regular solid core wire and alligator clips to connect to the electrodes.

Can someone please tell me what I am doing wrong? or tell me how to make a simple EMG circuit that uses the Arduino's analogRead().

I am also getting ac sine waves when my laptop is plugged to power, so I tried removing the power. The distinguishable sine wave wasn't really showing up, but it was still just as noisy...

**I am a beginner to both Arduinos and designing Analog circuits.**

[![enter image description here][1]][1]

I found this design from here: https://greenhecktech.wordpress.com/2016/09/19/improving-the-emg-amplifier/

  [1]: https://i.stack.imgur.com/ID0Ct.png

body:
"noisy most of the time" - good news: if it's not all the time, that's a sign it can be fixed.

"bandpass filter is also not really helping" - *INA122P circuit likely has something wrong.  check any resistors involved.* Edit: if this was about U2.2, see below as that doesn't look like a band pass...

"regular solid core wire and alligator clips to connect to the electrodes" -
basically 0 shielding with mini-rabbit ears at each end and a big loop area between the wires.
Eventually you will want something better than gator clips.
My main recommendation is that as far as wire goes, if you *form twisted pairs* they tend to be pretty darn good at rejecting noise at least for that part of the wire.  You will want to twist a signal along with its reference (such as a +V and a ground).

Some explanation of the circuit:

U2.1 is creating a 2.5V source that it uses as the reference 'ground' for U1.  Reason for this is to treat 0 as "-2.5" and 5 as "2.5" as op amp math is generally done on a +V, -V basis.  (Personally, I prefer to use voltage regulators to make power buses instead of this. As a result, I give a stink eye to circuits that use the op amp method and claim something about reducing part count.)

U2.2 is a capacitor shy of an active band pass.  It's a high pass filter that is helping preserve and even promote some of the high frequency noise you are picking up. So yes, you may wish to modify or even ditch it until you have high frequency noise under control.

If possible, you may also wish to look into operating at a higher voltage.  This can help improve your signal to noise ratio.  If your signal is essentially +/-2.5V, 250mV of noise would be 10:1, but if you can run at +/-5 V, that same 250mV noise contribution gets dwarfed 20:1.


message:
ESP-01 wakes up from deep sleep and then hangs

I have found a number of other posts from people with the same problem but I can't find an answer.

I have a small batch of ESP-01 boards, sold by Inland, and I wish to use deep sleep mode on them.

I soldered a small copper wire from pin 8 (i.e. GPIO 16) to RST.  On one board I soldered it directly, on another I soldered pin 8 and RST to two sides of a 2 pin header so I could use  jumper in case I wanted to disconnet GPIO 16 from RST.

I am flashing the following simple code (using Arduino IDE 1.8.12), which is about the simplest test of the deep sleep mode that I can think of.

    void setup()
    {
       Serial.begin(74880);
       Serial.setTimeout(2000);

       while(!Serial) { }

       Serial.println(
         "I'm awake, but I'm going into deep sleep mode for 15 seconds");

       ESP.deepSleep(15e6);
    }

    void loop() {
    }

 On starting the serial monitor shows

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 3664, room 16
    tail 0
    chksum 0xee
    csum 0xee
    v39c79d9b
    ~ld
    I'm awake, but I'm going into deep sleep mode for 15 seconds

After 15 seconds the serial monitor shows

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

and nothing else. After that the thing hangs and nothing further happens.

So,  it appears that the setup runs, the serial monitor prints the message, the mc goes into deep sleep, after 15 seconds it wakes up by a reset, but doesn't go through set up again, hence doesn't print the message or go back sleep.

Here are some comments.    The problem has nothing to do with Wifi, MQTT etc, I have tried many fancy sketches using all of these, I have same problem no matter what, the above sketched is my distillation to the simplest demonstration of the deep sleep problem.

I have flashed the program with Arduino IDE, Platform IO, and esptool.py from a command line.  It doesn't make a difference.

There may be a problem with my soldering job, but I'm pretty good at soldering and SMD rework, and I have repeated the job on a number of these ESP-01 modules, inspected and tested with multimeter, etc.  all with the same outcome.

I don't see a problem with my code or IDE, I have a batch of Lolin Nodemcu boards, and this sketch works perfectly on all of those.  In that case I simply connect GPIO 16 to RST with a jumper wire, the program prints the message, sleeps for 15s, wakes up, prints it again, goes back to sleep for 15s more, etc. etc.

Are these just bad boards?  I have read some things that say the flash chips might be lousy, and if I replace those it might help? I'm tempted to trash these boards and buy some D1 mini's, but I've seen a number of posts from people who say they've had the same problem with D1 minis.   If the board is the problem, are there any recommendations for manufacturers or vendors that sell better quality?

body:
I have come to the conclusion that these boards are bad.    I wrote a simple sketch that turns an LED on for 3 seconds, then goes into deep sleep for 12 seconds, then wakes up.   I have a batch of 3 Lolin ESP8266 nodemcu boards and the sketch works fine on all of them.   The LED goes on for 3s, then goes off for 12s, then goes back on, etc. Furthermore using an ammeter I measure a current draw of around 80 mA while the LED is on, and around 4 mA while it's off, repeatedly.

However --- I have another batch of five ESP-01 boards.   I soldered a fine copper wire to GPIO 16 and to the reset pin, used the same code, same set up, power supply, LED, etc.
The light goes on for 3s then goes off for 12s,  then comes back on and stays on and then there is no further change.  Furthermore, the current draw during the first 3s is around 80 mA, but when the light comes back on and the controller hangs, the current draw is around 40mA.

Incidentally, I tested the nodemcu boards,the ones that work fine, with this sketch but disconnecting the jumper from GPIO 16 or RST, and it behaves exactly the same as the ESP-01 boards, including the 40mA current draw in  the zombie state.   So it would appear that the problem on the ESP-01 boards is that the GPIO 16 pin is just not connected to RST.  However I have soldered all five of these things multiple times, and I have become pretty darned proficient at soldering that little pin, and I am 99.999999% sure that I have the wire soldered to the pin, with no bridges, didn't fry anything, etc.


body:
Not necessarily an answer, but something to look at: check the Manufacturer ID of the Flash on your board.  My suspicion is that when some Flash chips come out of suspend, they're in lower drive mode than on initial power-up.  At least one person fixed his 'zombie mode' by replacing the Flash with a different vendor.  Nobody else has attempted it yet.

I have an Inland ESP-01S that's reporting MID = 0x5E (supposedly Zbit) and it comes out of Deep Sleep repeatedly.  Here's all of the Manufacturer IDs I know of or have seen:

Winbond EF
GigaDevice C8
Puya 85
Bright Moon 53
BergMicro E0
XMC 20
XTX 0B
Eon 1C
Shanghai Fundan A1
Macronix C2
Hua Hong Zhixin 68
ISSI 9D
Paragon E0 (same as Berg - oopsie or clone?)
Zbit 5E
Zetta BA

esptool.py --port /dev/ttyUSB0 flash_id   (linux)
esptool.py -p COMx flash_id    (Windoze)

Note: the cheap D1 Mini boards with no-name ESP-12F modules flooding eBay, Aliexpress and other places report XTX Flash, and they have a 5.6K pull-up on EXT_RSTB which will shorten the RST pulse from GPIO16, as well as making it hard to hit the level to be detected as a LOW due to the series 470 ohm resistor.  We're unsure whether it's the Flash or the low value pull-up (typically 10 or 12K on other boards/modules) that's causing issues with those boards.  Normally if RST isn't seen as LOW after Deep Sleep then you'll get an "ets_main.c" message at boot before it hangs.

I have a clone D1 Mini Pro that has a Flash that reports MID = EF (Winbond), although the marking on the Flash is nothing I can find on Winbond's site, only on places selling cheap Flash.  Luckily the D1 Mini Pro also exits Deep Sleep successfully.


message:
Output voltage range between 0-5v

I am using arduino Uno/Mega.

I am trying to output a range of 0-5v volts using PWM.

Is it possible to do it?

It’s would be nice to see some code or instructions, as far I have seen, they used external Module to get that voltage range, maybe I am wrong or I didn’t understand them well.

Thanks!

body:
The Arduino is a digital device; each output pin is either HIGH (+5v) or LOW (0v = GND), not in between.

For certain types of devices (motors, LEDs) there is a technique you mentioned called PWM, pulse width modulation, which turns the output on and off rapidly. It's still just a square wave alternating between 0 and 5v but it's doing it really fast. So for an LED for example, your eye will make you think it's at half-brightness even though it is flashing on and off very quickly.

To do this you need to use a pin that has "analog" ability and use the "analogWrite" command.


body:
Short answer: No.

Arduino Unos and Megas have PWM (Pulse Width Modulation) output, which rapidly turn the output on and off with a varying "duty cycle" (The ratio of on time to off time.) That is not the same thing as an analog output voltage.

If you have a constant load you can build a low pass filter that will smooth the output to a slightly dirty DC output based on the PWM output.

You're better off using an external DAC (Digital to Analog Converter.) You send that a digital value and it converts it to a clean, filtered analog output. Most modern DACs are fast enough to output complex waveforms like music.

## Edit:

The Arduino zero apparently has a built-in DAC with up to 10-bit resolution. you could use that to output a low current DC voltage. However the zero is a 3.3V device.


message:
Why must I reload ArduinoCreateAgent-1.1-windows-installer-chrome every time I restart my computer?

What am I missing that this is happening?
Used to use a laptop (with Create Agent installed on hard drive) which never had this problem.
Now using a Windows 10 desktop and the On-line Create Agent.
Unless I reload the Arduino Create Agent, I always get the 'No Plug-In Connection' error message, please see screen capture. [![enter image description here][1]][1] Device manager recognizes the Arduino Uno and assigns COM3 to the USB connection, please see screen capture.[![Screen Capture from Device Manager][2]][2]

  [1]: https://i.stack.imgur.com/HglKv.png
  [2]: https://i.stack.imgur.com/SztqJ.png

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


message:
Sketch is not being received by Arduino even though Arduino Editor acts like it is finished?

In my attached screen capture the Arduino Editor appears to be performing the upload, however it never finishes. Completes three steps, the last being the sketch up-load and then states that it is busy.  Sorry that I can't submit a short video. [![Up-Loader Busy][1]][1]Please suggest ideas to solve this issue.  Maybe this is related to my first question?

  [1]: https://i.stack.imgur.com/m4EeV.png

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


message:
How to count number of bytes appearing in the Arduino serial?

I need to count the number of bytes appearing in the serial (UART bus) bus, how to count bytes in Arduino with Arduino Serial functions? is this possible?

Application -
RS485 communication with multiple boards **without slave ID**

slave boards will send data to the master board when,

1st 10 bytes = masters send a 10byte message to all slaves

slaves listening to the bus always until it is the turn to send the data

when byte count is 10, slave 1 sends data 5 bytes to master

when byte count is 15 (10+5), slave 2 sends data 5 bytes to master

when byte count is 20 (15+5), slave 3 sends data 5 bytes to master

max count is 25 known value

body:
`Serial.available()` returns the number of bytes available for reading in the buffer.

    int nBytes=Serial.available();
    if (nBytes > x) {
    ............
    ............
    ............
    }


message:
send configuration commands with arduino

I am using ublox zed F9P multi GNSS module. I have to program it for its configuration messages. Like I have to run a specific configuration of my receiver with the help of Arduino. I know arduino parse the GNSS sentences but can anyone tell me how to write code for ublox configuration commands such that that command can change setting of the receiver upon burning it in Arduino. Also, that code should retain in the receiver even if arduino is disconnected (closing arduino IDE console). Please help

body:
Here you find a **standard** library from arduino.

https://www.arduino.cc/reference/en/libraries/sparkfun-ublox-arduino-library/

You can find the documentation here:

https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library


message:
Can I use arduino pro micro rx tx as digital pins

I'm using arduino pro micro Atmega32u4 5v 16Mhz

I want to use it to make a HID Keyboard and Mouse but I ran out of pins so I was wondering if I can use the RX and TX pins as digital input pins. Will it work? Will it affect the communication of the arduino  to the computer?

body:
Using TX and RX on a 32U4 does not affect PC communication. It uses a competent different communication channel.

You can use those pins for digital operation with no problems, you just won't be able to use `Serial1` for communication with serial peripherals.


body:
Welcome to ASE.

1. Communication between the PC and the Arduino Pro Micro happens through the USB, unlike the Arduino Uno and Mega, which use the RX and TX lines.
2. In your case, the USB pins of the Micro are used to communicate with the PC. Hence, the RX and TX pins are available for digital input and output operations.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/OVjSD.jpg


message:
ESP32 softAP SSID not const

I would like to be able to set the wifi SSID in the setup(), so I can customize it based on the MAC address or something similar. (avoiding to ESP's with the same code having the same SSID). However since it requires a const it does not seem to be possible, or am I missing something?

I'm using platformIO if that matters...

body:
A `const` parameter to a function doesn't define what can be passed. It is, instead, a "promise" by the function that it will not modify the data you pass it.

In C when you pass a "string" (which is actually an array of characters) to a function you don't actually pass the string (as in the content). You really just pass a pointer to the location in memory where the string is stored.

It is perfectly possible for a function to then make modifications to that passed "string", which will be modifying the original data in memory. That is not really desirable in many situations.

So by flagging the parameter as `const` you tell the compiler "From this moment onwards the data pointed to by this variable must not be changed". All attempts to write to the memory using that variable will be blocked by the compiler.

There's no actual difference between, say, a `char *` and a `const char *` other than how the compiler treats attempts to write to them.

When you pass a `char *` to a function that is expecting a `const char *` the pointer is "upgraded" to a constant so that no attempts to change the data will be allowed.

The converse is not allowed though - you can't (or shouldn't) try and convert a `const char *` to a `char *` as on some systems ("Princeton" architecture systems with a single monolithic memory address space) the pointer could be pointing to data stored in flash, and an attempt to write to that will obviously fail.

The function you are calling to set the SSID is merely promising that it won't attempt to change the data you pass it. It doesn't matter if it's a constant or not - both will be treated as a constant and not be changed.


body:
The library [WifiManager][1] might work for you, it’s got a captive portal to configure your wifi connection on the fly. It’s got quite some configuration options to shape it to your will if I am not mistaken, I hope it serves you well.

  [1]: https://github.com/zhouhan0126/WIFIMANAGER-ESP32


message:
ATTINY85 and POT

I need to read a potentiometer value from an ATTINY85.
I have big fat 10K POT but for this use case I need it to be very small so I used a salvaged 2.4K one, the kind that is soldered directly onto a PCB.

I am using tinkercad to prototype my project and I am facing a very weird problem. Everytime I read from the POT Pin, I get the value of 512 (using the debugger)

Here is a screenshot of my prototype:
[![enter image description here][1]][1]

The goal is to power the circuit and the lamp (does not matter what is there, consider it just a load) with a 9V battery, use a 5V regulator to power the ATTINY85 and use an NPN transistor to turn the lamp/load on or off.

For information, the whole regulator and transistor setup is tested and works like a charm.

Here is the code I wrote for the this case:

    void setup()
    {
      pinMode(PB0, INPUT);
    }

    int potValue = 0;

    void loop()
    {
      potValue = analogRead(PB0);
      delay(100);
    }

Not real fancy right?
Now no matter what use for the POT, and I tried 2.4K, 10K and up to 100K, the value read by the ATTINY is always 512.

Do you see something wrong in this setup?
Could it be a bug in tinkercad? (I'd be surprised though)

I could try and share this circuit within tinkercad if someone would be willing to have a look...

EDIT: I just tried with PB2 as suggested but not the value is always 58:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Xyzc5.png
  [2]: https://i.stack.imgur.com/5DHK8.png

body:
[Port PB0 is not an ADC (analog input) pin on the ATTiny85](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf).

Available pins of the ATTiny85 (from the Atmel ATtiny 25, 45, 85 datasheet):

[![ATtinyx5 pinout][1]][1]Choose PB2, PB3, PB4 or PB5 if you need an analog input.

Additional information: When built in TinkerCAD, using PB2 as an analog input does not seem to work correctly and produces a fixed value. Using PB3 did work correctly however. This might be a bug in TinkerCAD.

  [1]: https://i.stack.imgur.com/ksObn.jpg


message:
Why should I connect the l289n motor driver wires to specific arduino pins only?

So, I am new with arduino and am to build a robot using motors, for that I have bought l298n H bridge motor driver. I have watched various site and videos ,to make sure not to make a mistake but, in every video and sites

I have found their connecting the motor direction controller to

  [![Diagram][1]][1]

  [1]: https://i.stack.imgur.com/pVUof.png

IN1 -> Arduino Pin 8 (digital) and IN2 -> Arduino Pin 7 (digital)

Till then it was fine ... Now the fishy thing for me is

IN3 -> Arduino Pin 5 (PWM) and IN4 -> Arduino Pin 4 (Digital)

Why connect to a Digital and a PWM?

For E1 and E2 I am sure that the wires should be connected to the PWM (~) pins for arduino, to control speed of the motor..

But, Should not I be able to connect IN3 and IN4 both to rest of the digital pins 12, 13 or 2,4 Just Like IN1 and IN2 is connected to 7 and 8.

But the IN3 and IN4 is connected to a PWM and a Digital pin.

Conclusion,

So can I use all the unused non PWM digital pins to connect the motor direction control?

Thanks for your precious time..!

body:
Pwm is just a digital out with extra fancy on off controls.  You can use any digital out if you do not need those extra features.

To just signal a single H bridge (1 motor of your l289n) for forward, reverse, stop, one only needs two digital outs.

I recommend you get the hang of your h bridge first - signaling it on a bread board with vcc (usually 5v but can be 3.3) and ground rather than the arduino.  Then once you understand the motor directions that result from your wiring, write the code accordingly.  This tends to result in:
1) fewer fried arduinos
2) code with functions and signals named after their intent (rather than having to mix forward and reverse)


message:
Fast PWM: Resolution in hertz

I am trying to get a nice sounding varying PWM to DAC, and intend to use a [Sallen Key][1] as part of an active low pass filter.

I set the Fast PWM at a max of 255 ([WGM1\[0-3\] = 5][2]) and set/clear OC1A upon comparing with OCR1A `(1<< COM1A1)`

I also update the value of OCR1A in 64 distinct steps, changing those steps around 15'000 times a second to create a specific sinusoidal shape.

As the chip works at 16 Mega Hertz, does this mean that one cycle of PWM is `16'000'000/256=` 62.5 Kilo Hertz? If not, what is its resolution

Thank you!

  [1]: http://sim.okawa-denshi.jp/en/OPstool.php
  [2]: http://sculland.com/ATmega168/Interrupts-And-Timers/16-Bit-Timer-Setup/

body:
With the help of the comments, I decided to use variable PWM max values to match absolutely with the frequency. This resulted in a crispier sound that *actually doesn't need the Sallen Key anymore*.

For example, a low C natural, or `261.6Hz`, updated `32` times for `8` full cycles of PWM give us, for a 16MHz chip, an period and amplitude of `238`.

This means that having a prescaler of `8` (`CS01`), a period (`OCR0A`) AND a max potential duty cycle (`ICR1`) of `238`, and going through 32 iterations of the sound sought for, I got the sound that I wanted and none of the wave groove that comes with a pulse duty cycle cut short.

Sure, it means less granularity when it comes to a Bb with a max duty cycle of 133, however it worked for me.


message:
Can Arduino UNO permanently store a code?

I'm really new to Arduino and wanted to know if I can make Arduino a permanent controller?
and could you help me with a cheaper alternative?
I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

Thanks a lot for helping me out:)

body:
> idk if the arduino stores the code for ever

The code is saved in the flash memory, which is non-volatile. It does not lose its content during power cycles. Also, when looking at the time dimension, it holds the code over a very long time, though not for ever. The [datasheet of the Atmega328p][1] (the microcontroller in the Arduino Uno or Nano) states:

> Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

So over 20 years at a temperature of 85°C you can get 0.0001% of data loss in the flash memory. At normal room temperature you can get that loss in 100 years. So significantly longer than the lifetime of most electronic products.

> I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

There are different ways and levels of protection. Though that is a more advanced topic, that you should tackle, when your product is finished otherwise. There are multiple resources on the web about this. The first place to look is always the datasheet of the used microcontroller. First part might be to not use the standard Arduino bootloader, but your own. And then you can set 2 fuses for getting different levels of protection (write protection, read protection), that will lock out 99% of the people. [This question][2] on Electrical SE might also be interresting for you. You can find many resources on the web by searching for something like "Arduino code protection" or "AVR code protection" (if you are using an AVR based microcontroller like with the Arduino Uno/Nano/Mega)

---

Apart from that I also would open the question to you, if your code is really that new and ingenious, that you need to protect it from being read that way? It might totally be, that this is the case for you. But from my perspective the probability is very low. I cannot say of my own codes, that they are worth the hassle of protection. And it also depends on what you really want to prevent that way.

For context: When you program the Arduino (or any microcontroller) with your C/C++ program, the text of the program is not saved on the Arduino. Instead the code is first converted to Assembler code and then compiled into binary machine code. On that level all the nice concepts of the higher level languages are not present, so they are done by multiple lower level functions (for example loops are jumps with conditions). An attacker might read the machine code back from the microcontroller. The biggest threat here is, that he would just copy it to a new microcontroller.

If he wants to get "code" from it, he would invoke a disassembler, which converts the machine code back to the assembler language. But at this point all symbols (names of variables, functions, ...) are lost, because they are not saved in the original machine code from the start. Reading and understanding such a code is very difficult, especially, if your code is rather big and complex. Most times it would be easier for an attacker to just reverse engineer your code based on the behavior of the original microcontroller.

So in the end, you cannot really prevent people from building counterfeit products. That's what a patent is for.

This does not mean, that you should not use the code protection. Just do a realistic security assessment and then decide, if it is worth the hassle.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [2]: https://electronics.stackexchange.com/questions/53282/protecting-avr-flash-from-reading-through-isp


message:
working with ultrasonic sensors

I have a little problem dealing with ultrasonic sensor
I want a simple thing , when the sensor read High pulse then after it low pulse , turns on the led
 so I try to make it with a 5cm distance and a flag , but it's dose not work
help me please!

        #define echoPin 5
        #define trigPin 7
        int GREEN = 2;
        int YELLOW = 3;
        int RED = 4;
        int pos = 0;
        int flag = 0 ;
        long duration;
        int distance;
        void setup() {

      // put your setup code here, to run once:
        pinMode(GREEN, OUTPUT);
        pinMode(YELLOW, OUTPUT);
        pinMode(RED, OUTPUT);
        pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
        pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
         }

        void loop() {

        ultra();

        if ( distance <= 5 && flag == 0)
        {//H
          flag = 1 ;}
        } //high pulse (When the distance <=5)

        if ( distance >5 && flag == 1)
        {//L
          red_light(); }

        }//the led should turned on when low pulse appears (When the distance >5)

        void red_light()
        { digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);
        digitalWrite(RED, HIGH); }

        void ultra()
        { digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);
        distance = duration*0.034/2; }

    //this is my code

body:
> what actually happens with this code is when I put something near the sensor <= 5 , the led is on without i removed the thing , but I want the led on when I put then remove the thing

Here is my theory on what happens here. You can confirm it by using one of the solutions, that I will explain below.

Currently your code is measuring the distance as fast as it can. The measurement is what takes the longest time in one iteration of the `loop()` function. Thus you get many many measurements per second. But such distance measurements are always noisy, meaning that the values change randomly in a specific range. When you put the object in front of the sensor, you expect the values to just go down, but actually they are sometimes rising again for 1 or 2 values because of the noise. So the measured values might look something like this (only imagined for making the point; not real values):

    5.4 --> 5.2 --> 4.99 --> 5.001 --> 4.89 --> 4.90 --> 4.5

Overall the values go down, but you are comparing always the current value with the fixed threshold of 5cm. When the noise just raises the value again, while you pass 5cm, you will get a false "put and removed again" outcome. At the probability  of the noise doing that is really high, since you measure that often and ultrasonic sensors are not accurate down to millimeters. You could even have the distance pass 5cm multiple times due to the noise.

There are some possibilities to reduce noise or to handle it.

- **Hysteresis:** The first, that I would implement here is hysteresis. That means, that you set the "put" distance different than the "remove" distance. For example you could use 5cm as the distance to register, that the object is put in front of the sensor, but then you wait for the distance to go above 7cm to actually treat the object as "removed". You need to choose the difference between the distances larger than the noise (you can find that out via experimenting). This principle is also used directly with noisy digital signals on the Arduinos input pins. An Arduino Uno will treat voltages above about 2.6V as digital 1 (HIGH signal), and a value below 2.1V as digital 0 (LOW signal) (taken from the [datasheet of the Atmega328P][1], which is the microcontroller on an Arduino Uno, while assuming the controller running on 5V like in an Arduino Uno). In electrical terms this is called a Schmitt-Trigger.

    For implementing this, you can just change the threshold values in your if statements.

- You can reduce the noise by always measuring multiple times in a row and then calculating the mean value from it. Since a part of the noise is random, you can smoothe out this part a bit through taking the mean. That also reduces your time resolution, but in such a simple use case that mostly doesn't matter that much.

- If the reaction time doesn't matter that much, you could reduce the frequency of measurements, so that subsequent distance measurements are already to far away from each other for the noise to create false triggers. This is worse than the other solutions, since it also depends on how fast you put the object in front of the sensor, but it is really easy to implement (just a simple `delay()` call, or better using `millis()` like in the `BlinkWithoutDelay` example for non-blocking code)

I would first implement the hysteresis. Then, if the difference in distances, that you need for it to work good, is too big for you, you can take the mean of multiple value to reduce the noise.

---

And just for protocol, as it already was said in the comments: Your first if statement has an extra closing bracket `}` which should not be there.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


message:
iterate through 8 thermocouple sensors (MAX31856)

I have 8xMAX31856 and I am trying to use the Adafruit library. Instead of writing all 8 thermocouple channels each time in code (and wasting memory), I want to store the objects in an array and loop through them periodically.

Here is my code:

    Adafruit_MAX31856 TCouple1 = Adafruit_MAX31856(2,11,12,13);
    Adafruit_MAX31856 TCouple2 = Adafruit_MAX31856(3,11,12,13);
    Adafruit_MAX31856 TCouple3 = Adafruit_MAX31856(4,11,12,13);
    Adafruit_MAX31856 TCouple4 = Adafruit_MAX31856(5,11,12,13);
    Adafruit_MAX31856 TCouple5 = Adafruit_MAX31856(6,11,12,13);
    Adafruit_MAX31856 TCouple6 = Adafruit_MAX31856(7,11,12,13);
    Adafruit_MAX31856 TCouple7 = Adafruit_MAX31856(8,11,12,13);
    Adafruit_MAX31856 TCouple8 = Adafruit_MAX31856(9,11,12,13);

    char* thermocouples[] = {TCouple1, TCouple2, TCouple3, TCouple4, TCouple5, TCouple6, TCouple7, TCouple8};

however, I am met with this error on compile:

    cannot convert 'Adafruit_MAX31856' to 'char*' in initialization

Why can I not store these variables in an array and call on them later? Is there another way to do this? They work on SPI logic...

body:
You CAN store them in an array, but NOT in an array of pointers to characters. That is just the wrong type. Try

    Adafruit_MAX31856 thermocouples[] = {TCouple1, ...}

or even ditch the first declarations and use

    Adafruit_MAX31856 thermocouples[] = {
        Adafruit_MAX31856(2,11,12,13),
        Adafruit_MAX31856(3,11,12,13),
        Adafruit_MAX31856(4,11,12,13),
        ...
    };

I don't have that library installed, but I tried compiling this pattern with the `Bounce2` library and it works. That looks like this:

    Bounce buttons[] = {
        Bounce(),
        Bounce(),
        Bounce()
    };