# Question
Title: Thermistor returns correct value on Arduino Nano, completely fails on Arduino Uno Wifi Rev 2?
I am completely baffled. When I wire the thermistor into my Nano, everything reads completely fine. Then when I switch to the Uno Wifi Rev 2, I get negative numbers -40 to -80 when I was reading 24 on the Nano.

Wiring Diagram is:

```
           Thermistor
           |       |
Gnd---Resistor     Vcc
           |
       A6/A0 (6 for nano, 0 for Uno)

```

Code is:

```
#include <thermistor.h>
#define pin A6 //I change this to A0 on the WIfi. This is the only change
float temp;
uint32_t timeout = millis();
THERMISTOR thermistor(pin, //Analog pin
                  9800,    //Nominal res at 25 ºC
                  3559,    //Thermistor's B value
                  10000);  //Value of the resistor
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);
  temp = thermistor.read();
  Serial.println(temp);
}

```

# Answer
The Arduino UNO WiFi Rev2 defaults to an internal analog reference of 0.55V where the classic (non-"Every") Nano defaults to the external VCC voltage as a reference, which is usually around 5V, often a little lower because of the diode it uses between USB and "5V".

Either you need to be using the same voltage reference by selecting a common one with analogReference, or you need to use different references and calculate differently (or provide different values to the thermistor library) according to each reference.

If you've been using the VCC on the normal Nano board, you could try `analogReference(VDD);` on the UNO Wifi Rev 2. This isn't necessary a great way to do it (probably using internal references would be better), but it is a simple way to get similar results on a UNO Wifi Rev2 without changing more than a single line to set the reference.
> 1 votes

---
Tags: arduino-nano, arduino-uno-wifi, thermistor
---


# Question
Title: Is there a working combination of Arduino IDE + Ardublock?
I'm trying to set up Ardublock, but the last release they have is from 2014 and in a recent Arduino IDE it fails when I try to upload the program to the Arduino board:

```
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: processing.app.Editor.setText(Ljava/lang/String;)V
    at com.ardublock.ArduBlockTool.didGenerate(ArduBlockTool.java:72)
   ....

```

I assume there is a different API in the recent Arduio IDE for copying the generated code into the editor. This is the block diagram I'm trying to upload. As you can see there are no libraries involved:

Is there a known combination of Arduino IDE and Ardublock which works? Or perhaps an addon similar to Ardublock which is maintained?

# Answer
> 1 votes
I found that Ardublock project was forked on Github, and the latest release indeed works with up-to-date Arduino IDE.

---
Tags: arduino-ide
---


title: Arduino IDE not seeing Arduino library

text:
# Question
Title: Arduino IDE not seeing Arduino library
Working on my first real Arduino project.

I opened my code in the Arduino IDE and hit build and I get errors "not declared in the scope" on every single call to the Arduino library. For instance, digitalWrite, digitalRead, INPUT, OUTPUT, etc.

I open other projects with my Arduino IDE and they build fine, so it's clearly the code in this project. I've restarted. No change.

Ideas?

# Answer
> 0 votes
Still not sure what the problem was, but I included `Arduino.h` and everything worked. This is a hack, but an effective one. If someone else knows what I did wrong, let me know.

---
Tags: ide, build
---


# Question
Title: Arduino with NRF24L01. Getting correct data from unkown transmitter
I want to use my Arduino with this: VAC8010F measure unit. It communicates with NRF24L01. The problem is I simply don't know which band or information it is receiving. Can somebody help me with this?

Thanks for any suggestions!

# Answer
Don't have full details yet. But the VAC8010F uses modbus RS485 protocol. My research shows that the NRF24 just transmitts and receives the MODBUS protocol to and from master/slave. I have found modbus libs and samples of code on the net. There is a command driven program to communicate with MODBUS free for linux, which is the o/s I use. I don't know about win. Anyway, once I receive the MAX485TTL interface for my ARDUINO MEGA I will write code for data logging to p.c. then modify to use the NRF24, as I should be able to extract the ADDRESS, and CHANNELS etc, and packet construct.

Hope this is of some help.

Patrick
> 1 votes

# Answer
Nordic has an app to connect to nRF https://www.instructables.com/Send-Data-to-Mobile-Using-NRF24L01-Using-NRF-As-a-/

The app is available for all platforms. Did not try it myself. Hope this helps. I going to do the same, but want receive it on Android.

If you got some news, please let me know. Thanks
> 1 votes

---
Tags: nrf24l01+
---


# Question
Title: How do I add Gyroscope, Accelerometer, Euler, and Temperature data to one Arduino board?
I have to use a BNO055 to get temperature/accelerometer/Euler/Gyroscope data into one Arduino board for a school project. I am very new to coding so I am not familiar with the commands. I have gotten my BNO055 to give me all the data individually but I am having problems getting them all compiled into one code file to upload. I have googled it but I keep getting links to upload them individually. Posted below is my latest attempt.

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  **Serial**.begin(9600);
  **Serial**.println("Orientation Sensor Test"); **Serial**.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    **Serial**.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  **Serial**.print("Current Temperature: ");
  **Serial**.print(temp);
  **Serial**.println(" Celsius");
  **Serial**.print("");
}

