body: I have a Arduino UNO and I want to remove the previously uploaded code....how to do that?

title: How to remove any previous program from Arduino?

Answers: 3

body: Just upload a new one. I frequently "blank" an arduino when I'm done with it by uploading "Blink.ino" from the examples included with the IDE. (The only reason I've had to remove old code is to avoid an issue where I might later wire up the Arduino in a way that is dangerously incompatible with the old code running on it.)

body:
Replacing your sketch with another doesn't actually "remove" the previous one. Is that really necessary? If you're trying to prevent the first one from executing, replacing it, as already suggested by @Juraj, is a simple and proper solution.

If you need to prevent anyone ever being able to read any part of the previous one, you'd need to load another sketch at least as large as the previous one so it over-writes all of it, or create and run a modified "bootloader" program that erases the parts of flash you wish to obscure.

(Your question doesn't address your reason for wanting to "remove" the sketch. I'm adding this for completeness; not because I think it's likely.)

body: I got it. just upload blank code that is written when you start arduino ide.


body:
I only started learning Arduino recently. This is my first project.

So the idea for the project is that there will be an Arduino board(Ideally an Uno but I don't know if another board would be better) and when you hold a button down it will transmit what you are saying to a device on the wifi. I know I will have to get a WiFi module and like a microphone and button, so can you help me figure out just the gist of how the project will go and what parts I should get.

Thanks!

title: I want to stream audio from an Arduino to a device on the wifi

Answers: 2

body:
An Arduino can do this, but this is a very advanced problem on an Arduino. It sounds like perhaps you need something more plug-and-play. In that case, buy a [Raspberry Pi 4 starter kit][1] and a [USB microphone][2], and start working on the problem from there. The Raspberry Pi 4 is a Linux computer, so everything you do will be writing scripts or programs (in any language: it's just a regular computer, so use Python, C, C++, Java, bash, whatever you want) to run on its [Raspberry Pi OS (formerly called Raspbian)][3] Linux operating system.

If you go this route, you'll want to ask your questions on the [Raspberry Pi Stack Exchange][4] as well.

Keep in mind the question you asked is too broad. You are generally expected to do your own background research and then ask more specific questions, demonstrating what you've already tried.

Getting an Arduino to send out microphone data is, like I said, a very advanced subject and project (think: professional level / expert hobby level) unless you can Google and find pre-made libraries and how-tos on the subject.

Essentially, for the Arduino Uno route you'd need to do some fancy high-rate ADC sampling with a modified ADC clock rate in a special ADC mode which takes repeated samples and then interrupts your code when a sample is ready, rather than just doing normal `analogRead()` since that is both blocking/polling-based which wastes clock cycles and creates sample jitter which causes audio distortion, and then you'd need to send this data via some Wifi shield (add-on board) or an ESP8266 or something, or via some other technology (wired or wireless) to a computer to pass it on to the internet. This may involve binary packetization/bit-packing, error checking, buffering, etc., all of which is its own special skill to acquire.

Some of my projects have taken me 3+ years to complete them, since I began complicated projects as a beginner. This is one of those multi-year type projects for a beginner for sure.

(Heck, if you give me two LEDs and two resistors and an Arduino Nano, with those items *alone*, I can send you on your way to work 8 hrs a day for 3 months straight on projects. It's easy to under-estimate the complexity of something until you're neck-deep in it.)

Update: if you want to go the Arduino route, here's some tips to get you on a search route more likely to get you to a solution faster. Again, no doubt an Arduino Uno _can_ do this. It for sure can. But, a faster Arduino can do it easier and better. So:

1. **Google** search for projects on [Adafruit][5] which may do this. Ex: [Google search for "adafruit stream audio"][6]. Their tutorials are 2nd to none--the best in the world--and their products top-notch.
1. Search for projects on [Sparkfun][7] which may do this. Ex: [Google search for "sparkfun stream audio"][8]. They also are excellent and have world-class tutorials.
1. Search for projects which do this with a [Teensy][9], [Zero][10], [Due][11], or other high-speed 32-bit microcontroller, instead of an Uno. Audio processing is more difficult for a slower 8-bit Uno than for any of those 3 Arduino/Arduino-compatible devices.
1. Also look on [Instructables.com][12] for tutorials and help.
1. One more thought: [Google search for "atmega328 stream audio to wifi"][13] (an Uno uses the ATmega328 microcontroller, so that's a good search term to use)

-------

Update: also take a look at this tutorial by GreatScott (who is also super awesome) (https://www.instructables.com/id/Make-Your-Own-Spy-Bug-Arduino-Voice-Recorder/), which uses this AVR-based (for ATmega328: Arduino Uno, Nano, Pro Mini, etc., or ATmega2560: Mega) advanced audio library for both recording and playing back audio. See:

1. https://github.com/TMRh20/TMRpcm
    1. [Recording Audio](https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#recording-audio)
    1. [Audio streaming over NRF24L01+ radio link](https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#audio-streaming-over-nrf24l01-radio-link)

  [1]: https://amzn.to/32cz2fU
  [2]: https://amzn.to/32bD1cP
  [3]: https://www.raspberrypi.org/downloads/raspberry-pi-os/
  [4]: https://raspberrypi.stackexchange.com/
  [5]: https://www.adafruit.com/
  [6]: https://www.google.com/search?q=adafruit stream audio&oq=adafruit stream audio&aqs=chrome..69i57.3968j0j7&sourceid=chrome&ie=UTF-8
  [7]: https://www.sparkfun.com/
  [8]: https://www.google.com/search?sxsrf=ALeKk00CUsKlr9P_tNH8FwHIf0EHrXcdBg:1599621375241&ei=_0hYX7vEDc-GsAXS0IvQCg&q=sparkfun stream audio&oq=sparkfun stream audio&gs_lcp=CgZwc3ktYWIQAzoRCAAQsAMQigMQtwMQ5QIQiwNQ8MgCWLLTAmCx1QJoA3AAeACAAaEBiAGwCJIBAzAuOJgBAKABAaoBB2d3cy13aXq4AQLAAQE&sclient=psy-ab&ved=0ahUKEwj7v-H-jdvrAhVPA6wKHVLoAqoQ4dUDCA0&uact=5
  [9]: https://www.pjrc.com/teensy/
  [10]: https://store.arduino.cc/usa/arduino-zero
  [11]: https://store.arduino.cc/usa/due
  [12]: https://www.instructables.com/
  [13]: https://www.google.com/search?q=atmega328 stream audio to wifi&oq=atmega328 stream audio to wifi&aqs=chrome..69i57.7093j0j4&sourceid=chrome&ie=UTF-8

body:
You can use a ESP32 with built-in WiFi and Bluetooth. [Record a wave-File to a SD-card][1] using [this][2] library, send it over Blutooth and [play][3] it on the PC with a little script.

  [1]: https://www.instructables.com/id/Make-Your-Own-Spy-Bug-Arduino-Voice-Recorder/
  [2]: https://github.com/MhageGH/esp32_SoundRecorder
  [3]: https://realpython.com/playing-and-recording-sound-python/


body:
In my project, I am trying to create a timer display with LEDs base on how long a button was pressed and hold.

There are 8 LED lights in total, when the toggle button was pressed, 1st LED lights up; keep holding/ pressing the button, the 2nd LED lights up after 1sec, the 3rd LED lights up after 2sec and so on. So 7s after the button was pressed and hold, all 8 LEDs shall light up. When the button was released at anytime, all LEDs would be off.

Something is wrong with my code which the timer seems not working (saving the time when the button was pressed) and calculate the time difference ("current time" - "time when button pressed") in order to lights up the LED.

My codes:

     int current;
     long millis_held;
     long prev_secs_held;
     unsigned long firstTime;
     byte previous = LOW;

     const int buttonPin = 13;

     void setup() {
     pinMode(buttonPin, INPUT);
     pinMode(2,OUTPUT) ;
     pinMode(3,OUTPUT) ;
     pinMode(4,OUTPUT) ;
     }

     void loop() {
     current = digitalRead(buttonPin);

     if (current == HIGH && previous == LOW) {
     firstTime = millis();
     digitalWrite(2, HIGH);

     millis_held = (millis() - firstTime);

     if (millis_held >= 1000 && firstTime <2000){
     digitalWrite(3, HIGH);
     }

      if (millis_held >= 2000){
      digitalWrite(4, HIGH);
     }
     }

     else {
     digitalWrite(2, LOW);
     digitalWrite(3, LOW);
     digitalWrite(4, LOW);
     }
     }

Hope you guys can help, thanks a lot.

title: How do I make LEDs lights up one by one according to how long the button was pressed and hold

Answers: 2

body:
There are multiple errors in your code.

In the loop, the first if might not have the use you intended it to have. You are checking for `previous == low`, but you never set previous to high. Therefore this check can be removed entirely, or you could restructure your code a bit and add a `previous = high`.

Secondly, this `if` is also flawed:
```
if (millis_held >= 1000 && firstTime <2000){
    digitalWrite(3, HIGH);
}
```
You are checking for `firstTime < 2000` which means you need to press the button within 2 seconds of the power-up of the Arduino or else this code will not run.

Lastly, for this to run you probably only want to set `firstTime = millis()` once when you press the button, and not every time the `loop()` runs thereafter while you keep the button pressed. You would need to move the bracket on line 32 to line 22, that is from just above the `else` to the line above `millis_held = (millis() - firstTime);` and then add `previous = HIGH;` in the first if.

I am leaving it to you to fix your code, since that would be good practice to get some feeling for it. Happy coding!

Lastly you still need to add the last 5 leds, but once the first few work you should be fine.

body:
Great thanks to Ananas_hoi, I was finally able to get my code work accordingly!! The following code only show the 4 LED to be lights up one by one every second when the button was pressed and hold:

    int current;
    long millis_held;
    unsigned long firstTime;
    byte previous = LOW;

    const int buttonPin = 13;

    void setup() {
      pinMode(buttonPin, INPUT);
      pinMode(2,OUTPUT) ;
      pinMode(3,OUTPUT) ;
      pinMode(4,OUTPUT) ;
      pinMode(5,OUTPUT) ;
    }

    void loop() {
      current = digitalRead(buttonPin);

      if (current == HIGH && previous == LOW) {
         firstTime = millis();
         digitalWrite(2, HIGH);
         previous = HIGH;
      }

      millis_held = (millis() - firstTime);

      if (millis_held >= 1000 && previous == HIGH) {
          digitalWrite(3, HIGH);
         }

      if (millis_held >= 2000 && previous == HIGH) {
          digitalWrite(4, HIGH);
         }

      if (millis_held >= 3000 && previous == HIGH) {
          digitalWrite(5, HIGH);
         }

      if (current == LOW) {
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      previous = LOW;
     }
    }


body:
So I am trying to have a full-duplex high-speed(I'll be reducing the delay to microseconds once the below problem is solved) comm. between two Arduino Unos. Here is the code below:

Master:

    volatile uint8_t rdata;

    #define SCK   13  // D13 = pin19 = PortB.5
    #define MISO  12  // D12 = pin18 = PortB.4
    #define MOSI  11  // D11 = pin17 = PortB.3
    #define SS    10  // D10 = pin16 = PortB.2

    void SPI_MasterInit(void)
    {
      /* Set MOSI and SCK output, all others input */
      //DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
      pinMode(MOSI, OUTPUT);
      pinMode(MISO, INPUT);
      pinMode(SCK, OUTPUT);
      pinMode(SS, OUTPUT);
      /* Enable SPI, Master, set clock rate fck/4 */
      SPCR = (1 << SPE) | (1 << MSTR) | (0 << SPI2X) | (0 << SPR1) | (0 << SPR0) ;
      SPCR |= _BV(CPOL);
      //SPCR |= _BV(CPHA);

    }

    void SPI_MasterTransmit(uint8_t data) {
      PORTB &= ~(1<<2);
      SPDR = data;
      //asm volatile("nop");
      while (!(SPSR & (1 << SPIF)));
      rdata = SPDR;
      PORTB |= 1 << 2;
      Serial.print("data "); Serial.print(data); Serial.print(" rdata "); Serial.println (rdata);

    }

    void setup (void)
    {
      Serial.begin(115200);
      PORTB |= 1 << 2; //digitalWrite(SS, HIGH);
      SPI_MasterInit();
    }

    void loop (void)
    {

      for (byte i = 0; i < 10; i++) {

        SPI_MasterTransmit(i);

        //Serial.print(m);
        delay(100);

      }
    }

Slave:

    volatile boolean process_it;
    volatile byte indx = 129, c = 0;

    #define SCK   13  // D13 = pin19 = PortB.5
    #define MISO 12  // D12 = pin18 = PortB.4
    #define MOSI 11  // D11 = pin17 = PortB.3
    #define SS    10  // D10 = pin16 = PortB.2

    void SPI_SlaveInit(void)
    {
      /* Set MISO output, all others input */
      //DDR_SPI = (1<<DD_MISO);
      pinMode(MOSI, INPUT);
      pinMode(MISO, OUTPUT);
      pinMode(SCK, INPUT);
      pinMode(SS, INPUT);
      /* Enable SPI */
      SPCR |= _BV(SPE); // SPI Enable, sets this Arduino to Slave
      SPCR |= _BV(SPIE); // SPI interrupt enabled
      SPCR |= _BV(CPOL);
      //SPCR |= _BV(CPHA);
    }

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

      SPI_SlaveInit();

    }

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {

      SPDR = indx;
      indx--;
      if (indx < 121)
        indx = 129;
      c = SPDR;
      process_it = true;

    }

    void loop (void)
    {
      if (process_it) {

        Serial.println (c);

        process_it = false;

      }

    }

Below output shows the o/p of the master on the left and slave one the right:

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

The master prints the data it has sent(to the slave, "data" variable) followed by the data it has received (from the slave, "rdata" variable). The slave simply prints the received data (from the master).

If you look carefully at the pic you would see that the master sometimes gets the same data (in the next cycle)  it has sent (in the current cycle) (0 and 4 in the pic). At the same time, the slave fails to receive exactly that data (0,4). Also, you can the value of 'indx' is not decremented and the master receives the decremented value in the next cycle. These two things prove that the Slave ISR is not being called randomly (hence the data in the SPDR is not read which is then echoed back to the master plus the index variable is not decremented). Is there a solution to this? I would be really grateful if someone could help me with this.

**Edit**: I face the exact same problem with the default arduino SPI library, here is the code:

Master:

    #include <SPI.h>
    volatile byte m=0;
    void setup (void)
    {
        pinMode(MOSI, OUTPUT);
        pinMode(MISO, INPUT);
        pinMode(SCK, OUTPUT);
        pinMode(SS, OUTPUT);

      Serial.begin (115200);
      Serial.println ();

      digitalWrite(SS, HIGH);

      SPI.begin ();

      SPI.setClockDivider(SPI_CLOCK_DIV4);
    }

    void loop (void)
    {
    for(byte i=0; i<10; i++){
      digitalWrite(SS, LOW);
      m = SPI.transfer (i);
      digitalWrite(SS, HIGH);
          Serial.print("data "); Serial.print(i); Serial.print(" rdata "); Serial.println (m);
      delay(100);
    }
    }

Slave:

    #include<SPI.h>

    volatile byte c = 0, indx =129;
    volatile boolean process_it = false;
    void setup (void)
    {
      pinMode(MOSI, INPUT);
      pinMode(SCK, INPUT);
      pinMode(SS, INPUT);

      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= _BV(SPE);
      Serial.begin (115200);

     SPI.attachInterrupt();

    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {

          SPDR = indx;
          indx--;
          if (indx < 121)
            indx = 129;
          c = SPDR;
          process_it = true;

    }  // end of interrupt service routine (ISR) SPI_STC_vect

     void loop (void)
        {
          if (process_it) {

            Serial.println (c);

            process_it = false;

          }

        }

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

title: SPI slave ISR not being called randomly

Answers: 0


body:
II have setup a UNO and a HC-05 Bluetooth module as a 'Slave', and a NANO and an HC-05 Bluetooth module as 'Master', I believe the comm's work ok as I am receiving values and text, but the analog IN via a pot on the 'Master' (NANO) reads fine on the master Serial Screen, but does not read the same on the Slave (UNO)serial screen,the values received are changing from accurate to inaccurate on during data transfer.

I was hoping for a continuous accurate stream as the pot will be replaced with a 'load cell' and I need to capture weight readings and display them on a time base, I used bluetooth as the load cell and 'Slave' will be approx 5m apart. I would appreciate any help and I can send the sketch if you wish?

Regards, Gordon

title: Transfer analog value via Bluetooth HC-05 (master) to second HC-05 (slave)

Answers: 0


body:
I am building a arduino based bicycle speedometer with time and temperature display.

Im currently stuck with the DS3231 (zs-042) chip. I found online a lot of library issues, i tried using
multiple libraries (Rinky-Dink, ds3231-master) but nothing works. I found a simple code online to test the chip but when I upload it the following error shows up: "no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)"

```
#include <Wire.h>
#include <DS3231.h>
DS3231  rtc(SDA, SCL);

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

  // Initialize the rtc object
  rtc.begin();
  rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)
  delay (1000);
}

```
The error occurs in the third line (rtc (SDA,SCL)) - I have checked the pins and switched the battery on the chip. I also tried using A4 and A5 instead of SDA and SCL pins...

Any type of help would be awesome.

Best regards,
Marin

title: Arduino DS3231 error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)'

Answers: 1

body:
Alright I found the problem.

https://www.youtube.com/watch?v=BM3A7w3bhqM&ab_channel=MERTKILIC

In this video at 5:00 you can see the following:

First you have to download the library, unzip it and copy the files inside.

You will have to paste it to your Arduino/Libraries/DS3231 folder.

[![][1]][1]

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

On the left is the current DS3231 Library which I added through the arduino library manager. Its not the same as the one the right, it should be, but its not, copy the files from the unzipped DS32321 library into the Arduino/library/DS3231.

Works fine now !


body:
I'm writing a program that has a sub program that saves values to an array, but the sub program that saves the values to the array comes back with an error telling me that the array isnt declared in that scope.

I'm fairly new to this and self taught but even when I try and pass the array into the sub program I get the same error. I'm sure its a fairly simple obvious error I'm making but I just cant get it to work.

If anyone sees any other errors or better ways for me to write any of this any help would be greatly valued as I'm still not confident on what I'm supposed to be doing.

```
#include <HX711.h>

#include <Wire.h>  // IC2 communication

#include <LiquidCrystal_I2C.h>  //LCD
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

int max_load;
int interval;
int max_load_prev;
int interval_prev;
int mode;
int handle_weight;
int tip_weight;
int stop1;
int mode_previous;
int interval_sum;

int mode1 = 53;
int mode2 = 51;
int mode3 = 49;
int start1 = 39;
int start2 = 37;
int increment = 47;
float potentiometer1 = A0;
float potentiometer2 = A1;
int tare_1 = 45;
int tare_2 = 43;

//stepper motor controller
int stepPin = 12;
int dirPin = 13;

//sensor readings
  HX711 tip_read;
  HX711 handle_read;
  int DOUT_tip = 6;
  int DOUT_handle = 5;
  int CLK_tip = 4;
  int CLK_handle = 3;

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

  lcd.init();
  lcd.backlight();

  //saving to array//
  float data_storage_array[600][3];

  pinMode(mode1, INPUT);
  pinMode(mode2, INPUT);
  pinMode(mode3, INPUT);
  pinMode(start1, INPUT);
  pinMode(start2, INPUT);
  pinMode(increment, INPUT);
  pinMode(stop1, INPUT);
  pinMode(potentiometer1, INPUT);
  pinMode(potentiometer2, INPUT);

  //sesnor readings
  tip_read.begin(DOUT_tip, CLK_tip);
  tip_read.set_scale(55);// change to calibration factor
  handle_read.begin(CLK_tip,CLK_handle);
  handle_read.set_scale(55);// change to calibration factor

  pinMode(tare_1, INPUT);
  pinMode(tare_2, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  mode_previous = 0;
  interval = 25;
  max_load_prev = 0;
  interval_prev = 0;
  interval_sum = 0;
  while (digitalRead(start1) == 0) {
    if (digitalRead(mode1) == 1) {
      mode = 1;
    }
    if (digitalRead(mode2) == 1) {
      mode = 2;
    }
    if (digitalRead(mode3) == 1) {
      mode = 3;
    }
    if (mode_previous != mode) {
      Display_mode_set_up(mode);
      mode_previous = mode;
    }
    if (digitalRead(increment) == 1) {
      delay(500);
      if (interval >= 1000) {
         interval = 25;
      }
      else if (interval < 1000) {
        interval = interval + 25;
      }
    }
    max_load = max_load_reading();
    if (max_load_prev != max_load or interval_prev != interval){
      Display_value_set_up(max_load, interval, mode);
      max_load_prev = max_load;
      interval_prev = interval;
    }
    Display_output(handle_weight, tip_weight);

  tare_one();
  }
  if (mode == 1) {
    mode_one(max_load, tip_weight);
  }
  else if (mode == 2) {
    mode_two(max_load, interval, handle_weight, tip_weight);
  }
  else if (mode ==3) {
    mode_three(max_load, interval, handle_weight, tip_weight);
  }
  Pause_stop();
}

//---SUB ROUTINES---

void mode_one(int max_load, int tip_weight) {
  tip_weight = read_tip();
  while (tip_weight < max_load) {
    tip_weight = read_tip();
    turn_motor();
    Pause_stop();
    Display_output(handle_weight, tip_weight);
  }
}

void mode_two(int max_load, int interval, int handle_weight, int tip_weight) {
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip;
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    while (digitalRead(start2) == 0) {
      delay(1);
    }
  }
  send_values_to_pc();
}

void mode_three(int max_load, int interval, int handle_weight, int tip_weight) {
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load) {
    while (tip_weight < aim_value) {
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    delay(10000);
  }
  send_values_to_pc();
}

void tare_one() {
  if (tare_1 == HIGH) {
    tip_read.tare();
  }
  if (tare_2 == HIGH) {
    handle_read.tare();
  }
}

void turn_motor() {
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

int read_tip() {
  int weight;
  weight = tip_read.get_units();
  return weight;
}

int read_handle() {
  int weight;
  weight = handle_read.get_units();
  return weight;
}

void save_to_array(int interval_sum) {
  data_storage_array[interval_sum][0] = interval_sum;
  data_storage_array[interval_sum][1] = tip_read.get_units();
  data_storage_array[interval_sum][2] = handle_read.get_units();
  interval_sum = interval_sum + 1;
}

void send_values_to_pc() {
}

int max_load_reading() {
  int KG_value;
  int g_value;
  int load_max;
  KG_value = analogRead(potentiometer1);
  g_value = analogRead(potentiometer2);
  KG_value = KG_value * 2;
  KG_value = KG_value/ 100;
  KG_value = round(KG_value);
  KG_value = KG_value* 100;
  g_value = g_value/ 10;
  g_value = round(g_value);
  if (g_value >= 100){
    g_value = 99;
  }
  load_max = KG_value + g_value;
  return load_max;
}

void Pause_stop() {
  if (digitalRead(stop1) == 1){
    delay(1000);
    while (digitalRead(start1) == 0){
      if (digitalRead(stop1) == 1){
        motor_unwind();
      }
      else{
        delay(100);
        lcd.setCursor(0, 2);
        lcd.print("Program Paused");
      }
    }
    lcd.setCursor(0, 2);
    lcd.print("                    ");
  }
}

void motor_unwind() {
  tip_weight = read_tip();
  while (tip_weight < 100) {
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  int count = 100;
  while (count > 0) {
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
    count = count -1;
  }
}

void Display_mode_set_up(int mode) {
  lcd.setCursor(0, 0);
  if (mode == 1) {
    lcd.print("Mode: Max           ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:---");
  }
  if (mode == 2) {
    lcd.print("Mode: Incrimental    ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  if (mode == 3) {
    lcd.print("Mode: Automatic      ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  lcd.setCursor(0, 3);
  lcd.print("Tip:");
  lcd.setCursor(9, 3);
  lcd.print("Handle:");
}

void Display_value_set_up(int max_load, int interval, int mode) {
  if (mode == 1) {
    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);
  }
  if (mode == 2 or mode == 3) {

    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);

    lcd.setCursor(17, 1);
    lcd.print("   ");
    lcd.setCursor(17, 1);
    lcd.print(interval);
  }
}

void Display_output(int handle_weight, int tip_weight) {
  tip_weight = read_tip();
  handle_weight = read_handle();
  lcd.setCursor(4, 3);
  lcd.print(tip_weight);
  lcd.setCursor(16, 3);
  lcd.print(handle_weight);
}
```

title: Arduino array error

Answers: 2

body:
You are declaring `float data_storage_array[600][3]` in `setup()`, and using it in another function, that can't "see" it.

The simplest way of making it work is making your array global by declaring it at the top in the section where you declare other variables like `max_load`.

body:
As others have mentioned, your array is out of scope and can only be used in the `setup()` function. I have moved this out of the `setup()` function and into the global variable section.

I am also cautious of how much SRAM you were using with your (600 x 3 =) 1800 float elements. So I have changed it to ints and reduced it to 250 x 3. You have put down that you are using the Arduino Mega, so this could be expanded further if necessary.

Your variable `interval_sum` was set to increment with no upper limit. This means you would end up going beyond the limits of the array. I have fixed this.

I have reviewed your code briefly and added some fixes and some comments. It is untested. I hope this helps you.

<!-- language: lang-c++ -->

    #include <HX711.h>
    #include <Wire.h>  // IC2 communication
    #include <LiquidCrystal_I2C.h>  //LCD

    LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

    int max_load;
    int interval;
    int max_load_prev;
    int interval_prev;
    int mode;
    int handle_weight;
    int tip_weight;
    int stop1;
    int mode_previous;
    int interval_sum;

    const int mode1 = 53;    // <-- added the const keyword to all pin definitions as they dont change
    const int mode2 = 51;
    const int mode3 = 49;
    const int start1 = 39;
    const int start2 = 37;
    const int increment = 47;
    const int potentiometer1 = A0;    // <-- Changed to int as it is only a pin definition
    const int potentiometer2 = A1;    // <-- Changed to int as it is only a pin definition
    const int tare_1 = 45;
    const int tare_2 = 43;

    //stepper motor controller
    const int stepPin = 12;
    const int dirPin = 13;

    //sensor readings
    HX711 tip_read;
    HX711 handle_read;
    int DOUT_tip = 6;
    int DOUT_handle = 5;
    int CLK_tip = 4;
    int CLK_handle = 3;

    //saving to array//
    int data_storage_array[250][3];    // <-- Moved before setup(). Changed to int. Reduced to 250x3 elements.

    void setup() {
      // put your setup code here, to run once:
      lcd.init();
      lcd.backlight();

      pinMode(mode1, INPUT);
      pinMode(mode2, INPUT);
      pinMode(mode3, INPUT);
      pinMode(start1, INPUT);
      pinMode(start2, INPUT);
      pinMode(increment, INPUT);
      pinMode(stop1, INPUT);
      pinMode(potentiometer1, INPUT);
      pinMode(potentiometer2, INPUT);

      //sesnor readings
      tip_read.begin(DOUT_tip, CLK_tip);
      tip_read.set_scale(55);// change to calibration factor

      handle_read.begin(CLK_tip,CLK_handle);
      handle_read.set_scale(55);// change to calibration factor

      pinMode(tare_1, INPUT);
      pinMode(tare_2, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      mode_previous = 0;
      interval = 25;
      max_load_prev = 0;
      interval_prev = 0;
      interval_sum = 0;
      while (digitalRead(start1) == 0){
        if (digitalRead(mode1) == 1){
          mode = 1;
        }
        if (digitalRead(mode2) == 1){
          mode = 2;
        }
        if (digitalRead(mode3) == 1){
          mode = 3;
        }
        if (mode_previous != mode){
          Display_mode_set_up(mode);
          mode_previous = mode;
        }
        if (digitalRead(increment) == 1){
          delay(500);
          if (interval >= 1000){
             interval = 25;
          }
          else if (interval < 1000){
            interval = interval + 25;
          }
        }
        max_load = max_load_reading();
        if (max_load_prev != max_load or interval_prev != interval){
          Display_value_set_up(max_load, interval, mode);
          max_load_prev = max_load;
          interval_prev = interval;
        }
        Display_output(handle_weight, tip_weight);
        tare_one();
      }
      if (mode == 1){
        mode_one(max_load, tip_weight);
      }
      else if (mode == 2){
        mode_two(max_load, interval, handle_weight, tip_weight);
      }
      else if (mode ==3){
        mode_three(max_load, interval, handle_weight, tip_weight);
      }
      Pause_stop();
    }

    //---SUB ROUTINES---

    void mode_one(int max_load, int tip_weight){
      tip_weight = read_tip();
      while (tip_weight < max_load){
        tip_weight = read_tip();
        turn_motor();
        Pause_stop();
        Display_output(handle_weight, tip_weight);
      }
    }

    void mode_two(int max_load, int interval, int handle_weight, int tip_weight){
      int aim_value;
      aim_value = 0 + interval;
      tip_weight = read_tip;
      while (tip_weight < max_load){
        while (tip_weight < aim_value){
          turn_motor();
          Pause_stop();
          Display_output(handle_weight, tip_weight);
          tip_weight = read_tip();
        }
        save_to_array();    // <-- Global variable removed
        aim_value = aim_value + interval;
        while (digitalRead(start2) == 0){
          delay(1);
        }
      }
      send_values_to_pc();
    }

    void mode_three(int max_load, int interval, int handle_weight, int tip_weight){
      int aim_value;
      aim_value = 0 + interval;
      tip_weight = read_tip();
      while (tip_weight < max_load){
        while (tip_weight < aim_value){
          turn_motor();
          Pause_stop();
          Display_output(handle_weight, tip_weight);
          tip_weight = read_tip();
        }
        save_to_array();    // <-- Global variable removed
        aim_value = aim_value + interval;
        delay(10000);
      }
      send_values_to_pc();
    }

    void tare_one(){
      if (tare_1 == HIGH) {
        tip_read.tare();
      }
      if (tare_2 == HIGH) {
        handle_read.tare();
      }
    }

    void turn_motor(){
      digitalWrite(dirPin, HIGH);
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(500);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(500);
    }

    int read_tip(){
      int weight;
      weight = tip_read.get_units();
      return weight;
    }
    int read_handle(){
      int weight;
      weight = handle_read.get_units();
      return weight;
    }

    void save_to_array(){    // <-- Global variable removed
      data_storage_array[interval_sum][0] = interval_sum;
      data_storage_array[interval_sum][1] = tip_read.get_units();
      data_storage_array[interval_sum][2] = handle_read.get_units();
      if (interval_sum >= 249){   // <-- Added this if statement as there was no way to cap this number
          interval_sum = 0;
      }
      else{
          interval_sum = interval_sum + 1;
      }
    }

    void send_values_to_pc(){

    }

    int max_load_reading(){
      int KG_value;
      int g_value;
      int load_max;
      KG_value = analogRead(potentiometer1);
      g_value = analogRead(potentiometer2);
      KG_value = KG_value * 2;
      KG_value = KG_value/ 100;
      KG_value = round(KG_value);
      KG_value = KG_value* 100;
      g_value = g_value/ 10;
      g_value = round(g_value);
      if (g_value >= 100){
        g_value = 99;
      }
      load_max = KG_value + g_value;
      return load_max;
    }

    void Pause_stop(){
      if (digitalRead(stop1) == 1){
        delay(1000);
        while (digitalRead(start1) == 0){
          if (digitalRead(stop1) == 1){
            motor_unwind();
          }
          else{
            delay(100);
            lcd.setCursor(0, 2);
            lcd.print("Program Paused");
          }
        }
        lcd.setCursor(0, 2);
        lcd.print("                    ");
      }
    }

    void motor_unwind(){
      tip_weight = read_tip();
      while (tip_weight < 100){
        digitalWrite(dirPin, LOW);
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(500);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(500);
      }
      int count = 100;
      while (count > 0){
        digitalWrite(dirPin, LOW);
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(500);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(500);
        count = count -1;
      }
    }

    void Display_mode_set_up(int mode){
      lcd.setCursor(0, 0);
      if (mode == 1){
        lcd.print("Mode: Max           ");
        lcd.setCursor(0, 1);
        lcd.print("MLoad:");
        lcd.setCursor(12, 1);
        lcd.print("inti:---");
      }
      if (mode == 2){
        lcd.print("Mode: Incrimental    ");
        lcd.setCursor(0, 1);
        lcd.print("MLoad:");
        lcd.setCursor(12, 1);
        lcd.print("inti:   ");
      }
      if (mode == 3){
        lcd.print("Mode: Automatic      ");
        lcd.setCursor(0, 1);
        lcd.print("MLoad:");
        lcd.setCursor(12, 1);
        lcd.print("inti:   ");
      }
      lcd.setCursor(0, 3);
      lcd.print("Tip:");
      lcd.setCursor(9, 3);
      lcd.print("Handle:");
    }

    void Display_value_set_up(int max_load, int interval, int mode){
      if (mode == 1){
        lcd.setCursor(6, 1);
        lcd.print("      ");
        lcd.setCursor(6, 1);
        lcd.print(max_load);
      }
      if (mode == 2 or mode == 3){

        lcd.setCursor(6, 1);
        lcd.print("      ");
        lcd.setCursor(6, 1);
        lcd.print(max_load);

        lcd.setCursor(17, 1);
        lcd.print("   ");
        lcd.setCursor(17, 1);
        lcd.print(interval);
      }
    }

    void Display_output(int handle_weight, int tip_weight){
      tip_weight = read_tip();
      handle_weight = read_handle();
      lcd.setCursor(4, 3);
      lcd.print(tip_weight);
      lcd.setCursor(16, 3);
      lcd.print(handle_weight);
    }


body:
I'm building kinda "ball game" for a total of 6 players based on these per-player specs:
- 1 stepper motor with 4 pins
- 2 end stops (start & finish) per motor
- 1 finish LED
- 3 holes to score, resulting in slow, medium or fast motor movement

Additionally, there's a "master reset" to move all motors back to their starting end stops.

Because of my initial assumption, 54 pins would be enough, I didn't realize actually requiring 60 pins (24 for motors, 12 for end stops, 6 for LED, 18 for holes). I'm also neither an expert at microelectronics nor C programming language, but my understanding of the [Mega's pins](https://github.com/arduino/ArduinoCore-avr/blob/master/variants/mega/pins_arduino.h#L85-L88) is that I need 12 + 18 PCINT capable pins (end stops + holes) while only 16 pins are available.

So far, the only information I could find suggests buying an Arduino Shield to resolve this by providing additional 16 PCINT pins. But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.

How to get at least 30 PCINT capable pins, treated equally by Arduino? In case there's no need for the PCINT requirement, which pins can be used as an alternative?

title: Get more PCINT capable pins on Mega 2560

Answers: 1

body:
The Atmega2560 has a total of 24 pins associated to the PinChange interrupt. You cannot change that. It is an internal property of the microcontroller.

As you already have seen yourself, you need to use extra chips to extent the available IO pins. There are different options to consider:

- IO-Port-Expanders (available for I2C or SPI) (for example the [PCF8574][1]. Don't know, if that is the best, just the port expander, that I also used myself)
- Shift-In (for inputs) or Shift-Out (for outputs) registers (often used are the 74HC595 (Shift-out register) and the 75HC165 (Shift-In register). I often used [this tutorial][2] as reference)

As you don't want to poll these chips all the time, I suggest, that you use one, which provides an additional interrupt pin. That pin will change its value, when one of the input changes. You could then connect this pin to one of the interrupt pins of the Atmega2560. When the interrupt triggers, you can read the states of the input pins.

> But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.

Indeed that wouldn't be good. So you should divide the pins up by their purpose, not by their association to a player. For example all end stop inputs, or all outputs for the stepper motors. Then you need to access, what timing requirements each group has. Then you can take the group with the lowest requirements and check, if and which chip would be able to handle the data fast enough. For example the "finish LED". You didn't specify, what exactly it does, but I guess, that it is not really time critical. So you could handle all finish LEDs via a single shift-out register.

Or take the inputs for the holes: I guess here you have some sensor, that triggers, when a ball passes it. Check how long the sensor get's triggered. Most likely (depending on the type of sensor) this depends on the speed of the ball. Take a speed, that you want to consider maximum (for example the pitching speed of a good baseball player, as these are really high), and calculate, how long the resulting pulse will be. The chip, that you choose, might be fast enough for this. So you could handle all ball hole inputs over extra chips (meaning chips providing extra input chips, like a Shift-In register or a port expander).

> In case there's no need for the PCINT requirement, which pins can be used as an alternative?

Every pin capable of digital IO. That's nearly every pin on the Arduino Mega. Though that means, that you cannot use interrupts for them and you have to poll then constantly. That might be ok for you. It really depends on your exact timing requirements.

> I thought polling was a "avoid where possible"-area?!

Yes and no. First you asked for the possibility of using other pins, so I mentioned that above. Though doing that means using no PinChange interrupt. Generally polling is bad, when

1. you spend too much time on it, leaving no time for other functions of the code, or
2. if the events, that you are polling, are too short for your polling code.

That can happen in the cases, that

1. you use blocking code to poll (like waiting with a `while` loop for a button press), which blocks all other functions from executing.
2. your code needs a long enough event to register it (for example the signal from your hole sensors might be very short. If your polling interval is bigger than that, you will loose some events)

If you stay inside of the confinements and use non-blocking code, there is nothing bad with polling.

Let's take the often used [Bounce2 library][3] for Arduino. It helps you with reading buttons and handles the debouncing for you. It does not use any interrupts. You are expected to call `Bounce.update()` often enough to catch all button presses, which is typically a few ms at max. But since the Arduino Mega runs on 16MHz, it is capable of way faster speeds than the few ms. Calling `Bounce.update()` often enough is easy, when you don't write code, that stays a long time to execute. So no delays, except for maybe very short ones. Instead you can use the coding style of the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It uses the `millis()` function as a time base to check repeatedly, if it is time to do something, and only do so, if it really is time for it. Much like you are baking a pizza by putting it into the oven and then regularly watch at your clock, if it is time to get the pizza out of the oven. You don't want to sit in front of the oven waiting for pizza. The analog of doing that is writing blocking code with `delay()`.

So all in all about polling vs interrupts: It depends on your requirements. Fast response times or short events often need interrupts, though you need to cope with limited usable pin numbers and different interrupts (which is a bit more complex to code). Polling - when done right - can give you big freedom and rather easy handling, while saving interrupt sources for more important functions. Though it poses bigger limits on response times and the duration of events. Also it depends strictly on the rest of your code.

---

Note, that in the above, terms like "time critical", "fast response times" and such are more meant for the region of a low number of microseconds. Timings in the millisecond range can easily be done by using the mentioned non-blocking coding style (either with `millis()`, or for greater resolution and accuracy at low numbers of milliseconds `micros()`). The principle is always the same and there are tons of tutorials about it on the web and even many questions and answers on this site. So you can google for this, to get a more detailed tutorial.

  [1]: https://www.ti.com/lit/ds/symlink/pcf8574.pdf
  [2]: https://dronebotworkshop.com/shift-registers/
  [3]: https://github.com/thomasfredericks/Bounce2


body:
I am building an underwater robot, which can move Up/Down, Forward/Reverse, controlled by a Joystick.

The situation is like this :

USB Joystick is connected to a PC, PC is connected to an Arduino via tether cable (Ethernet), and motors of the robot are connected to the arduino.

The joystick I am using is having 2 sticks, and I have decided to use 1 stick to control the UP-DOWN movement (Actually, I'm using only 1 axis of that stick for this.) and the 2nd stick to control the LEFT-RIGHT movement.

My question is, Whenever the user manipulates both the sticks simultaneously (To achieve diagonal motion, for example), The joystick will send 2 signals, one after the other, one for each stick. Keeping in mind the limited receiver buffer size of the arduino, how do I program the arduino, such that it can understand the difference between linear motion signal and diagonal motion signal?

**I am highly motivated to program this on my own. I just need an Intuition for this.**

A thought came to my mind is, to use the following strategy:

For my Up-down stick value, I add a character such as `'U'`, followed by the integer joystick value. For E.g. I send `"U4"` to go up at speed `4`. With some twitching, I can even send down signal with the same preceding character `U`.

Similarly, for Forward/Backward, I send `"F3"` to go fwd/bkwd at speed `3`. And for diagonal, I send something like `"T5"` to go diagonally at speed 5.

My concern with this is, I will transmit 2 characters from the PC to Arduino. Will the arduino be able to read such 2 characters, interpret them and act accordingly, without the noticeable lag? Or is there any other better way?

**This also makes me wonder, how commercial robots (such as Commercial Drones) handle such situations?**

The movements the robot will make needs to be quick. There should not be "visible" lag, That is, the user should not feel that the Robot is responding after a couple of seconds.

title: Transmitting multiple values to the arduino, and Interpreting them with minimum delay

Answers: 1

body:
I don't know about commercial drones, however your 'protocol' seems to be quite efficient, as it uses 4 bytes to send 2 values (e.g. U3F5) for Up with speed 3 and Forward with speed 5.

Let's assume values from 0-7. Then you can send them both in 8 bits/one byte:

   H H H H V V V V

Where H is the horizontal speed (from -8 (000) to +7 (111), in total 16 possible values.
For the vertical speed you can do the same.

So within one byte you send both speeds (meaning also there is no lag).
In case you need more accuracy, than send two bytes: one byte with horizontal and one byte with vertical speed. Depending on the sending/receiving speed I doubt there is any lag.

Even with your protocol I doubt there is a lag, but the above is more efficient.

I'm sure even more efficient algorithms can be created, probably by using the difference with the previous value (like sending delta values).

Another algorithm that can be created, assuming there is a big chance that only one of the two directions is changed (either horizontal or vertical is) and having a high accuracy

    D V V V V V V V

Where D is the direction (0 = horizontal, 1 = vertical) and V is the value/speed (-64 to +63, 7 remaining bits).


body:
I've bought an Arduino Nano Every clone/compatible (not a standard Nano V3) that uses an ATMega4808 instead of the ATMega4809 the official Nano Every uses. This rather insignificant change of chip is detected by the Arduino IDE (v. 1.8.13) which tells me that the chip is wrong when I select "Nano Every" from the boards list and try to upload a sketch. The seller ([link to the product][1]) does not answer to my help requests. Does anybody own one of these and knows how to make it run?

Below a photo of the board. Note the small difference in pinout (4 extra pin, D22, D23, D24 and UPDI)

[![enter image description here][2]][2]

  [1]: https://www.digitspace.com/nano-every-arduino-compatible?search=nano every&description=true
  [2]: https://i.stack.imgur.com/75P6n.jpg

title: Nano Every clone with ATMega4808 not recognized

Answers: 1

body:
Probled solved, it turns out to be a Thinary Nano Every.

Instructions for installing on the Arduino IDE are on Github here: https://github.com/Thinary/ThinaryArduino


body:
I'm running this project with HC-05 https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5 and I am getting connection error. I have ensured my port selected and board is accurate but no such luck. The Arduino uno is powered by 3.7v batt (output ~8v with reg) so it is simply just a battery connection and BT module, but when uploading the sketch, it fails. I am relatively new to arduino, and am not sure where to begin this debug.

I am using PC windows, and using a BT dongle receiver for connection (maybe this affects port comm?)

Thanks in advance

Here us the error message

    Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

    Sketch uses 1954 bytes (6%) of program storage space. Maximum is 32256 bytes.

    Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables.
    Maximum is 2048 bytes.

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for
    suggestions.

    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x04

title: Failed HC-05 Bluetooth sketch upload - (port and board correct)

Answers: 1

body: when uploading the code, did you ensure disconnecting the Rx, Tx pins from the Arduino? Coz this is a similar error you get when you upload code with your comm pins connected. Try uploading the code with no wires connected.


body:
I was able to set up a Arduino Nano with an I2C board very easily, but the Arduino Nano Every is giving me a much harder time (my project required low profile).

Just to test, I stripped some wires, and looped them into the board, I'm not sure I want to solder on the pins as they may be too tall. Anyways, just trying to get a proof of concept going right now.

Here's how it's connected:

[![My shitty POC][1]][1]

based on this pin diagram: https://i2.wp.com/rosmianto.com/wp-content/uploads/2019/05/Untitled-Diagram-4.png?fit=1506,1974&ssl=1

The screen lights up so I know the 5v and Ground connections work, but when I scan for I2C devices with i2c_scanner, it sees no devices.

    18:20:56.254 -> Scanning...
    18:20:56.289 -> No I2C devices found
    18:20:56.289 ->
    18:21:01.265 -> Scanning...
    18:21:01.265 -> No I2C devices found
    18:21:01.300 ->

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

title: "No I2C devices found" Arduino Nano Every

Answers: 1

body: Looping the wires through the board and not soldering them is probably your problem. That's not going to make a very good connection. You may get power and ground that way, but digital signals like I2C comms are going to see a LOT of noise.


body:
So I've been looking into branchless programming to speed up code and I'm curious as to how exactly Arduino (or rather atmega328) actually reads machine instructions. Does it have a memory cache or does it read every instruction from the flash memory?

From my understanding of branchless programming it speeds up the computation because the CPU does not have to jump inside the instructions and can read it sequentially, hence does not need to load in new instructions in case it has to jump to a location that's not loaded.

My question is, does this apply to the atmega328? If it reads every instruction straight from flash without using a cache then it shouldn't matter much if it has to jump in the instructions, right?

title: Branchless programing on arduino?

Answers: 1

body:
There is no cache, so you don't need to worry about that. All instructions are fetched direct from flash and executed straight away.

There is, though, a 2-stage pipeline. That means that in one clock cycle an instruction is fetched from flash, and in the next clock cycle it's executed - and while that is being executed the next instruction is being fetched ready.

That means that when a branch occurs, since the AVR uses a very very simplistic approach to branch prediction (i.e., it assumes the branch will not be taken and just loads the next instruction regardless), it has to discard the contents of the pipeline and start from scratch.

That's only a one clock penalty while it loads the newly-branched-to instruction, but it's still a penalty.

Cache is only needed when the CPU core runs faster than the memory can be accessed. Since the AVR only runs at up to 20MHz that is considerably slower than the flash can be accessed, so adding cache would be completely pointless. Other faster MCUs do use caching, such as the 200MHz PIC32MZ, since otherwise "wait states" would have to be introduced to slow the reading from flash down.


body:
    when i write this code in esp8266, it's work fine. but when i tried that code in esp32 with some changes,it shows error on compile time:

    board which i use : DOIT ESP32 DevKit v1

error is:

    In file included from C:\Users\Gabbar Singh\Documents\Arduino\ESP32_OTA\ESP32_OTA.ino:5:0:
    C:\Users\Gabbar Singh\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\HTTPUpdate\src/HTTPUpdate.h:47:6: error: multiple definition of 'enum HTTPUpdateResult'
     enum HTTPUpdateResult {
          ^
    In file included from C:\Users\Gabbar Singh\Documents\Arduino\ESP32_OTA\ESP32_OTA.ino:3:0:
    C:\Users\Gabbar Singh\Documents\Arduino\libraries\ESP32httpUpdate\src/ESP32httpUpdate.h:59:6: note: previous definition here
     enum HTTPUpdateResult {
          ^
    Multiple libraries were found for "WiFi.h"
     Used:C:\Users\GabbarSingh\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\WiFi
     Not used: C:\Program Files (x86)\Arduino\libraries\WiFi

and the last error is : exit status 1
                        Error compiling for board DOIT ESP32 DEVKIT V1.

    Code:

    #include <Update.h>
    #include <WiFi.h>
    #include <ESP32httpUpdate.h>
    #include <WiFiClient.h>
    #include <HTTPUpdate.h>
    #include <HTTPClient.h>

    #define LED_BUILTIN 2

    const String FirmwareVer = {"1.4"};

    #define URL_fw_Version "http://vadaliya2007.000webhostapp.com/atte/ota/version.txt"
    #define URL_fw_Bin "http://vadaliya2007.000webhostapp.com/atte/ota/firmware.bin"
    HTTPClient http;

    const char* ssid = "Honor8X";
    const char* password = "1414141414";

    void FirmwareUpdate()
    {
      http.begin(URL_fw_Version, "5b fb d1 d4 49 d3 0f a9 c6 40 03 34 ba e0 24 05 aa d2 e2 01"); // check version URL
      delay(100);
      int httpCode = http.GET();            // get data from version file
      delay(100);
      String payload;
      if (httpCode == HTTP_CODE_OK)         // if version received
      {
        payload = http.getString();  // save received version
        Serial.println(payload );
      }
      else
      {
        Serial.print("error in downloading version file:");
        Serial.println(httpCode);

      }

      http.end();
      if (httpCode == HTTP_CODE_OK)         // if version received
      {
        if (payload.equals(FirmwareVer) )
        {
          Serial.println("Device already on latest firmware version");
        }
        else
        {
          Serial.println("New firmware detected");
          WiFiClient client;

          // The line below is optional. It can be used to blink the LED on the board during flashing
          // The LED will be on during download of one buffer of data from the network. The LED will
          // be off during writing that buffer to flash
          // On a good connection the LED should flash regularly. On a bad connection the LED will be
          // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second
          // value is used to put the LED on. If the LED is on with HIGH, that value should be passed
          //ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);

          t_httpUpdate_return ret = ESPhttpUpdate.update(URL_fw_Bin, "", "5b fb d1 d4 49 d3 0f a9 c6 40 03 34 ba e0 24 05 aa d2 e2 01");

          switch (ret) {
            case HTTP_UPDATE_FAILED:
              Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
              break;

            case HTTP_UPDATE_NO_UPDATES:
              Serial.println("HTTP_UPDATE_NO_UPDATES");
              break;

            case HTTP_UPDATE_OK:
              Serial.println("HTTP_UPDATE_OK");
              break;
          }
        }
      }
    }

    unsigned long previousMillis = 0;        // will store last time LED was updated
    const long interval = 30000;

    void repeatedCall() {
      unsigned long currentMillis = millis();
      if ((currentMillis - previousMillis) >= interval)
      {
        // save the last time you blinked the LED
        previousMillis = currentMillis;
        FirmwareUpdate();
      }
    }

    void setup()
    {
      Serial.begin(115200);
      Serial.println("");
      Serial.println("Start");
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED)
      {
        Serial.print("O");
        delay(500);
      }
      Serial.println("Connected to WiFi");
      pinMode(LED_BUILTIN, OUTPUT);
    }
    void loop()
    {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(100);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(100);                       // wait for a second
      repeatedCall();
    }

title: Error occurs when compiling ESP32 self-update firmware code

Answers: 1

body: the error is i used two libraries esp32httpupdate and httpupdate, which both have same function so i remove the other one(httpupdate)... and now problem is solved.


body:
i'm trying to get control an Aplus chip aMTP32M (stores audio samples) with Arduino . this amtp32m ic provide CPU SERIAL MODE its come with DATA and CLOCK pin.i try Spi mode with Amtp32m ic but its not working.

Please help me for this.
Link for  for DATASHEET of AMTP32M IC -[http://www.aplusinc.com.tw/proimages/Mtp Vioce Ic/aMTP32M/aMTP32M/Datasheet/aMTPxxM-Datasheet_V1.1_20141216.pdf][1]

  [1]: http://www.aplusinc.com.tw/proimages/Mtp Vioce Ic/aMTP32M/aMTP32M/Datasheet/aMTPxxM-Datasheet_V1.1_20141216.pdf

title: Help me for interfacing Arduino with AMTP32M VOICE IC

Answers: 2

body:
according to this :
[![enter image description here][1]][1]
it's more similar to I2C than SPI. anyway, it's just 2 wire custom serial interface. you can use any 2 GPIOs for this purpose.
for sending a byte, you have to:

 1. initialize 2 GPIOS (CLK_IO and DAT_IO) to output, high.
 2. set DAT_IO low
 3. wait at least 1us (according to datasheet ver 1.1, page 18) then set CLK_IO low.
 4. place the D0 bit value on the DAT_IO
 5. toggle the CLK_IO (set it high, wait at leas 1us, set it low)
 6. do steps 4 and 5 for all the remaining bits.
 7. at the end set CLK_IO high
 8. wait for at least 1us and set the DAT_IO high.

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

body:
Finely i try the below code for serial mode. it's worked perfectly...

    type def union
      {
    unsigned char BYTE;
    struct
    {
        unsigned        BIT0:1;
        unsigned        BIT1:1;
        unsigned        BIT2:1;
        unsigned        BIT3:1;
        unsigned        BIT4:1;
        unsigned        BIT5:1;
        unsigned        BIT6:1;
        unsigned        BIT7:1;
    };
    }ByteToBit;

    void Play(unsigned char Val)
    {
      ByteToBit SectionNo;

      SectionNo.BYTE = Val;

    CLOCK = 1;
    DATA  = 0;
    CLOCK = 0;

    DATA  = SectionNo.BIT0;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT1;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT2;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT3;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT4;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT5;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT6;
    CLOCK = 1;
    CLOCK = 0;
    DATA  = SectionNo.BIT7;
    CLOCK = 1;
    CLOCK = 0;

    DATA  = 0;
    CLOCK = 1;
    DATA  = 1;

    return ;
    }

     void main(void)
     {
        unsigned char SectionNo;

    CLOCK = 1;
    DATA  = 1;

    SectionNo = 0x00;
    while(1)
    {
        Play(SectionNo);
        Delay_1mS();        // Wait for BUSY set up time...
        while(BUSY);        // Voice playing...
        SectionNo++;
    }

    return ;
    }


body:
Im building a arduino based bicycle speedometer. When the code starts the user picks his bike size (which I need to calculate the radius). Then I have a state finite machine where the user taps the button between speed, time and temperature. I need to put this circuit on a battery and it needs to be mounted on a bike. But every time you plug and unplug the battery, the code runs from the beginning again, which I don't want. So every time the user turns the speedometer off then on, he needs to pick his bike size again. Is it possible to save the size he has picked so that the next time he turns it on, it doesn't come across.

So - user has his speedometer, turns it on, picks the bike size, turns it off, then sometime later turns it back on and the part for picking the bike size doesn't show up, it simply "knows" remembers what the user picked last time.

I don't know how could that work, would the Arduino run the certain code only once or is there a function for "the next time Arduino has electricity behave like this".

title: How to save a state - make an arduino run a code only once/make aruduino bahave differently the next time he is on

Answers: 1

body:
As one of the comments said, you will need to use the [EEPROM][1] library. When you save a variable in your code (e.g. `int test = 10;`) the variable along with its value gets stored in the RAM. The EEPROM is a piece of harddisk on your arduino that will remember its value when you power off your arduino.

If you implement a power-off button, simply save the state (or in your case, the wheel size) in EEPROM whenever the user inputs it. The next time you power up, you can check if there is a previous value in EEPROM and continue with that value if it exists. Otherwise ask the user for their wheel size.

You might want to implement a reset-button as well, to reset whenever you change bike or wheels. Look up a code example of EEPROM, as there are a lot online.

  [1]: https://www.arduino.cc/en/Reference/EEPROM


body:
I have a problem. I don’t know how to combine this two codes & the diagram. My project is about automatic water storage door that using water sensor & rain sensor. The rain sensor will function when rain while the water sensor will control the open/close door. The door will open when it rain but it will remain close when the volume in the water storage is full.the volume of water in tank was controlled by flood sensor(water sensor). Here is the code for two sensor.

rain sensor
const int senmin = 0;
const int senmax = 1024;
int led = 13;
int sensory = A0;
int i;
void setup() {
  Serial.begin (9600);
  pinMode(led, OUTPUT);
}

void loop() {
  int sensor = analogRead(sensory);
  int range = map(sensor, senmin, senmax, 0, 3);

  switch (range)
  {
    case 0:
      Serial.println("raining");
      digitalWrite(led, HIGH);

      break;

    case 1:
      Serial.println("not raining");
      digitalWrite(led,LOW);
  }
  delay(500);

}

water sensor

const int waterSens = A0; //define water sensor
const int led = 9;//define led to pin 9
int waterVal; //define the water sensor value

void setup() {
pinMode(led, OUTPUT); //set led as an output
pinMode(waterSens, INPUT);//set water sensor as an input
Serial.begin(9600);  //start the serial port at 9600 bauds

}

void loop() {
  waterVal = analogRead(waterSens); //read the water sensor

  Serial.println(waterVal); //print the value of the water sensor to the serial monitor

if (waterVal <= 0){
  digitalWrite(led, HIGH);//if the water sensor senses water turn the led on
}
else{
  digitalWrite(led, LOW);//if it doesn't sense anything turn the led off
}
}

title: How to combine this two sensor code

Answers: 0


body:
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Nano, ATmega328P"

Sketch uses 934 bytes (3%) of program storage space. Maximum is 30720 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49

An error occurred while uploading the sketch

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x49

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

title: I cannot upload any code to my arduino nano

Answers: 2

body: I had the same problem with an Arduino Micro. When the upload starts, press once the reset button.

body:
For me selecting the `ATmega328P (Old Bootloader)` from the **Tools** --> **Processor** menu in the Arduino IDE solved the problem.

See: https://gyorgybalassy.wordpress.com/2020/10/16/arduino-programmer-is-not-responding-not-in-sync-error/


body:
I have two characters, that I get by Bluetooth.

    char a = SerialBT.read();
    char b = SerialBT.read();
According to the [Arduino Reference][1], decoded data stored in a char gets encoded to ASCII text.

I want to combine them in an Intenger, but the following methods don't work:

    int c = a + b;

    int c = (int)a + (int)b;

    int c = (a - 48) + (b - 48);

and

    String c;
    c.setCharAt(0, a);
    c.setCharAt(1, b);
Thank you

  [1]: https://www.arduino.cc/reference/en/language/variables/data-types/char/

title: Convert character to Integer while leaving encoded

Answers: 2

body:
OK, so after the lengthy requests for clarifications, it appears that
you are receiving a number in ASCII decimal (`"12"`) and want to parse
it into an integer.

You may use the `parseInt()` method of the serial object, like:

```cpp
int c = SerialBT.parseInt();
```

This can however make you program quite slow, as `parseInt()` uses a
timeout to know when to stop expecting more digits.

If you already have read the bytes, you can combine them with simple
arithmetics:

```cpp
int c = 10 * (a - '0') + (b - '0');
```

Note that `'0'` is the same as 48, only it makes more explicit the
intent of your code.

body:
Use an AND mask to convert the character to a digit:

```c
int c = 10 * (a & 0x0F) + (b & 0x0F);
```

When ASCII was invented, the digits `0` to `9` were encoded in hexadecimal as `30` to `39` to enable easy conversion to/from digits and characters.

To convert a digit to ASCII, OR the byte with 0x30:
```c
byte digit = 5;
char character = digit | 0x30;
```
To convert a character to a digit, AND it with 0x0F:
```c
char character = '5';
byte digit = character & 0x0F;
```
These logical operators are faster and more efficient than mathematical operations + and -.


body:
After a lot of help from you guys (huge thanks) Ive completed my code and gone to test it. unfortunately though one line of code `weight = (tip_read.get_units());` stops anything from happening and on the mode one, two or three sub programs it freezes somewhere in there. Any and all help and advice is welcome as Ive been trying to fix this all day and got literly nowhere.
```
#include <HX711.h>

#include <Wire.h>  // IC2 communication

#include <LiquidCrystal_I2C.h>  //LCD
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

int max_load;
int interval;
int max_load_prev;
int interval_prev;
int mode;
float handle_weight;
float tip_weight;
int stop1;
int mode_previous;
int interval_sum;

int mode1 = 53;
int mode2 = 51;
int mode3 = 49;
int start1 = 39;
int start2 = 37;
int increment = 47;
float potentiometer1 = A0;
float potentiometer2 = A1;
int tare_1 = 45;
int tare_2 = 43;

//stepper motor controller
int stepPin = 12;
int dirPin = 13;

#
//sensor readings
  HX711 tip_read;
  HX711 handle_read;
  #define DOUT_tip  4
  #define DOUT_handle  6
  #define CLK_tip  3
  #define CLK_handle  5

  //saving to array//
  float data_storage_array[400][3];

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

  lcd.init();
  lcd.backlight();

  pinMode(mode1, INPUT);
  pinMode(mode2, INPUT);
  pinMode(mode3, INPUT);
  pinMode(start1, INPUT);
  pinMode(start2, INPUT);
  pinMode(increment, INPUT);
  pinMode(stop1, INPUT);
  pinMode(potentiometer1, INPUT);
  pinMode(potentiometer2, INPUT);

  //sesnor readings

  tip_read.begin(DOUT_tip, CLK_tip);
  tip_read.set_scale(194);// change to calibration factor

  handle_read.begin(CLK_tip,CLK_handle);
  handle_read.set_scale(43.5);// change to calibration factor

  pinMode(tare_1, INPUT);
  pinMode(tare_2, INPUT);

  Serial.begin(9600);

  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  mode_previous = 0;
  interval = 25;
  max_load_prev = 0;
  interval_prev = 0;
  interval_sum = 0;
  while (digitalRead(start1) == 0){
    if (digitalRead(mode1) == 1){
      mode = 1;
    }
    if (digitalRead(mode2) == 1){
      mode = 2;
    }
    if (digitalRead(mode3) == 1){
      mode = 3;
    }
    if (mode_previous != mode){
      Display_mode_set_up(mode);
      mode_previous = mode;
    }
    if (digitalRead(increment) == 1){
      delay(500);
      if (interval >= 1000){
         interval = 25;
      }
      else if (interval < 1000){
        interval = interval + 25;
      }
    }
    max_load = max_load_reading();
    if (max_load_prev != max_load or interval_prev != interval){
      Display_value_set_up(max_load, interval, mode);
      max_load_prev = max_load;
      interval_prev = interval;
    }
   Display_output(handle_weight, tip_weight);
   tare_one();
  }
  if (mode == 1){
    mode_one(max_load, tip_weight);
  }
  else if (mode == 2){
    mode_two(max_load, interval, handle_weight);
  }
  else if (mode ==3){
    mode_three(max_load, interval, handle_weight);
  }
  Pause_stop();

}

//---SUB ROUTINES---

void mode_one(int max_load, float tip_weight){
  tip_weight = read_tip();
  while (tip_weight < max_load){
    tip_weight = read_tip();
    turn_motor();
    Pause_stop();
    Display_output(handle_weight, tip_weight);
  }
}

void mode_two(int max_load, int interval, float handle_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    while (digitalRead(start2) == 0){
      delay(1);
    }
  }
}

void mode_three(int max_load, int interval, float handle_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    delay(1000);
  }
}

void tare_one(){
  if (tare_1 == HIGH) {
    tip_read.tare();
  }
  if (tare_2 == HIGH) {
    handle_read.tare();
  }
}

void turn_motor(){
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

float read_tip(){
  float weight;
  weight = (tip_read.get_units());
  return weight;
}
float read_handle(){
  float weight;
  weight = (handle_read.get_units());
  return weight;
}

void save_to_array(int interval_sum){
  data_storage_array[interval_sum][0] = interval_sum;
  data_storage_array[interval_sum][1] = tip_read.get_units();
  data_storage_array[interval_sum][2] = handle_read.get_units();
  interval_sum = interval_sum + 1;
}

int max_load_reading(){
  int KG_value;
  int g_value;
  int load_max;
  KG_value = analogRead(potentiometer1);
  g_value = analogRead(potentiometer2);
  KG_value = KG_value * 2;
  KG_value = KG_value/ 100;
  KG_value = round(KG_value);
  KG_value = KG_value* 100;
  g_value = g_value/ 10;
  g_value = round(g_value);
  if (g_value >= 100){
    g_value = 99;
  }
  load_max = KG_value + g_value;
  return load_max;
}

void Pause_stop(){
  if (digitalRead(stop1) == 1){
    delay(1000);
    while (digitalRead(start1) == 0){
      if (digitalRead(stop1) == 1){
        motor_unwind();
      }
      else{
        delay(100);
        lcd.setCursor(0, 2);
        lcd.print("Program Paused");
      }
    }
    lcd.setCursor(0, 2);
    lcd.print("                    ");
  }

}

void motor_unwind(){
  tip_weight = read_tip();
  while (tip_weight < 100){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  int count = 100;
  while (count > 0){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
    count = count -1;
  }
}

void Display_mode_set_up(int mode){
  lcd.setCursor(0, 0);
  if (mode == 1){
    lcd.print("Mode: Max           ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:---");
  }
  if (mode == 2){
    lcd.print("Mode: Incrimental    ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  if (mode == 3){
    lcd.print("Mode: Automatic      ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  lcd.setCursor(0, 3);
  lcd.print("Tp:");
  lcd.setCursor(9, 3);
  lcd.print("Hdle:");
}

void Display_value_set_up(int max_load, int interval, int mode){
  if (mode == 1){
    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);
  }
  if (mode == 2 or mode == 3){

    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);

    lcd.setCursor(17, 1);
    lcd.print("   ");
    lcd.setCursor(17, 1);
    lcd.print(interval);
  }
}

void Display_output(float handle_weight, float tip_weight){
  tip_weight = read_tip();
  handle_weight = read_handle();
  lcd.setCursor(3, 3);
  lcd.print("   ");
  lcd.setCursor(3, 3);
  lcd.print(tip_weight);
  lcd.setCursor(14, 3);
  lcd.print("    ");
  lcd.setCursor(14, 3);
  lcd.print(handle_weight);
}

title: Several lines of code stop program from running?

Answers: 0


body:
I'm using ESP8266 and 4 dot Matrix Tiles, to display clock ( updates using NTP and WiFi ).
Everything is working well, but only when I'm constructing text using a `const char*` type.

But, since I wish to construct text as `sprintf(temp, "12:00");` or `char temp[20]="12:00\n;` creates gibberish text.

    MD_Parola dotMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

    void updateTime()
    {
      char clk[10];
      char dat[10];
      char temp[10];
      sprintf(temp, "12:00"); // <---- this ways failes
      const char *t = "12:00"; // <---- this way succeeds
      dotMatrix.displayText(t, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
    }

[link to library][1]

Appreciate explanation how to construct text not as `const char*`

  [1]: https://majicdesigns.github.io/MD_Parola/class_m_d___parola.html

title: MD_Parola display issue when constructing test

Answers: 1

body:
The library documentation states:

> The library does not allocate any memory for the text message

That suggests, that the buffer has to be valid beyond the execution of the `displayText()` function. But as you declare it inside of your `updateTime()` function, it the buffer gets out of scope, when exiting that function. The memory space can then be reused by the rest of the program. At that point the library will still have the pointer to the old location, though that pointer can now be considered invalid. Thus you are just reading, what the compiler decided to place in that memory location.

To solve that, you need to keep the buffer variable in scope. You can do this by moving the declaration to the global scope.


body:
I have code that fetches analog input values from terminals A0, A1 and A2 of an Arduino Mega 2560. When I plot the data, it does not give the desired waveform.

The desired waveform is also measured with a the digital storage oscilloscope.

I was thinking to make use of an Arduino Mega 2560 as an oscilloscope that can have 16 channels, because the DSO has only 4 and for a project, I urgently need 16 channels. Would be great if the community people suggest something.

[![Data read by Arduino-MATLAB interface][1]][1]

Below is the desired data from the oscilloscope that is measured in parallel to avoid any confusion about the circuit.

[![Desired data measured parallel by an oscillopse][2]][2]

    %This is a script that will plot Arduino analogRead values in real time
    %Modified from http://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/
    %The code from that site takes data from Serial

    clear all
    close all
    clc

    %User Defined Properties
    a = arduino('Com5')             % define the Arduino Communication port
    arduino=serial('COM5','BaudRate',9600);
    s1 = serial('COM5');                                                       % Define here YOUR serial port
    s1.BaudRate=9600;

    plotTitle = 'Arduino Data Log';  % plot title
    xLabel = 'Time (s)';     % x-axis label
    yLabel = 'Voltage (V)';      % y-axis label
    legend1 = 'Voltage 1'
    legend2 = 'Voltage 2'
    legend3 = 'Voltage 3'
    yMax  = 5                           %y Maximum Value
    yMin  = 0                       %y minimum Value
    plotGrid = 'on';                 % 'off' to turn off grid
    min = 0;                         % set y-min
    max = 5;                        % set y-max
    delay = .01;                     % make sure sample faster than resolution

    �fine Function Variables
    time = 0;
    data = 0;
    data1 = 0;
    data2 = 0;
    count = 0;

    %Set up Plot
    plotGraph = plot(time,data,'-r' )  % every AnalogRead needs to be on its own Plotgraph
    hold on                            %hold on makes sure all of the channels are plotted
    plotGraph1 = plot(time,data1,'-b')
    plotGraph2 = plot(time, data2,'-g' )
    title(plotTitle,'FontSize',15);
    xlabel(xLabel,'FontSize',15);
    ylabel(yLabel,'FontSize',15);
    legend(legend1,legend2,legend3)
    axis([yMin yMax min max]);
    grid(plotGrid);

    tic

    while ishandle(plotGraph) %Loop when Plot is Active will run until plot is closed

    %          dat = readVoltage(a,'A0')* 0.48875855327; �ta from the arduino
    %          dat1 = readVoltage(a,'A1')* 0.48875855327;
    %          dat2 = readVoltage(a,'A2')* 0.48875855327;

             dat = readVoltage(a,'A0')* 1; �ta from the arduino
             dat1 = readVoltage(a,'A1')* 1;
             dat2 = readVoltage(a,'A2')*1;

             count = count + 1;
             time(count) = toc;

             data(count) = dat(1);
             data1(count) = dat1(1)
             data2(count) = dat2(1)

             %This is the magic code
             %Using plot will slow down the sampling time.. At times to over 20
             %seconds per sample!
             set(plotGraph,'XData',time,'YData',data);
             set(plotGraph1,'XData',time,'YData',data1);
             set(plotGraph2,'XData',time,'YData',data2);

              axis([0 time(count) min max]);

              %Update the graph
              %pause(delay);
      end

    delete(a);

    disp('Plot Closed and arduino object has been deleted');`

  [1]: https://i.stack.imgur.com/llNe9.jpg
  [2]: https://i.stack.imgur.com/pe0Fm.jpg

title: The analog read is not giving the correct waveform as that of an oscilloscope

Answers: 1

body:
Your sampling rate is far too low for the signals you are looking at; you're not getting enough data points for drawing something that looks like the original signal.

The Arduino library's `analogRead()`, while slow, can do better, up to about 9000 samples/s; the ADC in the atmega2560 in free-running mode can do about 75000 samples/s at 8 bits resolution. This would require programming it at the register level.

There is only one ADC, so if you want 16 channels, this leaves about 4700 samples/s for each channel. In that configuration, however, the first measurements aren't valid and the second ones should be used, further reducing the sample rate per channel to about 2300 samples/s.

With a perfect reconstruction filter, this would limit you to measuring signals up to only 1150 Hz.

All this doesn't even consider the time it takes to store or transmit the results.

So, an Arduino Mega 2560 will not do for making a usable 16-channel oscilloscope for your signals; it's not even close.


body:
i bought the HM 10 Bluetooth controller (CC2541), i got connect on this device through Serial Bluetooth Terminal (Android App) [with Serial BLE menu][1] this method not requires any pass and "Connected" state is showed and the led on CC2541 is always HIGH now, but... any command sended from terminal or sended from serial arduino is not show and "AT+NAME" or "AT+NAME?" returns null everytimes, this is my code to run Bluetooth on Arduino Mega2560:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(26, 27); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("Goodnight moon!");

      delay(500);

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!");
    }

    void loop() // run over and over
    {
      if (mySerial.available()) {
        String s = "";
        char c;
        while((c = mySerial.read()) != -1) {
          s += c;
          delay(10);
        }

        Serial.println("Received: " + s);
      }

      if (Serial.available()) {
        String s = "";
        char c;
        while((c = Serial.read()) != -1) {
          s += c;
          delay(10);
        }

        delay(10);

        Serial.println("Sent: " + s);

        mySerial.print(s);
      }
    }

Example of output serial monitor:

    Sent: AT+DEFAULT

    Sent: AT+BAUD9600

    Sent: AT+HELP
 I never receive "Received" status...

  [1]: https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal&hl=pt_BR

title: CC2541 Bluetooth AT Commands not work for any Commands sended from Serial

Answers: 0


body:
This page https://store.arduino.cc/usa/mega-2560-r3 contains an image under the Documentation section which shows digital pins 10 to 13 with labels SS, MOSI, MISO, and SCK.

**EDIT:** The documentation page has since been updated with the correct pin assignment as discussed below. The image has been removed to stop it from showing up in "mega SPI pinout" searches and continuing to spread wrong information.

However, this page says that those are at pins 50 to 53 https://www.arduino.cc/en/reference/SPI.

[![table from SPI page][2]][2]

Which page is correct?

  [2]: https://i.stack.imgur.com/Y85w8.png

title: Wrong documentation for Mega2560 SPI Pins?

Answers: 1

body:
The image is incorrect, unfortunately.

The SPI pins are below:

    PB0 - #SS
    PB1 - SCK
    PB2 - MOSI
    PB3 - MISO
[![enter image description here][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/6Ic3N.png
  [2]: https://i.stack.imgur.com/jNsas.png
  [3]: https://i.stack.imgur.com/BUydA.png


body:
I'm creating a  controller for a small greenhouse, I have a DHT22 for measuring and two relay module that controls heating and cooling systems, and I will use a piezo to produce humidity when it goes below X amount. This piezo works at 1.7 MHz and I know that Arduino can provide 1.779Mhz, I think It's close enough. After that I'll place a MOSFET at the output and then connect the piezo.

I'm quite new so I'm trying copy-paste some codes and this is what I've done:

**I don't know how to turn on and off the frequency generator, I would like to know the code for that**

               #include <DHT.h>
                #include <DHT_U.h>

                #define DHTPIN 6
                #define DHTTYPE DHT11 //Define sensor as DHT11

                #define RELAY1  4  // Relay heating
                #define RELAY2  5  // Relay cooling

                int red = 8; // red LED heating
                int blue = 9; // blue LED cooling

                DHT dht(DHTPIN, DHTTYPE);

                float temperature;
                float humidity;

                // Frequency Generator code
                const uint8_t OUTPUT_PIN = 3;  // = OC2B pin inamovible
                const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

                void setup()
                {

                  pinMode(red, OUTPUT);
                  pinMode(blue, OUTPUT);
                  pinMode(RELAY1, OUTPUT);
                  pinMode(RELAY2, OUTPUT);

                  // Freq generator code
                    pinMode(OUTPUT_PIN, OUTPUT);
                    TCCR2B = 0;           // stop timer
                    TCNT2  = 0;           // reset timer
                    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
                           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
                           | _BV(WGM21);  // ...ditto
                    TCCR2B = _BV(WGM22);  // ...ditto
                    OCR2A = PERIOD - 1;
                    OCR2B = PERIOD/2 - 1;
                }

                void soundBuzzer() {
                    TCCR2B |= _BV(CS20);  // F_CPU / 1
                }

                void silenceBuzzer() {
                    TCCR2B &= ~_BV(CS20);
                    TCNT2 = 0;
                }
                  //End of freq generator code
                void loop()
                {
                  delay(1000); //delay time between measurements. 1 sec for DHT11

                  temperature = dht.readTemperature(); //Reads temperature
                  humidity = dht.readHumidity(); //Reads humidity

                 if(temperature < 25)
                    {
                digitalWrite(red,HIGH);
                digitalWrite(blue,LOW);

                digitalWrite(RELAY1,0);
                digitalWrite(RELAY2,1);
                     }
                 else if(temperature > 25)
                    {
                digitalWrite(RELAY1,1);
                digitalWrite(RELAY2,0);
                digitalWrite(red,LOW);
                digitalWrite(blue,HIGH);

                }

            if(humidity < 30)
             {
       TCCR2A |= _BV(COM2B1);
        }
            else if(humidity > 35)
                    {
              TCCR2A &= ~_BV(COM2B1);

                }
            }

I don't even know if i'm doing it right, please let me know and thanks

title: 1.7 MHz generator for a water atomizer

Answers: 0


body:
I have this project where I need a modbus tcp server that will host a series of sensor data for other modbus client devices to read. I use this [Library][1] by Andresoarmento

This is the code i am using from the library example:

    #include <EtherCard.h>
    #include <Modbus.h>
    #include <ModbusIP_ENC28J60.h>

    //Modbus Registers Offsets (0-9999)
    const int SENSOR_IREG = 100;
    //Used Pins
    //const int sensorPin = A0;

    //ModbusIP object
    ModbusIP mb;

    long ts;

    void setup() {
        // The media access control (ethernet hardware) address for the shield
        byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
        // The IP address for the shield
        byte ip[] = { 192, 168, 1, 120 };
        //Config Modbus IP
        mb.config(mac, ip);

        // Add SENSOR_IREG register - Use addIreg() for analog Inputs
        int i = 2200;
        mb.addIreg(SENSOR_IREG,i);

        ts = millis();
    }

    void loop() {
       //Call once inside loop() - all magic here
       mb.task();

       //Read each two seconds
       if (millis() > ts + 2000) {
           ts = millis();
           //Setting raw value (0-1024)
           int i = 0;
           i++;
           mb.Ireg(SENSOR_IREG, i);
       }

The enj28j60 module is working as i tested it. So, I used a modbus scanner(CAS SCANNER) which was unable to detect it. Can anyone tell me how to get this all working and test it?

Thank you in advance.

  [1]: https://github.com/andresarmento/modbus-arduino

title: Modbus TCP/IP using Arduino uno and ENC28J60 module

Answers: 0


body:
i am working on uno.
i am using mfrc522.
the module is not detecting aby of the cards. nothing is poping up on the screen.
this is the code-

    #include <deprecated.h>
    #include <MFRC522.h>
    #include <MFRC522Extended.h>
    #include <require_cpp11.h>

    // RFID door access system.

    #include <SPI.h>
    #include <MFRC522.h>
    #include <Servo.h>

    #define SS_PIN 10
    #define RST_PIN 9
    #define LED_G 5 //define green LED pin
    #define LED_R 4 //define red LED
    #define BUZZER 2 //buzzer pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
    Servo myServo; //define servo name

    void setup()
    {
      Serial.begin(9600);   // Initiate a serial communication
      SPI.begin();      // Initiate  SPI bus
      mfrc522.PCD_Init();   // Initiate MFRC522
      myServo.attach(3); //servo pin
      myServo.write(0); //servo start position
      pinMode(LED_G, OUTPUT);
      pinMode(LED_R, OUTPUT);
      pinMode(BUZZER, OUTPUT);
      noTone(BUZZER);
      Serial.println("Put your card to the reader...");
      Serial.println();

    }
    void loop()
    {
      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent())
      {
        return;
      }
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial())
      {
        return;
      }
      //Show UID on serial monitor
      Serial.print("UID tag :");
      String content= "";
      byte letter;
      for (byte i = 0; i < mfrc522.uid.size; i++)
      {
         Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
         Serial.print(mfrc522.uid.uidByte[i], HEX);
         content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
         content.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
      Serial.println();
      Serial.print("Message : ");
      content.toUpperCase();
      if (content.substring(1) == "76 2B E3 93") //change here the UID of the card/cards that you want to give access
      {
        Serial.println("Authorized access");
        Serial.println();
        delay(500);
        digitalWrite(LED_G, HIGH);
        tone(BUZZER, 500);
        delay(300);
        noTone(BUZZER);
        myServo.write(180);
        delay(5000);
        myServo.write(0);
        digitalWrite(LED_G, LOW);
      }

     else   {
        Serial.println(" Access denied");
        digitalWrite(LED_R, HIGH);
        tone(BUZZER, 300);
        delay(1000);
        digitalWrite(LED_R, LOW);
        noTone(BUZZER);
      }
    }

please help me

title: i am working on rfid module and the module is not detecting sny of the cards

Answers: 0


body:
I want to know the recommended wiring for relay. I am setting it up as NO.
1) Where should I connect the relay, the hot wire or the ground wire?
2) Where should I connect the wire going to bulb, NO or C pins of relay? Where should I connect the wire going to AC, NO or C?

title: What is the proper wiring for relay module?

Answers: 2

body:
**Connect the bulb to the NO pin of the relay.**

Image source from: https://ncd.io/relay-logic/

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

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

body:
A relay is a simple switch controlled by an electromagnet coil. The "NO" (normally open) side is off until you apply power to the coil. The "NC" (Normally closed) side is on until you supply power to the coil, at which point it turns off. Switches don't have polarity. If you connect the common into one part of a circuit and the "NO" side into the other, it doesn't matter which goes where.

## Edit:

As another poster pointed out, you **should** wire the relay so it switches the hot leg from the plug, not the neutral (Assuming you're in the US or another country with polarized plugs.) That is much safer, since it means when the relay is off, the lamp is only connected to the neutral line. If, instead, you wire the relay to switch the neutral leg then the lamp will ALWAYS be connected to hot, and if somebody touches the wires they could get a shock.

## Important:
What **does** matter is how you power the relay. If you try to drive a simple relay directly from a logic pin, it will likely damage or destroy the Arduino.

If you're using a "digital" relay that takes a constant 5V source, and a logic level control, such relays have built in transistors and protection diodes that prevent the relay coil from destroying solid state electronics.

If you're using a simple relay, you'll need an appropriate transistor to boost the current to the coil, as well as a "flyback diode" to protect the transistor from back-EMF when the coil is disconnected.


body:
I am trying to make a smart table project. But I have stumbled upon one problem, that is I don't know which display should I use. I need a display that has roughly aspect ratio of 2:1 but also has a relatively high pixel density. I have purchased a 2.42 inch display based on SSD1309 but the display is way too pixelated for my use. Do you have any display recommendations for me?

This is the display that I have bought:

[![2.42" Inch 12864 128 * 64 OLED Display Module IIC I2C SPI Serial White/Blue/Green/Yellow LCD Screen for C51 STM32 SSD1309][1]][1]

The display I am trying to achieve is like this:

[![enter image description here][2]][2]

It looked like the display that I'm trying to achieve uses a custom made display. Is there anyway I can achieve that kind of look (at least similar in quality) with displays on the market?

  [1]: https://i.stack.imgur.com/WYXI2.png
  [2]: https://i.stack.imgur.com/44Glm.png

title: I want a bar type display for my Arduino Project

Answers: 1

body:
As Majenko already stated, the second image shows a custom display. It is not pixelated, because each shown element/symbol has it's own element in the LCD. When you have one of these displays, you might be able to reuse it for your project, but that is advanced.

In the case of pixel based displays with a significantly higher resolution than the standard SSD1309 driven LCD or OLED displays, you are mostly out of luck. There might be fitting products, though they most likely will be expensive and are not as easy to drive, as the standard ones. AVR based Arduinos, like Uno, Nano or Mega, are also not really good for driving high res displays.

The way to go depends on your exact requirements.

- You could - as Majenko suggested - ditch the Arduino and use an old smartphone. If you need more control over the smartphone for your project, than the standard Andriod gives you, you could install an open source OS on the phone.

- You could move to a Single Board Computer, like the Raspberry Pi Zero, and buy a display for it. There are many displays for Raspberry Pis, that should have enough resolution. Though most of them are larger than a normal smartphone display.