void loop(void)
{
  /* Get a new Sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  **Serial**.print("X: ");
  **Serial**.print(gyroscope.x());
  **Serial**.print(" Y: ");
  **Serial**.print(gyroscope.y());
  **Serial**.print(" Z: ");
  **Serial**.print(gyroscope.z());
  **Serial**.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  **Serial**.print("X: ");
  **Serial**.print(accelerometer.x());
  **Serial**.print(" Y: ");
  **Serial**.print(accelerometer.y());
  **Serial**.print(" Z: ");
  **Serial**.print(accelerometer.z());
  **Serial**.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  **Serial**.print("X: ");
  **Serial**.print(euler.x());
  **Serial**.print(" Y: ");
  **Serial**.print(euler.y());
  **Serial**.print(" Z: ");
  **Serial**.print(euler.z());
  **Serial**.println("");
  delay(100);
}

```

# Answer
Does the code below work? I have no compiler at hand, so I can not test it.

If you have to explain what you have done, you'll get into trouble. I don't know your teacher, but ... ;-). Seriously, that was very basic stuff. Try to find some documentation, how to program with the Arduino IDE and learn the basics. A good startpoint is https://www.arduino.cc/en/Tutorial/HomePage .

Then go on with SENSORs and Vector Maths.

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}

```
> 2 votes

---
Tags: arduino-uno, bno055
---


# Question
Title: Using PWM pins on the UNO to generate Stereo Sound
I am trying to generate stereo sound using an Arduino UNO. Instead of using a separate DAC chip (as shown here), can I use the PWM pins on the UNO along with a low-pass filter?

Also, would I need any additional circuitry if I go this path?

# Answer
> 1 votes
You can generate "stereo sound", but I don't think you'll like it. The PWM frequency is only 490 or 980 Hz, which is going to be plainly audible unless you filter the output very severely. So you'll only be able to produce low frequency sounds, about like what comes out of the woofer speakers in your home stereo. In other words, nothing like music. Might be OK for certain experiments, but nothing you'd want to listen to for pleasure.

As far as additional circuitry, you'll need to convert the DC outputs of your two low-pass filters to AC before you try to drive headphones. This requires a big decoupling capacitor for each channel. If you are going to drive a separate amp, you might be able to skip the capacitors since most amps have them built into the inputs.

---
Tags: arduino-uno, pwm, audio
---


# Question
Title: Power LED Matrix With LiPo Battery & ESP32
I want to power an ESP32 with a 3.7V LiPo battery. There's a LED matrix of 64 WS2812 LEDs attached to the ESP32. I learned that I need a buck boost converter to power the microcontroller as it needs a 5V power input. The boost converter delivers that when there is no matrix attached. However if the matrix is attached it only receives about 2.7V. Turning the potentiometer on the boost converter changes nothing in this case. What is the reason for this? I am sorry if this question seems basic to you. I am an beginner with electronics.

Here is a rather hideous scetch of the connections. I hope this is okay:

This is the buck converter I used: https://www.amazon.de/gp/product/B079H3YD8V/ref=ppx\_yo\_dt\_b\_asin\_title\_o02\_s00?ie=UTF8&psc=1

# Answer
The way you have it set up is fine if you aren't going to light up all the LEDs at full brightness. And if you do, you're not going to break your ESP32 Dev Board the way you have it set up in your diagram (since you are not running the power THROUGH the board). The LiPo battery probably has its own little regulator on it to prevent it from being damaged.

Check your dev board specifications on how much power you actually need to supply to the Vin pin. The ESP32 chip operates between 2.3 and 3.6 volts (3.3 recommended). Your dev board regulates the 5v to provide that amount to the chip.

Most likely, your dev board will run fine on the 3.7V provided by your LiPo without the buck-boost. I use a similar setup (without a buck-boost) to demo little projects to friends. I use a ESP32U-01 dev board from EZSBC, a 64 LED Matrix from Adafruit, and a 3.7v LiPo battery.

Depending on how many LEDs are lit (and what color), you shouldn't expect the battery to last very long. And the overall brightness of your led matrix will be limited.

If you are using the FastLED Animation Library, I would recommend setting a power limit using set\_max\_power\_in\_milliwatts function and limiting it to 1500mW for starters. Again, if you are not drawing power THROUGH the ESP32 board, you're fine.
> 1 votes

---
Tags: led, esp32, battery, ws2812
---


# Question
Title: Fast PWM with Arduino, the inputs outputs don't work
Hello to the community!

I am using ATTINY85 and I am programming it through the AVRISP using an Arduino UNO.

This is the code I am using :

```
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
    PORTB = 0;        //Reset values on port B

    // After setting up the timer counter,
    // set the direction of the ports to output
    DDRB |= (1<<PB1) | (1<<PB0) | (1<<PB3); // PB0, PB1 and PB3

    // PLLCSR - PLL control and status register:
    // PLL is a clock multiplier
    //      - multiplies system 8 MHz by 8 to 64 MHz
    // PLL is enabled when:PLLE bit is enabled,
    // CKSEL fuse is programmed to 0001.  This clock is
    //   switched off in sleep modes!
    PLLCSR |= (1<<PLLE);    // PLL enable

    // Wait until the PLOCK bit is enabled
    // before allowing the PCK to be enabled
    //WaitForPLOCK();
    //unsigned int i = 0;

    while ((PLLCSR & (1<<PLOCK)) == 0x00)
    {
        // Do nothing until plock bit is set
    }

    // Enable asynchronous mode, sets PWM clock source
    PLLCSR |= (1<<PCKE);

    TCCR1 = (1<<CTC1)    | // Enable PWM
            (1<<PWM1A)   | // Set source to pck
            (0<<(CS13))  |
            (0<<(CS12))  |
            (1<<(CS11))  |
            (1<<(CS10))  | // Clear the pin when match with ocr1x
            (1<<COM1A1);
    GTCCR = (1<<PWM1B) | (1<<COM1B1);

    // Set PWM TOP value - counter will count and reset
    //  after reaching this value
    //           OCR1C
    // 100 kHz   159
    // 80 kHz    199
    OCR1C = 199;

    // Enable Timer1 OVF interrupt
    TIMSK = (1<<OCIE1A) | (1<<TOIE1);

    sei();

    OCR1A = 190;  //chaning th FR
}

void loop() {
    PORTB |= (1 << PB3);
    delay(500);
    PORTB &= ~(1 << PB3);
    delay(500);
}

```

the problem is that when I use the PWM my rest of the outputs do not work . Any idea why is this happening?

I am using the ATTINY CORE library from Spence Konde.

# Answer
This line:

```
TIMSK = (1<<OCIE1A) | (1<<TOIE1);

```

enables a couple of interrupts generated by Timer 1. Whenever you enable an interrupt source, you should make sure that the matching ISR has been defined. Otherwise, the interrupt request is routed to `__bad_interrupt()`, which by default jumps to the reset vector, thus resetting your program.
> 5 votes

---
Tags: programming, pwm
---


title: Arduino H-bridge for rc car

text:
# Question
Title: Arduino H-bridge for rc car
I've got an old rc car laying around, of which i would like to swap the insides, but re-use some of the parts that are already in there. The car runs 2 dc motors: one for steering, one for throttle. The dc motors are both connected to H-bridges in the original setup to make their direction switchable. This is done via 8 transistors. 4 for the throttle and 4 for the steering.

The transistors for steering are 2x S8050 (NPN) and 2x S8550 (PNP). For throttle it uses 2x 2SD882 (NPN) and 2x 2SB772 (PNP).

I found a schematic in an online post of a arduino H-Bridge setup. It look promising, but it uses 2n4403 and 2n4401 transistors. I was wondering if I could copy the schematic, replace the Arduino 5v power source (as depicted in de schematic) with the battery voltage source of the car, and replace the transistors in the schematic with one pair of the transistors I described above (so 2x 2SD882 and 2x 2SB772 or 2x S8050 and 2x S8550) Would the arduino be able to switch the described transistors? Would the 1K ohm resistors in between the arduino and the transistors suffice?

I am planning on making this schematic twice, once for throttle and once for steering. The throttle output is max 11.5v and the steering uses around 5v. Therefore the throttle circuit would be powered from the battery voltage and the steering circuit would be powered of a 5v regulator.

Can this be done this way?

# Answer
Just a comment about your diagram. The two transistors should not share an Arduino pin in that way. If the pin is pulled high the transistors saturate and your current 'shoots through' from supply straight to ground. Instead assign one Arduino pin to each transistor (using the base resistor in your diagram).
> 1 votes

---
Tags: arduino-uno, motor, transistor, resistor, h-bridge
---


# Question
Title: How should I decide the cut-off frequency for my low-pass filter?
I'm trying to generate some basic thumping stereo sound using Arduino's PWM pins along with low-pass filters.

This is the frequency spectrum for the sound I want to play using Arduino UNO's PWM pins:

Based on this, I think (from what I understand) the cut-off frequency for the low-pass filter should be around 8900Hz. But, wouldn't the PWM function operate at a much higher frequency to generate the same wave? If that's how it'll be, how should I decide the cut-off frequency for my low-pass filter?

I understand that the fastest frequency one can get for 8-bit PWM on an UNO is 62.5 kHz. So, I might not be able to generate this wave using the UNO itself. Unfortunately, I won’t be able to use another microcontroller for this project. However, what I can do to solve this issue is - generate a different sound wave of lower frequency. If someone can help me with finding out by how much will the frequency of the wave increase if I use PWM to generate it, I’ll be able to generate an appropriate wave.

# Answer
That looks like the spectrum of an 8-bit sound that is playing low bass notes only. Most everything above that looks like noise floor. (You can only get about 6 dB range per bit of resolution, so 8 bits gives about 48 dB max.) If this is the case, you definitely don't want to reproduce the upper frequencies. If you want to stick to your original PWM scheme, use pins 5 or 6 because they use 980 Hz PWM instead of 490. I suggest you determine the filter by trial and error, since it comes down to how much PWM carrier you can tolerate. You can make a simple RC filter using the formula F = 1 / (2 * pi * R * C) where F is the cutoff frequency in Hz, R is ohms, and C is farads (that's 10^6 microfarads per farad). This type of simple filter will have a very soft cutoff frequency, about 6 dB per octave, so if you set it for 123 Hz (3 octaves below 980 Hz) the 980 Hz PWM will be reduced by 18 dB. The R connects to the PWM pin, and the C goes from the other end of R to ground, as does the signal output. The formula assumes that there is no output load, so you should connect an amplifier there. If you are like most folks, you probably have fewer capacitor values on hand than resistor values, so pick the C value first. Let's say it's 1 uFd. Then if you use R=1K the cutoff will be 159 Hz. Change R while listening to the output
> 1 votes

---
Tags: pwm, audio, filter
---


# Question
Title: What terminologies and concepts describe the codes that follow a format of Text1.Text2()?
I'm just really curious because some codes really follow a format like this. Examples include serial.begin(), serial.println() and when I used servomotors the left part was the name of the servomotor, which I declared. I want to know what concept does the code with a format of Text1.Text2() refer to? What do you call Text1 and Text2? Are there official or commonly used terminologies for the concepts and parts such as "variable", "statement", "code"?

To add to my understanding, it appears that Text1 refers to an object and that Text2 has the concept of "function" where it performs something related to the object. Though I would think that another terminology would be possessed by Text2 other than function to distinguish it from a function since it is required to be written in the format I mentioned, which next to the object with a period separating them and no spaces at all.

# Answer
> 1 votes
The over-arching concept is *Object Oriented Programming* (OOP).

The terms I was taught at University - taking `Serial.println()` as an example:

* `Serial` is an *instance* of a *class* (in this case `HardwareSerial`), sometimes called an *object*.
* `println()` (a function in a class) is a *method* of a class.
* A "variable" in a class is called a *property* of a class.

A commented code example:

```

class Foo { // This is the *class*

    public: // These symbols are accessible from outside the class

        int bar; // This is a public property

        void baz() { // This is a public method
        }

    private: // These symbols are only available from inside the class

       int meep; // This is a private property

       void moop() { // this is a private method
       }
};

Foo bar; // Instantiate an instance of the Foo class and call it bar.

```

---
Tags: serial
---


# Question
Title: Making CS (chip select) work in SPI (for and SD card and OLED)
I'm working on a project that will log data to an SD card and display a user interface on an OLED. The SparkFun OLED breakout was super easy to set up. I was also able to get the SD-Card library working independently, though that was harder.

The trouble is when I combine these examples the SD card *only* writes during "setup" after that it isn't writing to the SD card as the loop continues. The OLED still works just fine. I've read up on SPI a bit and tried various things to get "chip select" to work (I suspect this is the problem) I even tried setting the CS pins to LOW or HIGH using digitalWrite, but this had no impact.

My pins are connected as follows:

```
          SD CARD      OLED
MOSI        A5            A5     same pin
MISO        A4            --     just SD connected
SCK         A3            A3     same pin
CS          A1            A2     different pins

```

The SD card writes in the main loop if I comment out all of the code that runs the OLED. The OLED works either way. What could I try next?

Here is the code:

```
 #include "application.h"
 #include "sd-card-library/sd-card-library.h"
 #include "SparkFunMicroOLED/SparkFunMicroOLED.h"
 #include "math.h"

 //////////////////////////////////
 // MicroOLED Object Declaration //
 //////////////////////////////////
 // Declare a MicroOLED object. If no parameters are supplied,
 // default pins are used, which will work for the Photon Micro
 // OLED Shield (RST=D7, DC=D6, CS=A2)
 // Since I use A1 as the chip select pin for the SD card these
 // defaults seem fine.

    MicroOLED oled;

 // Declare a file object?

    File myFile;

 // These are the pins for the SD card. A5, A4, and A3 are all
 // shared by the OLED.

    const uint8_t chipSelectSD = A1;
    const uint8_t mosiPin = A5;
    const uint8_t misoPin = A4;
    const uint8_t clockPin = A3;

 ////////////
 // setup //
 ////////////
 void setup() {
  delay(500);

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("this text was printed to the SD card during setup");
  dataFile.close();

  oled.begin();  // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  delay(1000);  // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.
  randomSeed(analogRead(A0) + analogRead(A7)); //seed to make test pattern random.

               }//end setup

//////////////////
// main loop //
//////////////////
void loop()  {

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("The text was added during the loop.");
  dataFile.close();

//test the display with text and pixels.
  printTitle("Pixels", 1);
  for (int i=0; i<512; i++)
  { oled.pixel(random(oled.getLCDWidth()),  random(oled.getLCDHeight()));
  oled.display(); }
   delay(9000);

               } //end loop

//-------------------------//
// function to print titles //
//-------------------------//
  void printTitle(String title, int font) {
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;
  oled.clear(PAGE);
  oled.setFontType(font);
  // Try to set the cursor in the middle of the screen
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
  middleY - (oled.getFontWidth() / 2));
  // Print the title:
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
                                           } //end title function

```

This is how the SD card is hooked up.

```
  oled.begin();  // Initialize the OLED

```

Any attempt to use the SD card after this line will not work. I've looked for something like "oled.end()" but have not found a way to reset to the state where the SD card works.

I have tried commenting out all of the OLED code and then the SD card writes fine in the main loop. So, I started adding the OLED code back in. This line of code breaks the SD card writing in the main loop:

# Answer
> 1 votes
I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card. Can be any digital pin I think but this one makes the LED blink too). Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH). That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH). This works real fine.

Now I tried to impelment this on a D1-Mini. Cannot get it to work.
SD.begin(D8) starts the first SD fine. By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???

---
Tags: sd-card, spi, display
---


# Question
Title: What is the difference when an arduino has been unplugged vs when a serial port connection was closed?
Using python code for a serial port connection to an arduino, it sends a value to the arduino, which then starts printing values to serial. The python code will print the value on the first or second run (if run soon enough after), but after that it won't read what's from `Serial.println` again. To get it to read again (whether I wait some time or not, like for the while loop to finish), the arduino has to be unplugged and plugged in again, why is that different than the serial port connection being closed by python? Here is the arduino code used,

```
int measured;
int counter = 0;
int maxnum = 10;

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

void loop()
{
  if(Serial.available() > 0)
  {
    while(counter < maxnum)
    {

        Serial.println("V");
        counter++;
        delay(100);

    }
  }
}

```

I know the value sent from python can be read because I added in code that reads from serial after checking if it's available and changed an output pin value, which works, even if the serial println is not read.

Edit: Since the answer is there shouldn't be a significant difference and the arduino script should be reset if the serial port was closed, the issue should be with the python code.

# Answer
> 2 votes
We cannot know, if your python code also has a problem. But your Arduino code will send the series of "V" only once.

You are using this while loop:

```
while(counter < maxnum)

```

in there you are incrementing the variable `counter`. But after you left the while loop, you are never resetting `counter` to zero. So the next time, `counter` is still equal to `maxnum`. Thus the while loop will not run again. To solve that, insert

```
counter = 0;

```

directly after your while loop. Though, for such loops its normally easier to just use a for loop.

---

Also you might have a second problem. Currently the code waits for Serial data to be received. When something is received, the code will enter the

```
if(Serial.available() > 0)

```

statement. But this will stay true, unless you are actually reading the data. Currently the code inside the if statement will be executed on every `loop()` interation forever. So if you are applying the above fix to the first problem, the code will send "V" forever after you send the first byte to the Arduino. To actually only react to data being received, you need to read the data from the buffer - even if you are throwing the data away:

```
Serial.read();

```

---

> What is the difference when an arduino has been unplugged vs when a serial port connection was closed?

For the Arduino itself? Nearly none. Reopening the serial connection will cause the Arduino to reset. The code then starts again from its beginning. Thats also what happens, when you power cycle (replugging) the Arduino. I think there are some little details, where both differ, but that certainly is not the problem here.

For the computer, replugging means, that the USB device (the USB-to-Serial chip on the Arduino to be precise) gets disconnected and again connected. That can lead to the OS allocating a different com-port/device-file for it, than before. Though that doesn't directly do something with the Arduino code (apart from the mentioned power cycle with reset).

For resetting (preserved from comment of OP):

> I found that by setting DTR to 0 then 1, then 0 again, right before closing the port, the arduino resets.

---
Tags: arduino-uno, serial, programming, python
---


title: Passing a method pointer

text:
# Question
Title: Passing a method pointer
I created a small library, which takes a callback function:

```
MyClass::add_callback(bool (*callback_function)(), byte behaviour) {
  // ...
  bool result = callback_function();
  // ...
}

```

So far, I'm using it for periodic polling (for which I don't want to use ISR interrupts). However, I like to use it for other periodic calls that require a state. A simple example is a blinking light, which has an on-off state, as well as knowledge when the next state change needs to occur.

I like to change this method or add another method that takes a method, instead of a function. How should I do this? I'm struggling with the C basics, but answers on StackOverflow seem foccused to more modern C variants. For example, this great answer on Stackoverflow recommends to use boost::bind, but I rather not include such a large dependency.

What I'm looking for is something akin to:

```
MyClass::add_callback(void *obj, bool (*callback_method)(), byte behaviour) {
  // ...
  bool result = Object::callback_method(&obj);
  // ...
}

```

where `Object::callback_method(&obj);` should be equivalent to `Object obj; bool result = obj.callback_method();`.

For bonus points, is it possible to make this independent on the Object class?

I'm happy for pointers to other sites (like StackOverflow), provided it is applicable to a bare Arduino program.

# Answer
The easiest method I know to do this would be to use a "C"-style wrapper for the member function call. This is in fact done to interface C callbacks with C++ objects.

You could do it like this:

```
struct Blinky {
  //state etc.
  bool isOn() { return /* something useful */ true; }
};

// The "C" wrapper for the callback
bool Blinky_callback(void *vblinky)
{
  return static_cast<Blinky*>(vblinky)->isOn();
}

struct MyClass {
  void add_callback(void *obj, bool (*callback_method)(void *), byte behaviour) {
    // ...
    bool result = callback_method(obj);
    // ...
  }
};

// Globals
MyClass c;
Blinky b;

void setup() {
  c.add_callback(&b, Blinky_callback, 0);
}

```

A slightly tidier way with a static member (functionally identical):

```
struct Blinky {
  //state etc.
  bool isOn() { return /* something useful */ true; }

  static bool callback(void *vblinky) {
    return static_cast<Blinky*>(vblinky)->isOn();
  }
};

// ...
c.add_callback(&b, Blinky::callback, 0);

```

Other variants would be using inheritance and virtual functions.

```
// Abstract base class
struct Sensor {
  virtual bool do_check() = 0;
};

struct Blinky : public Sensor {
  bool do_check() override { return true; }
}

```

Then you can have your `add_callback` look like:

```
void MyClass::add_sensor(Sensor *sensor) {
  // ...
  bool result = sensor->do_check();
  // ...
}

```

This is relatively nice to code with, and the compiler has a fighting chance at keeping your code typesafe, if all the "things" you want to control can conform to the same interface. The virtual dispatch won't cost much more (if anything) than the static wrapper in the previous example. You "pay" a few bytes per class and one pointer per instance for the virtual table though.

More modern techniques would involve templates and/or lambdas, or perhaps `std::function`, but all that seems overkill if your need is as described (and might generate a lot more code than you're expecting, or do dynamic allocations for `std::function` which is best avoided in context).

---

Remark: if you want to do it with (non-static) member function pointers, it is possible but the syntax is hairy:

```
void add_callback(Blinky *obj, bool (Blinky::*callback_method)(), byte behaviour) {
  // ...
  bool result = (obj->*callback_method)();
  // ...
}

```

And you're tied to that class. Unless you make `add_callback` a template, but beware extra codegen.
> 3 votes

---
Tags: class, callbacks
---


# Question
Title: How to convert kitchen timer code into a countdown
I found this code for a kitchen timer, it was the closest thing to a countdown. The code is here:

```

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

signed short minutes, secondes;
char timeline[16];

void setup() {

  lcd.begin(16, 2);
  lcd.print("Chronometre :");

}

void loop() {

  lcd.setCursor(0, 1);
  sprintf(timeline,"%0.2d mins %0.2d secs", minutes, secondes);
  lcd.print(timeline);

  delay(1000);
  secondes++;

  if (secondes == 60)
  {
    secondes = 0;
    minutes ++;
  }

}

```

How do I convert it properly for it to countdown from 1 minute and 30 seconds?

# Answer
> 1 votes
As a start, you need to initalise the `secondes` and `minutes` variables to 30 and 1 respectively.

replace `signed short minutes, secondes;` with:

```
signed short minutes = 1;
signed short secondes = 30;

```

Next thing I notice is that the code you have provided counts up and you have requested that it count down.

Change `secondes++;` and `minutes++;` with:

```
secondes--;
minutes--;

```

Lastly you need to change the logic for when the `secondes` and `minutes` variables reach zero.

If the `secondes` variable reaches zero but the `minutes` variable is greater than zero, then you decrement the minutes (using the line of code provided above) and top-up the `secondes` with 59.

```
secondes = 59;

```

You will need to check the value of the `secondes` and `minutes` variables using a couple of if...else statements.

```
if (secondes == 0 && minutes == 0) {
    // insert your timer finished code here
}
else if ( secondes == 0 && minutes > 0) {
    minutes--;
    secondes = 59;
}
else {
    // Error - your code should not reach here.
    // Display an error message on the LCD
}

```

This if..else statement will need to go at the top of your loop instead of the end.

# Answer
> 1 votes
The first thing I recommend is that you don't use sprintf(). Your sketch "program storage space" drops from 3502 bytes down to 1928 bytes by NOT using that function call, and dynamic memory used drops from 101 to 79 bytes.

I would recommend an OOP design that would make it easy to add functionality, like the ability to start, stop and reset the timer.

```
// Arduino Uno, IDE version 1.8.9
// 2330 bytes (7%) of program storage space.
// Global variables use 201 bytes (9%) of dynamic memory.
class CountdownTimer{

  private:

    byte m_hour;
    byte m_minute;
    byte m_second;
    byte m_timerActive;
    byte m_timerComplete;
    unsigned long m_previousMillis;

  public:

    CountdownTimer():
      m_hour(0),
      m_minute(0),
      m_second(0),
      m_timerActive(0),
      m_timerComplete(0),
      m_previousMillis(0){}

    bool Update(){

      if(m_hour == 0 && m_minute == 0 && m_second == 0){
        m_timerComplete = 1;
        return 0;
      }

      if(m_timerActive && (millis() - m_previousMillis >= 1000)){
        m_previousMillis += 1000;
        m_second--;
        if(m_second == 255){
          m_second = 59;
          m_minute--;
          if(m_minute == 255){
            m_minute = 59;
            m_hour--;
            if(m_hour == 255){
              m_hour = 0;
            }
          }
        }
        return 1;
      }
      else{
        return 0;
      }
    }

    byte GetIsTimerComplete(){
      return m_timerComplete;
    }

    void SetHour(byte hour){
      m_hour = constrain(hour, 0, 23);
    }

    void SetMinute(byte minute){
      m_minute = constrain(minute, 0, 59);
    }

    void SetSecond(byte second){
      m_second = constrain(second, 0, 59);
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_timerComplete = 0;
      m_previousMillis = millis();
    }

    void PrintTimeRemaining(){
      if(m_hour < 10){Serial.print("0");}
      Serial.print(m_hour);
      Serial.print(":");
      if(m_minute < 10){Serial.print("0");}
      Serial.print(m_minute);
      Serial.print(":");
      if(m_second < 10){Serial.print("0");}
      Serial.println(m_second);
    }

};

// Make a copy of the object to work with.
CountdownTimer myCountdownTimer;

void setup(){

  // Built in pin 13 LED timer completed indicator.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  // Test output to the serial monitor.
  Serial.begin(9600);

  // Set the countdown timer values,
  // start the countdown timer and
  // print the initial timer setting.
  myCountdownTimer.SetHour(0);
  myCountdownTimer.SetMinute(1);
  myCountdownTimer.SetSecond(30);
  myCountdownTimer.Start();
  myCountdownTimer.PrintTimeRemaining();
}

void loop(){

  // Call the Update function as fast as possible.
  if(myCountdownTimer.Update()){
    myCountdownTimer.PrintTimeRemaining();
  }

  // Turn on the Uno's Pin 13 LED once timer is complete.
  if(myCountdownTimer.GetIsTimerComplete()){
    digitalWrite(LED_BUILTIN, HIGH);
  }

}

```

---
Tags: arduino-uno, timers
---


# Question
Title: Current difference between pinMode(pin, INPUT_PULLUP) and digitalWrite(pin, HIGH)?
Does pin 5 or pin 6 use more power if they're just being used as a signal to an external device?

```
pinMode(5, INPUT_PULLUP);

pinMode(6, OUTPUT);
digitalWrite(6, HIGH);

```

.

EDIT: Thanks to some links below, I hopped thru a series of threads until I found the website www.gammon.com.au/power which did tests with a 328 and found the following results with the pins disconnected (which is different than my question but seems relevant nonetheless):

In SLEEP\_MODE\_PWR\_DOWN:

* All pins as outputs, and LOW: 0.35 µA.
* All pins as outputs, and HIGH: 1.86 µA.
* All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
* All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

# Answer
It all depends on the external device. If it has high-impedance inputs, then it makes no difference. The Arduino itself has high-impedance on its pins configured as `INPUT`. If the device draws current from this signal, then chances are it will draw more current from an `OUTOUT` `HIGH` than from an `INPUT_PULLUP`. How much more? We cannot say without knowing the specifics of that device.

If you model the device as a simple resistor to ground (which is almost certainly *overly* naive), then the current draw is

I = VCC / (R + Ro)

where R is the value of the resistor and Ro the output resistance of the Arduino: about 25 Ω for an `OUTPUT` and 32 kΩ for an `INPUT_PULLUP`.
> 3 votes

---
Tags: power, pull-up
---


# Question
Title: Set interrupts that are not GPIO or Timer in ESP32
I am making a project on ESP32. It reads certain sensor values, stores them in RTC memory and sends them by MQTT after a certain time. I wish that it transmits data immediately if there is a difference of, say 10 units, via an interrupt. I suppose this is not possible by GPIO interrupts and obviously not by a timer as I wish it to happen only if a condition is true and not periodically. I searched on the internet but couldn't find anything except GPIO and Timer interrupts.

**I am working on Arduino IDE.**

Is what I want possible and if yes, how. Please also give a certain example that is in Arduino language for me to study. Also, if it is possible using GPIO interrupts, please tell me how.

Thank you in advance

# Answer
> 0 votes
There is no such thing as an "interrupt on a value changing" since that is something that only exists in software, and interrupts are things triggered by hardware.

All you can do is check the value in `loop()` and send the data if the value is above your threshold. If you want to wake from sleep then you will have to do that periodically through other means.

---
Tags: esp32, interrupt
---


# Question
Title: What is happening when digitalWrite(pinname, LOW) is invoked after pinMode(pinname, INPUT_PULLUP)?
I read the Arduino official docs on digitalWrite and am confused about what is happening from an electrical perspective when digitalWrite is invoked on INPUT\_PULLUP pins.

Say my code says this:

```
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

```

The docs say:

> If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinMode() to INPUT\_PULLUP to enable the internal pull-up resistor. See the Digital Pins tutorial for more information.

Does this mean pin 4 is floating or is it at ground? Are those two lines of code equivalent to `pinMode(4, OUTPUT); digitalWrite(LOW);` ?

# Answer
> 2 votes
It's pretty explicitly stated there in your quote: if you write a LOW when in INPUT mode it disables the pullup resistor. That's all it does.

```
pinMode(4, INPUT);
digitalWrite(4, HIGH);

```

is exactly the same as:

```
pinMode(4, INPUT_PULLUP);

```

And

```
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

```

is exactly the same as

```
pinMode(4, INPUT);

```

Of course this exploits a peculiarity of the AVR's IO block, but any decent core will emulate that functionality for compatibility with older code.

---
Tags: voltage, input, electricity, pull-up
---


title: Buzzer+Push button+arduino

text:
# Question
Title: Buzzer+Push button+arduino
I want to stop the sound of a buzzer after I push the push button. I tried a code, but when the button is not pushed, the buzzer continue to make sound. How can I fixed it?

```
const int pin_contact= 6;
const int buzzer = 9; //buzzer to arduino pin 9

void setup(){
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
  pinMode(pin_contact, INPUT);
  Serial.begin(9600);
}

void loop() {
  tone(buzzer, 200);

  int stare_contact = digitalRead(pin_contact);
  if (stare_contact == HIGH) {
    noTone(buzzer);
  }
}

```

# Answer
> 1 votes
Try this

```
int LEDState = 1;
int SwitchPin = 6;
int LEDPIN = 9;

void setup()
{
  pinMode(LEDPIN,OUTPUT);
  pinMode(SwitchPin,INPUT);
  digitalWrite(LEDPIN,LEDState);
}

void loop()
{

  int SwitchState = digitalRead(SwitchPin);

  if(LEDState==1 && SwitchState==HIGH){
   LEDState = 0;
  }

  digitalWrite(LEDPIN,LEDState);
    delay(10);
}

```

# Answer
> 1 votes
Is your buzzer active low? try this code below. it will toggle buzzer pin output.

```
const int buzzerPin = 9;
const int buttonPin = 6;
int buzzerState = 1;
int buttonState;
int buttonTemp = 0;

void setup() {
  pinMode(buzzerPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  digitalWrite(buzzerPin,buzzerState);
  if (buttonState == HIGH && buttonTemp == 0){
    Serial.print("Buzzer toggle to : ");
    if (buzzerState) {
        Serial.println("LOW");
        buzzerState = 0;
    } else {
        Serial.println("HIGH");
        buzzerState = 1;
    }
    buttonTemp = 1;
  } else if (buttonState == LOW) {
    buttonTemp = 0;
  }
}

```

---
Tags: buzzer
---


# Question
Title: Atmega 328p at 3.3v : Internal vs external oscillator
I am currently working on a pcb that uses smd atmega 328p (au). I will be powering it through a lipo battery and a ldo regulator for 3.3v input. I am using the multiwii flight controller code. I know that atmega runs at 8mhz at 3.3v and 16mhz at 5v without overclocking the chip. The question is that should I use the internal 8mhz oscillator or external 8mhz? I will definitely make the chip more accurate as given in some forums but still does this effects anything or not?

# Answer
If the 8 MHz oscillator is off by a handful of percentage points, it will affect timing measurements you make using millis() and micros(). It could affect the baud-rates of Serial or SoftwareSerial. If these are not of any concern, the only remaining difference would be how fast your code can be executed. It's unlikely that the code pushes the chip runs so close to its maximum capability that it would matter, even at ~8 MHz.

Update:

> ... I just want to know if clock frequency effects the code and if I need to change code a bit like for example blink sketch runs at different time intervals on 8mhz and 16mhz(I tested it).

If you do nothing else, then yes, millis() will appear to run at half speed. You need to add a board definition to the IDE for an Arduino Uno running at 8 MHz. Then millis() and micros will be adjusted for the slower processor clock. How you do this depends on whether you choose the internal and less accurate 8 Mhz oscillator, or an external 16 MHz crystal.

For the internal oscillator, there is a board-definition on Github with instructions to load it into your IDE.

For an external oscillator, this article describes how to select the board type as "Arduino Pro or Pro Mini" and then be able to select the board frequency, using the Tools menu twice.
> 0 votes

---
Tags: atmega328, oscillator-clock
---


# Question
Title: How to receive commands to a running arduino program from a raspberry pi?
I have looked all over for a solution to this. I'm a noob in the arduino space and am really just getting my feet wet. It's possible that I am interpreting what I am reading wrongly. If so I apologize. Here is my problem/question. I want to create an autonomous driving small land drone. It would connect to some drive sensors, dc motors and do some stuff all by itself. In addition to this I want a raspberry pi with a camera surveying the scenery. Because it is unknown if/when the raspberry PI will see something that is interesting i want this default behavior to occur. The reason I want to do it like this is that I read it is better performance to drive from the Arduino because a linux based computer has so much stuff running on it there could be more lag in the response. In addition the python program will be making HTTP requests, doing image processing, and potentially doing even more. If the image processing software on the PI picks up something interesting then I want this functionality to override the Arduino default program. I was thinking to create a program in Arduino for the basic drive functionality but then be listening to a python process that is running on the PI. If it hears a command to go do something, then of course it will drop the default program, go complete the python generated task and once it is done then it will continue with the arduino default program.

How do I in effect listen to a python process from the Arduino? Or would the proper solution be to not even use the Arduino but drive it all from python on the PI? Any suggestions for how to solve this would be great to hear. I feel like there is an obvious best practice way to do this that I am not aware of. Thanks in advance!

# Answer
What you are asking for is not completely trivial, and may be ill-suited for a beginner's project. You will have to create a protocol for the communication between the Raspberry Pi and the Arduino (your own “command language” of sorts), and then implement on the Arduino a command interpreter that understands this protocol and acts accordingly. I highly recommend you use a text-based protocol, as this will be way easier to debug than a binary protocol.

For the Arduino side of the project, you first have to learn how to read the serial port from the Arduino. Then, you can take a look at this very basic command line interpreter for inspiration. Or you can search for Arduino libraries that provide similar interpreters.

On the Python side, you have to open the serial port (`/dev/ttyACM0`) and send your commands through it. The details on how to do that would be a Python question, which is are out of scope here.
> 1 votes

---
Tags: arduino-uno, python, raspberrypi
---


# Question
Title: How to print something when a character touches a character
I am making a stickman rush game, where it goes up and down and then there is a object that scrolls to the left. Whenever that stickman touches the object, it prints game over. However when the object is below the stickman, it prints game over even though its not touching. Can someone explain why this is happening?

Code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT);

   lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);
  lcd.write(byte(1));

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManPosition2 = 0;
  int obsticalPosition2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
  lcd.setCursor(obsticalPosition, 1);
  lcd.write(byte(1));
  lcd.print(" ");
  delay(150);

  xPosition = analogRead(vX);
  yPosition = analogRead(vY);
  SW_state = digitalRead(sw);
  mapX = map(xPosition, 20, 1003, -500, 500);

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

    if (mapX > 200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 0);
    lcd.write(byte(0));

  } else if (mapX < -200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 1);
    lcd.write(byte(0));
    }

  if (stickManPosition == obsticalPosition) {
    lcd.clear();
    lcd.print("Game Over.");
      } else if (
    }
  }

```

Any help would be great.

# Answer
You check StickMan and Object only X position not check Y position
incase you can check StickMan Y or check StickMan action like this code below.
or try this sim https://www.tinkercad.com/things/1LiyoY5n1mS-copy-of-stickman-rush/editel?sharecode=X6rMj1GjrKoAH95qWKY21z98ttyAs5aOTAKYy6hVJ3c

```
// Defind it on top
bool stickManIsJump = false;

// Added some code to check StickMan isJump or not
if (mapX > 200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 0);
  stickManIsJump = true;        /////////////// ADDED
  lcd.write(byte(0));
} else if (mapX < -200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 1);
  stickManIsJump = false;       /////////////// ADDED
  lcd.write(byte(0));
}

if (stickManPosition == obsticalPosition && !stickManIsJump) {      /////////////// ADDED
  lcd.clear();
  lcd.print("Game Over.");
}

```
> 1 votes

---
Tags: arduino-uno, arduino-ide, c++
---


# Question
Title: Using millis() instead of delay() when playing a melody
I want to make my Arduino to play several simple melodies, and also be able to skip a melody by pressing a button and go on with the next song. therefore I cannot use delay() because the code should constantly check if a button is pressed. So I wanted to use millis(), but dont't know how to implement it.

this is how song code looks like with delay():

```
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
//etc...

int tempo=144;

// change this to whichever pin you want to use
int buzzer = 11;

int melody[] = {

  //Based on the arrangement at https://www.flutetunes.com/tunes.php?id=192

  NOTE_E5, 4,  NOTE_B4,8,  NOTE_C5,8,  NOTE_D5,4,  NOTE_C5,8,  NOTE_B4,8,
  // etc...

};

// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
int notes=sizeof(melody)/sizeof(melody[0])/2;

// this calculates the duration of a whole note in ms (60s/tempo)*4 beats
int wholenote = (60000 * 4) / tempo;

int divider = 0, noteDuration = 0;

void setup() {
  // iterate over the notes of the melody.
  // Remember, the array is twice the number of notes (notes + durations)
  for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

    // calculates the duration of each note
    divider = melody[thisNote + 1];
    if (divider > 0) {
      // regular note, just proceed
      noteDuration = (wholenote) / divider;
    } else if (divider < 0) {
      // dotted notes are represented with negative durations!!
      noteDuration = (wholenote) / abs(divider);
      noteDuration *= 1.5; // increases the duration in half for dotted notes
    }

    // we only play the note for 90% of the duration, leaving 10% as a pause
    tone(buzzer, melody[thisNote], noteDuration*0.9);

    // Wait for the specief duration before playing the next note.
    delay(noteDuration);

    // stop the waveform generation before the next note.
    noTone(buzzer);
  }
}

```

I found this code on internet but I don't know how to implement this in above code. when I try to, I get some kind of cursed sound.

```
unsigned long previousMillis = 0;
boolean outputTone = false;

if (millis() - previousMillis >= noteDuration) {
    previousMillis = millis();
    if (outputTone) {
        noTone(buzzer);
        outputTone==false;
    } else {
        tone(buzzer, melody[thisNote], noteDuration*0.9);
        outputTone==true;
    }
}

```

edit1: I tried this:

```
    unsigned long previousMillis = millis();
    int thisNote = 0;

    while (thisNote < notes * 2) {

        // calculates the duration of each note
        divider = lied1[thisNote + 1];
        if (divider > 0) {
            // regular note, just proceed
            noteDuration = (wholenote) / divider;
        } else if (divider < 0) {
            // dotted notes are represented with negative durations!!
            noteDuration = (wholenote) / abs(divider);
            noteDuration *= 1.5; // increases the duration in half for dotted notes
        }

        // play the note
        tone(buzzer, melody[thisNote]);

        check();//check if button is pressed, and if so, changes number to 2
        if (number ==2){
            thisNote=notes*2;
        }
        if ((millis() - previousMillis) >= noteDuration){
           thisNote = thisNote + 2;
           // stop the waveform generation before the next note.
           noTone(buzzer);
        }

     }

```

but it doesn't work, and I don't really understand why

edit2: I changed something, this is probably the closest I have been to a working melody without "delay()". But it is extremely slow.

```
    boolean outputTone = false;
    unsigned long previousMillis = millis();
    int thisNote = 0;

    while (thisNote < notes * 2) {

        // calculates the duration of each note
        divider = lied1[thisNote + 1];
        if (divider > 0) {
            // regular note, just proceed
            noteDuration = (wholenote) / divider;
        } else if (divider < 0) {
            // dotted notes are represented with negative durations!!
            noteDuration = (wholenote) / abs(divider);
            noteDuration *= 1.5; // increases the duration in half for dotted notes
        }

        if (millis() - previousMillis >= noteDuration) {
            previousMillis = millis();
            if (outputTone) {
                noTone(buzzer);
                outputTone==false;
            } else {
                tone(buzzer, melody[thisNote], noteDuration*0.9);
                outputTone==true;
                thisNote = thisNote + 2;
            }
        }

        check(); //checks if button is pressed, and if so, changes number to 2.
        if (number ==2){
            thisNote=notes*2;
        }
     }

```

# Answer
> 1 votes
In essence you will need to break your for loop open and use a global variable for thisNote, incrementing it each loop (with the millis example so that proper timing is still adhered to).

This isn't the only approach to this problem. Your existing code could check for the button press within the for loop and escape the for loop when pressed.

# Answer
> 1 votes
I don't quite understand the code snippets, that you added to your question afterwards (they are partly incomplete). But I will propose my own solution to the problem.

A melody is a list of notes and pauses. Each note has a pitch and a duration. A pause has only a duration. We can now define a struct for holding a note:

```
struct Note {
    unsigned int pitch;
    unsigned int duration;
};

```

Since a pause does not have a pitch, we can use our struct for a note by setting the pitch to an invalid value (for example zero). For building a melody we are now defining an array of `Note`s. But since we want multiple melodies, so that we can switch between them, we are using a 2 dimensional array for defining all melodies in one array:

```
#define NR_MELODIES  2
#define MELODY_LENGTH 8
Note melody[NR_MELODIES][MELODY_LENGTH] = {
    { // melody 0
        {0      , 4}, //pause
        {NOTE_E5, 4},
        {NOTE_B4, 8},
        {NOTE_C5, 8},
        {NOTE_D5, 4},
        {NOTE_C5, 8},
        {0      , 8}, // pause
        {NOTE_B4, 8}
    },
    { // melody 1
        {0      , 4}, //pause
        {NOTE_B4, 8},
        {NOTE_C5, 8},
        {NOTE_D5, 8},
        {NOTE_C5, 4},
        {NOTE_B4, 8},
        {0      , 8}, // pause
        {NOTE_E5, 4}
    }
};

```

Here I used the divider (part of the whole note), just like you did in your code. A `4` means a quarter note, `8` an eight note. For preventing loosing the first note, I inserted a quarter pause at the start.

We also need a variable to hold the current position in our melody, one for the current melody and a timestamp variable for the timestamp of the last played note:

```
unsigned int current_note = 0;
unsigned int current_melody = 0;
unsigned long last_note_timestamp = 0;

```

Now in `void loop()` we check for our timestamp and the duration of the current note. If the current note should end, we end it, increment to the next note and start playing it:

```
if(millis() - last_note_timestamp > wholenote/melody[current_melody][current_note].duration){
    last_note_timestamp += wholenote/melody[current_melody][current_note].duration; // increment timestamp to start of next note
    noTone(buzzer); // stop current note
    current_note++; // increment to next note
    if(melody[current_melody][current_note].pitch){ // next note is not a pause
        tone(buzzer, melody[current_melody][current_note].pitch, wholenote/melody[current_melody][current_note].duration); // start note
    }
}

```

And after the if statement we can add an if statement for checking the melody change button. You didn't include the button check code in your question, so I will just use a placeholder function here.

```
if(change_melody_pressed()){
    // incrementing current melody and wrap around, if we reached last melody
    current_melody = (current_melody + 1) % NR_MELODIES;
    // reset current note to play melody from start
    current_note = 0;
}

```

Now we still need to think about, what happens, when a melody finishes. 3 possibilities:

* **We could restart the current melody:** We need to check for the last note in a melody, and then reset `current_note`:

```
  if(current_melody >= MELODY_LENGTH ){
      current_note = 0;
  }

```
* **We can increment to the next melody:** Like above, but we add the melody incrementing line in the if statement:

```
  current_melody = (current_melody + 1) % NR_MELODIES;

```
* **We can stop playing:** Here I would use the above if statement and set `current_note` to `-1`. Then we need to check in our first if statement, if `current_note` is not `-1`:

```
  if(current_note != -1 && millis() - last_note_timestamp > wholenote/melody[current_melody][current_note].duration)

```

Note: I have not tested the above code, but I compiled it to try finding syntax errors.

---
Tags: programming, c++, millis, piezo, algorithm
---


# Question
Title: AVRdude does not read the FUSE byte values correctly
I am exploring the ATmega328p MCU via a standard Arduino UNO, with the help of avr-gcc toolchain and AVRdude (All in the WINAVR package). I have successfully programmed the board a few times with it. However, when I try to read the fuse values via AVRdude, I get `0x0` for `lfuse`, `hfuse` and `efuse`.

I am using the following command (or its variants) to read:
`avrdude -c arduino -p ATMEGA328p -P com3 -b 115200 -v -F -U hfuse:r:hi_fuse_val.hex:h`

Following is the output I get:

```
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0

```

The file `hi_fuse_val.hex` also has `0` written to it.
What am I doing wrong?

# Answer
A couple of things. That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.

## No self-programming of fuses

A bootloader can't write fuses, at all. The chip just doesn't allow self-programming of fuses. If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino set up to behave as one).

## Optiboot and reading fuses

Optiboot doesn't report fuses, at least not as compiled for UNO.

The "arduino" bootloader protocol used by the avrdude `-c arduino` option is a modified version of the STK500(v1) protocol. The are two commands there that would need to be implemented to read fuses, `Cmnd_STK_READ_FUSE` and `Cmnd_STK_READ_FUSE_EXT`. They have corresponding definitions in the AVR Arduino core's copy of optiboot source. But the places where they would be implemented in the series of `if`-`else`s are absent. Unlike writing fuses, reading fuses *is* possible from AVR code. So it's not a limitation of the chip, the code to do it just isn't there.

Sidenote: You may notice that there are also definitions for commands that write FUSES. These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.

For what it's worth optiboot doesn't actually read the signature of the chip either. It just reports whatever values have been baked in at compile time. Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.

In any case, if you *do* change your fuses using a programmer, expect optiboot to continue reporting them as zero.

## Current fuse values

If you're curious about your actual fuses values, you run sketch that reads them and prints them over serial by using `#include <avr/boot.h>` and

```
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);

```
> 2 votes

---
Tags: arduino-uno, atmega328, avrdude, avr-gcc, avr-toolchain
---


# Question
Title: [SOLVED]how to send command to Gsm module from Arduino via serial port
Am using SIM7600X 4G HAT module (GSM) and Arduino Uno
after I start the module and Arduino, I receive data from Gsm module but I can't send any command to it.
On my Arduino board when I get data RX led flashing, and when I send command TX led flashing.

```
#include <SoftwareSerial.h>
SoftwareSerial myserial(3, 4); // gsm_TX, gsm_RX

void setup(){
  myserial.begin(9600); //Initialize GSM serial port
  Serial.begin(9600); //Initialize Arduino default serial port
}

void loop(){
  while(1){
    while (myserial.available()) {
      //Serial received data, output via mySerial.
      Serial.write(myserial.read());
    }
    while(Serial.available()) {
      //myserial received data, output it via Serial.
      myserial.write(Serial.read());
    }
  }
}

```

As the picture I send "AT" command or any command it no response. it show only module start up command.

My circuit

# Answer
I solved my problem, On my circuit GSM module use an external source and my Arduino Uno use serial port source, So it cant communicate via pin because both ground of them did not connect to each other then the answer is connected GSM module GND to Arduino Uno GND.
> 0 votes

---
Tags: arduino-uno, softwareserial, communication, gsm
---


# Question
Title: [SOLVED]SIM7600 Module Power up by Arduino Uno doesn't work
Am using SIM7600X 4G HAT with Arduino Uno

I follow to manual to Power up the module and it works well, The NET light flashing.

But when I connect to Arduino Uno and use DigitalPin 2 write (High -\> Delay500ms -\> Low) for "power on pulse" it doesn't work, The NET light still not flashing.

My code:

```
#include <Waveshare_SIM7600.h>
// Pin definition
int POWERKEY = 2;

char phone_number[] = "XXX";      //Store the phone number you want to call

void setup() {
  Serial.begin(9600);
  sim7600.PowerOn(POWERKEY);
  sim7600.PhoneCall(phone_number);
}

void loop() {

}

```

code from Waveshare (Waveshare\_SIM7600.h):

```
/**************************Power on Sim7x00**************************/
void Sim7x00::PowerOn(int PowerKey = powerkey){
   uint8_t answer = 0;

  Serial.begin(9600);

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    Serial.print("Starting up...\n");

    pinMode(PowerKey, OUTPUT);
    // power on pulse
    digitalWrite(PowerKey, HIGH);
    delay(500);
    digitalWrite(PowerKey, LOW);

    // Stuck in below loop because Send AT command and no response ///////
    // Becuase NET light not flashing (not connect) //////////////////////

    // waits for an answer from the module
    while (answer == 0) {     // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
      delay(1000);
    }

  }

  delay(5000);

  while ((sendATcommand("AT+CREG?", "+CREG: 0,1", 500) || sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0)
    delay(500);
}

```

# Answer
The GSM module requires a 5V 2A source and my Arduino Uno cant draw for it, my solution is to use a power bank that can draw 5V 2A for powering the GSM module and jump PWR pin to GND (manual said) the NET led start flashing and module can working but TX, RX pin still there for comm.
> 2 votes

---
Tags: arduino-uno, gsm
---


# Question
Title: Any way a GSM sim 900 can still work (USA)?
so I’m pretty new to arduino and have been working for weeks on a GPS tracker using a sim 900 and a knock off neo 6M. All my code seemed to be working but for some reason I could not get the sim900 to establish a connection. Took me long enough to find out 2G carriers have been pretty much shut down. This is for a project and I don’t have time to start over with a 4G shield. Are there any cell carriers that still support 2G? What are my options? I don’t know what to do

Edit: more detail, I’m using the sim 900 to send an sms with a gps location

# Answer
Somehow I got a connection! I live in PA but when I went to Boston for school I got 2G service. Maybe carriers haven’t fully shut it down.
> 1 votes

---
Tags: gsm, gps, tinygps
---


# Question
Title: How can I share one power supply between an arduino and servos?
I'm trying to power an arduino and a few modules (RF receiver, two servos, and a laser diode) through one power supply.

I get jittery/unresponsive servos when hooked up in the following configuration:

* power supply goes to usb breakout, joins with top + and - rails, powers everything (tried
* all grounds go to top - rail
* black/grey/white wires going off right side are power/ground for the servos
* red, green, yellow wires going off left/top side are signals to the servos/laser
* purple wire going off left/top is ground for the laser

If I remove the orange wire (usb breakout to + rail) and plug another power supply into the Arduino, the poor performance disappears and everything works nicely.

Since my power supply is 2.5A, I doubt that I don't have enough power for this setup. This leads me to believe that the Arduino/receiver side of the circuit is making the voltage unstable so the servos misbehave. Is there a way I can isolate these two parts of the circuit (diode, capacitor?) so that I can power the whole setup with one cable?

Components:

* Arduino pro micro (5v)
* RF Link Receiver (WRL-10532, 434 MHz)
* Servo (ROB-09065, sub-micro)
* Laser diode (5V, 20mA)
* Micro USB breakout (1A)
* USB Micro power supply (5.1V, 2.5A)

# Answer
> 2 votes
You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.

Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)

# Answer
> 1 votes
I too have found the servo driving of the Arduino ie UNO to be jittery. The problem is that the Arduino uses a timer, interrupts and software to terminate the pulse so if the processor is busy servicing another interrupt then the pulse gets extended by up to 10us. Modern servos, even the cheap ones, respond to this delay as if it were noise.

The servo library was dependent on clock frequency, and limited to pins 9 & 10, at one point in time, although that might have been fixed in updated versions. out of curiosity, what pins are you attaching your servos to? (9 or 10?)

you might try updating your version of the ardunio IDE/Libraries.

another thought, is that many servos are rated at 6V (not 5v), and while they will work, they may also be jittery. you might find it best to use a separate power supply. Be sure to connect the grounds of the Arduino and external power supply together.

From Servo.h:

```
...
    //attach(pin )  - Attaches a servo motor to an i/o pin.
    //attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
    //default min is 544, max is 2400
...

#define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached
#define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds
...

```

you might try tweaking the min, max, and default settings, or check your code against the settings provided by Servo.h.

---
Tags: power, servo, arduino-micro
---


# Question
Title: How do I create a constant loop with an event that only occurs once?
I am currently working in void loop() and have setup a distance meter that constantly checks the distance.

Once the distance threshold is met, a function is called. Now I only need this function to be called ONCE. But because the distance meter is constantly scanning (which I need), the function is also being repeatedly called. I tried making some sort of timer but I can't figure it out. Can someone please have a look at this?

```
if (distance <= 150){
    personPresent();
    }

  if(distance > 150){
    personAbsent();
      }

```

I need certain events within the if statement to occur only once. E.g., I want to register when there is a personPresent and have that event not fire repeatedly.

In this case, personPresent() is attached to a GPIO pin which triggers a buzzer sound. As it is now, the buzzer keeps on ringing as long as distance is less then 150. I need the buzzer to make a sound only ONCE and then not buzz for at least 5 minutes.

# Answer
What you want is not to check the distance but to check that the distance condition changed.

```
static boolean present = false;

```

Inside loop:

```
if (present == false && distance <= 150){
    personPresent();
    present = true;
} else if(present == true && distance > 150) {
    personAbsent();
    present = false;
}

```
> 3 votes

# Answer
```
static boolean didItAlready = false;

if(distance > 50 && !didItAlready){
     doIt();
     didItAlready = true;
}

```

You simply need a variable to keep track of whether or not it has been done. If and when you want to do the action again then set your variable back to false.
> 0 votes

# Answer
You just need a global variable to track whether it is done or not like this...

```
//  other Codes

bool State=0;

void setup(){

// other Codes...

}

void loop(){

if(distance <= 150 && State==0){

personPresent(); // This function should get executed only once
State=1;

}else if(distance>150 && State==1){

personAbsent(); // This sould also get executed once
State=0;

}

}

```

The global boolean variable ''' State ''' will keep track of how and when the functions need to be executed once, whenever conditions are met. And the boolean variable changes everytime (distance AND Sate) the conditions are met triggering those functions once per bool update.
> 0 votes

---
Tags: programming, sensors, pins, buzzer
---


# Question
Title: How to use pyserial to write two separate message?
I'm using pyserial to communicate with my arduino. I set up the connection and everything works fine. Now I have these two writing commands:

```
pyserial.write("conn".encode())
pyserial.write("mod1".encode())

```

On my arduino:

```
while (!Serial.available());
String s = Serial.readString();
if (s=="conn") do...;
if (s=="mod1") do...;

```

The problem is that none of the `if` statements are true because `s` becomes `"connmod1"`, because the messages are sent almost at the same time I guess. I know I could use some delimiter to split the string, but I would like to know what the convenient solution might be?

# Answer
If you want a quick, cheap, and easy solution, you could just use `sleep()` in your Python script to put a delay between the commands. This obviously isn't a perfect solution, but it's not difficult to implement.

Or, like you said, you could use a delimiter. It's not as easy to implement, but it'll work better.

If you go the delimiter rout, you'll probably need to use `Serial.read()` instead of `Serial.readString()`. That way you can examine characters individually as they come in. You can store your characters in a String or char array until you detect your delimiter and then execute your command.

Hope that helps!
> 1 votes

---
Tags: serial, arduino-nano, python
---


# Question
Title: Is there any working analogue to the pair std::function and std::bind in Arduino?
Both ArduinoSTL and StandardCplusplus don't support them. They implement the version that is compatible with c++03 (not c++11).

This functionality is handy when you design libraries that work with callbacks. And you do need them, if your Arduino does more than one thing simultaneously.

I tried also several other options, but none was enough. Most complete thing I found, Passing capturing lambda as function pointer, does not support plain function pointers and does not allow me to hold the `function` object as a member of the structure, because the type of the object depends on the lambda (not only its signature, like in `std::function`).

In particular, I need a functor that

* can store both capturing lambdas and plain function wrappers
* has a type that depends only on the signature of the function, so I can store it as a class member.

# Answer
> 1 votes
We have written a solution, that we published as a Platformio library: https://github.com/fopeczek/function\_objects.

Please note, that each functional object does one allocation, and those are not particularly friendly in an embedded environment. I am not even sure, that the Arduino C++ does heap deallocation, so you may be leaking resources if you create and destroy the functional objects in a loop.

---
Tags: pointer, stl
---


# Question
Title: int array passed through function has wrong values only after multiple passes
I have this code:

```
for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
}

```

which calls the function "multiLamp" and passes 3 int arrays with 2 values each. Here is the function:

```
void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],2);
    }
  }
}

```

This function is supposed to call some function "lamp" with a few integers from the arrays. In the beginning this works fine but after more than 50 calls of the "multiLamp" function the values in the arrays become {0,128,128} and {3,3,3} or something similar even though the values passed into it from my main code are equally valid as before (they are somehow changed after being passed to the "multiLamp" function).

I can't seem to find the issue here. Any help is appreciated!

**UPDATE:**

Here is the full code, although I don't know if it will be of any use because I wrote it to control some LEDs and if you don't have the setup it's difficult to see if the code is working or not.

```
int e[] = {12,13,11,10};
int xy[] = {2,3,4,9,6,7,8,5,1,A0,A1,0,A3,A4,A5,A2};

void setup() {
  for(int a=0;a < 4;a++){
         pinMode(e[a], OUTPUT);
         digitalWrite(e[a], LOW);
  }
  for(int b=0;b < 16;b++){
         pinMode(xy[b], OUTPUT);
         digitalWrite(xy[b], HIGH);
  }
}

void loop() {
  bigCubes(100);
  rain(20, 30);
  miniCubes(15);
  every(80);
}

void lamp(int epos, int xpos, int ypos, int del) {
  int xypos = 4*xpos+ypos;
  digitalWrite(e[epos], HIGH);
  digitalWrite(xy[xypos], LOW);
  delay(del);
  digitalWrite(e[epos], LOW);
  digitalWrite(xy[xypos], HIGH);
}

void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],1);
    }
  }
}

void every(int wait) {
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      for(int k = 0; k < 4; k++) {
        lamp(i,j,k,wait);
      }
    }
  }
}

void miniCubes(int wait) {
  int cube[8][3] = {{0,0,0},{0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,1,1},{1,0,1},{1,0,0}};
  for(int c = 0; c < 8; c++) {
    for(int it = 0; it < wait; it++) {
      for(int i = 0; i < 8; i++) {
        lamp(cube[i][0]+2*cube[c][0],cube[i][1]+2*cube[c][1],cube[i][2]+2*cube[c][2],2);
      }
    }
  }
}

void bigCubes(int wait) {
  multiLamp(new int[32] {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3}, new int[32] {0,0,0,0,1,1,2,2,3,3,3,3,0,0,3,3,0,0,3,3,0,0,0,0,1,1,2,2,3,3,3,3}, new int[32] {0,1,2,3,0,3,0,3,0,1,2,3,0,3,0,3,0,3,0,3,0,1,2,3,0,3,0,3,0,1,2,3}, wait, 32);
}

void rain(int its, int wait) {
  int x2 = random(0,4);
  int y2 = random(0,4);
  int x1;
  int y1;
  for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
  }
}

```

# Answer
> 0 votes
You are wrongly using the `new` operator for your arrays. That will dynamically allocate these arrays. They are put on the heap (not the stack like local variables) and thus don't get freed automatically, when the function exits. That has to be done by your code with the `delete` keyword. Your code just eats up all the available memory. Thats called a memory leak.

That you need to free your dynamically created variables is not an Arduino thing; this is correct for all C/C++ code. But the limited memory on AVR based Arduinos like the Uno makes it worse.

If you do the math, one iteration of `void loop()` will block 432 bytes of memory (216 array elements, each of type `int` thus 2 byte). The 2KB of memory (which is also needed for local and global variables) is eaten up rather fast.

I don't see, why you even would use dynamically created arrays. Why not just using locally defined arrays, like in the `miniCubes()` function?

---

That said, it is also a generally bad idea to use dynamic memory allocation microcontrollers, especially those with small memory. When creating and deleting objects of different sizes (which is the main advantage of dynamic allocation), you will leave small holes in your RAM, which are too small for one of your objects to fit. At some point your RAM is completely filled with these holes, so that no more memory can be allocated for your objects to save. Thats called memory fragmentation.

On your PC that isn't a problem because of 2 reasons:

* The PC has loads of RAM available, and
* the OS manages the RAM, defragmenting it, if necessary.

Since microcontrollers don't have an OS managing the RAM and often very limited RAM, you need to make sure, that your RAM doesn't get fragmented too much in the runtime of your code.

---
Tags: arduino-uno, arduino-ide, c++, c
---


# Question
Title: Arduino IDE 1.8.13 won't launch properly
Recently I have been trying to install Arduino IDE 1.8.13, and I have ran into according problem. When trying to launch Arduino IDE with ./arduino command it shows according error:

```
./arduino: line 35: /home/wiktor/Downloads/arduino-1.8.13/java/bin/java: No such file or directory

```

I have checked and java file does indeed exist. I am using 32 bit version of Arduino IDE and 32 bit version of Linux Alpine 3.13.3.

Thanks for all answers

# Answer
> 1 votes
Note: Below, technician 274 (the original poster) commented:

> It ended up working, after following alpinelinux wiki and installing the IDE using flatpak.

---

Part of the problem is how confusing the message is. `No such file or directory` is not actually referring to the java file. It's referring to the ld-linux.so interpreter specified in the elf file.

If you run the `file` command on the java executable, you'll see output that looks like:

```
./java/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9, not stripped

```

If you look for `/lib/ld-linux.so.2`, you're going to find that you don't have one, and that's the file it's complaining about.

Alpine Linux apparently uses Musl and the java binaries were compiled for glibc, which is normal for desktop Linux. On a typical desktop Linux system, that the java that ships with the Arduino IDE was compiled for, all kinds of executables make use of ld-linux.so.2. On your Alpine system, you'll find they're referring to /lib/ld-musl-i386.so.1 instead. From this vantage point, it's more of a Linux problem than an Arduino one, but I thought it might as well have something of an answer to point people toward relevant looking resources:

You may find it's easier to replace the java interpreter, but that won't be enough, because the Avrdude and GCC binaries will also expect ld-linux.so.2.

In the end, it may be easier to just not use Alpine Linux.

---
Tags: arduino-ide, linux
---


# Question
Title: DS3218MG Servo - Not working with power supply
I'm trying to run my **DS3218MG Servo Motor** with an external power supply and my arduino nano.

I'm using the following code:

```
#include<Servo.h>
Servo Myservo;
int pos;
void setup()
{
Myservo.attach(3);
}

void loop()
{

for(pos=0;pos<=180;pos++){
Myservo.write(pos);
delay(15);
}
  delay(1000);

  for(pos=180;pos>=0;pos--){
Myservo.write(pos);
delay(15);
}
  delay(1000);

```

}

According to the datasheet the servo needs a **DC 4.8-6.8** voltage. My first attempt was to only use the arduino and no external power supply. So did the following connections:

* servo's **ground** to arduino's **ground**
* servo's **+** to arduino's **5V**
* servo's **data** to arduino's GPIO **pin** 3

Using this connection works fine and the servo rotatates to the desired positions. However, because the arduino does not supply enough current, i bought a power supply with the following specs:

With that, i did the following connections:

* connect the **ground** of the power supply to arduino's **ground** (and servo)
* keep the **data** pin
* connect **+** of power supply to servo's **+**

Unfortunately, the servo does not move with the external power supply. IMO, it should have the right voltage and also supply enough current (at least as much as the Arduino).

Do you see the problem?

# Answer
@starcat, regular usb cable for powering arduino
> 1 votes

---
Tags: arduino-nano, power, servo
---


title: Don't understand problem with my code

text:
# Question
Title: Don't understand problem with my code
I'm trying to get a robot car(elegoo one) to do the obstacle avoidance course. I am trying to write my own one from scratch to better myself and thus would really appreciate it if someone were to tell me what's wrong with my code and why it's not working

```
#include <Servo.h>  //servo library
Servo myservo;      // create servo object to control servo
Servo servosweep;
int Echo = A4;
int Trig = A5;

#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define carSpeedForward 100
#define carSpeedLeftandRight 150
int rightDistance = 0, leftDistance = 0, middleDistance = 0;
int pos=0;

void forward(){
  analogWrite(ENA, carSpeedForward);
  analogWrite(ENB, carSpeedForward);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Forward");
}

void back() {
  analogWrite(ENA, carSpeedForward);
  analogWrite(ENB, carSpeedForward);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Back");
}

void left() {
  analogWrite(ENA, carSpeedLeftandRight);
  analogWrite(ENB, carSpeedLeftandRight);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Left");
}

void right() {
  analogWrite(ENA, carSpeedLeftandRight);
  analogWrite(ENB, carSpeedLeftandRight);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Right");
}

void stop() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
  Serial.println("Stop!");
}

//Ultrasonic distance measurement Sub function
int Distance_test() {
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(20);
  digitalWrite(Trig, LOW);
  float Fdistance = pulseIn(Echo, HIGH);
  Fdistance= Fdistance / 58;
  return (int)Fdistance;
}

void setup() {
  myservo.write(pos);
  myservo.attach(3);  // attach servo on pin 3 to servo object
  Serial.begin(9600);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  //stop();
}

void loop(){
  for (pos = 0; pos < 90; pos += 1.0) {
  servosweep.write(pos);
  delay(50);
  leftDistance=Distance_test();
  }

  myservo.write(90);
  middleDistance=Distance_test();

  for (pos=90;pos<=180;pos+=1.0){
    servosweep.write(pos);
    delay(50);
    rightDistance=Distance_test();

  }

  if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
      else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
      else if((rightDistance <= 40) || (leftDistance <= 40)) {
        back();
        delay(180);
      }
      else {
        forward();
      }
}

```

I'm trying to get the ultrasonic sensor to read values from the left(0 to 90), the middle(90) and the right(90 to 180) and then use them for comparison to decide where to go. When I run this code my car goes in circles and I don't know what the problem is. Any help would be appreciated.

# Answer
As jsotola writes, you are running through the 0-89 position and updating leftDistance every time. Then you find the middleDistance and finally you go through 91-180 and update rightDistance. After the two for loops, leftDistance will have the value for 89 and rightDistance will have the value for 180 because you overwrite your value without doing anything with it.

Start by skipping the for loops and measure at 0, 90 and 180 and use these values as you left, middle and right distance. When deciding if you want to back up, use the middle distance. Remember to use a delay between measurements that is large enough for the servo to get to the position for the next measurement
> 1 votes

# Answer
As a couple people already pointed out, you're using for loops that are unnecessary, and will cause you to get the wrong measurements. You're better off just using `myservo.write();` to set your servo to positions 0 and 180.

Additionally you never check to see if there's an obstacle infront of your robot. Instead, your robot immediately tries turn right or left. That's what's causing it to spin.

Here's a fixed version of your `void loop()`

```
void loop(){

  myservo.write(0);
  delay(50);
  leftDistance=Distance_test();

  myservo.write(90);
  delay(50);
  middleDistance=Distance_test();

  myservo.write(180);
  delay(50);
  rightDistance=Distance_test();

  /* Start by checking if there is space to go forward */
  if(middleDistance > 40){
     forward();
     }
/* If there isn't space to go forward, turn */
  else if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
  else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
  else if((rightDistance <= 40) || (leftDistance <= 40)) {
        back();
        delay(180);
      }
   else {
        forward();
      }
}

```

I hope this helps!
> 1 votes

---
Tags: sensors, servo, debugging
---


# Question
Title: arduino will not save data after receiving from serial communication
I'm new to Arduino and what I'm trying to do is change the variable by sending it from php to the Arduino.

I've added the delay as stated by other questions but it has not worked so far. The pin 13 LED so

Arduino Code

```
float val;
void setup() {

  Serial.begin(9600);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  val=29.1;

  Serial.println("Start!");
}

void loop() {

  if(Serial.available()){
    String temp = Serial.readStringUntil('\n'); //read string
    val = temp.toFloat(); //convert string to float
  }

  if(val==62.10){
    digitalWrite(13,HIGH);
  }else{
    digitalWrite(13,LOW);
  }

  Serial.println(val);
  delay(1000);

}

```

PHP Code

```
<?php
$port = fopen("COM3", "w");
sleep(2);
fwrite($port, "62.1");
fclose($port);
?>

```

Any tips would be much appreciated. Thank you for reading.

# Answer
> 1 votes
You are writing "62.1" but you are trying to read up until a `\n`, which you never send.

You need to ensure that you send the end-of-line character that you subsequently check for,

```
fwrite($port, "62.1\n");

```

Also it's worth noting that floating point values are only ever an approximation. They're great for doing calculations, but very poor at doing comparisons. Your test value of 62.1 cannot be represented precisely as a floating point value, the closest being about 62.099. If you do need to do a comparison then you should check it's within a small range, not a precise value.

---

Your "problem" seems to stem from you opening the serial port with one program, sending a value, then closing the serial port and opening it again in something else and expecting to see that value being echoed back to you.

That can't happen on a stock Arduino UNO. Every time you open the serial port the DTR line toggles the RESET pin to enter the bootloader - which is why you need the 2 second delay after opening the serial port.

In doing so the sketch then runs fresh every time you open the serial port.

There are a number of ways of disabling that reset, from cutting a trace on the Arduino, to adding a large-ish (10µF +) capacitor between RESET and GND - both of which will interfere with your ability to program the board. The capacitor is the easier to reverse.

Ideally you'd use a different serial channel to communicate so it never interferes with the reset or programming. You could use `SoftwareSerial` and an external USB to UART adaptor instead of the `Serial` connection, or use a board with a native USB connection that doesn't reset when you open the serial port, such as a Leonardo.

---
Tags: arduino-uno, serial
---