# Question
Title: if/else on digitalRead not executing on 'else' portion
I am a beginner with C++ but used to be good with BASIC (2 decades ago lol). I'm building a peristaltic metered doser that allows you to input desired mL on a 4x4 keypad and then when 'fill' button is pressed it doses the desired mLs through the peristaltic.

I'm still drafting/printing the peristaltic housing and all of that but in the meantime I want to get as much of the coding done as possible. It's still incomplete, but one of the functions I want the doser to have is a 'PRIME/FLUSH' button.

Originally I wanted the button to run the pump as long as the button is held down to prime the tubing with solution or flush the tubing with DI water. But I haven't had luck figuring out how to use a 4x4 button in momentary switch mode.

A workaround I had was to have the button be an on/off button. So press it once, pump turns on, press it again, pump turns off. Since the pump isn't printed yet I've been using the onboard LED as a tester for the coding (hence the LED\_BUILTIN).

The issue, from my research I figured what I would need was an if/else statement. When the button is pressed (in this case the 'a' button), it reads the LED\_BUILTIN status and if its HIGH it turns it off and if its LOW it turns it on.

But the 'if' part is working, it turns it on, but the 'else' part is not. When the LED is already on and the 'a' button is pressed, it stays on and doesn't rewrite to LOW.

Code below, any advice?

```
#include <KeypadShield.h>

KeypadShield keypad;

#include <LiquidCrystal_I2C.h>
#include <Wire.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

char Data[15];
byte data_count = 0;

int x;

char customKey;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  keypad.begin();
  lcd.begin(20,4);
    lcd.setCursor(4,0);
    lcd.print("Let's Fill!");
    lcd.setCursor(4,1);
    lcd.print("Designed by");
    lcd.setCursor(4,2);
    lcd.print("JP");
    lcd.setCursor(5,3);
    lcd.print("2019 v1.0");

    delay (2000);

    lcd.clear();

    lcd.setCursor(1,0);
    lcd.print("Enter volume in mL");
    lcd.setCursor(3,1);
    lcd.print("on keypad then");
    lcd.setCursor(5,2);
    lcd.print("press DONE");
    lcd.setCursor(0,3);
    lcd.print("mL:");
}

void softReset()
{
asm volatile ("  jmp 0");
}

void loop()
{
    customKey = keypad.getNextKeypress();

    if (customKey)
    {
      if (customKey == 'a')
      {
        if (digitalRead(LED_BUILTIN == LOW))
        {
          digitalWrite(LED_BUILTIN, HIGH);
          lcd.clear();
          lcd.setCursor(5,1);
          lcd.print("FLUSHING");
        }
        else
        {
          digitalWrite(LED_BUILTIN, LOW);
          lcd.clear();
          lcd.setCursor(1,0);
          lcd.print("Enter volume in mL");
          lcd.setCursor(3,1);
          lcd.print("on keypad then");
          lcd.setCursor(5,2);
          lcd.print("press DONE");
          lcd.setCursor(0,3);
          lcd.print("mL:");
        }
      }

      if (customKey == 'd')
      {
       softReset();
      }

      if (customKey != 'p' && customKey != 'a' && customKey != 'b' && customKey != 'c' && customKey != 'd' && customKey != 's')
      {
        Data[data_count] = customKey; // store char into data array
        lcd.setCursor(data_count+3,4); // move cursor to show each new char
        lcd.print(Data[data_count]); // print char at said cursor
        data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
        x = atoi (Data); //convert string to integer 'x' for use in equations
      }

     if (customKey == 'p')
      {
       lcd.clear();
       lcd.setCursor(7,0);
        lcd.print(x);
        lcd.setCursor(Data[data_count]+13,0);
        lcd.print("mL");
        lcd.setCursor(0,1);
        lcd.print("FILL --> fill");
        lcd.setCursor(0,2);
        lcd.print("RESET --> change mL");
        lcd.setCursor(0,3);
        lcd.print("FLUSH --> finish");

      }
    }
};

```

# Answer
> 7 votes
(Heh... before even seeing the code I guessed you'd done this...)

You are comparing a pin number, not the results of `digitalRead()`, and then passing the results of that comparison to `digitalRead()`:

```
if (digitalRead(LED_BUILTIN == LOW))

```

It should read:

```
if (digitalRead(LED_BUILTIN) == LOW)

```

Note the order of the brackets: `LED_BUILTIN` is passed to `digitalRead()`, and then the result of calling that function is compared to the value `LOW`.

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


# Question
Title: Powering L298N drivers from mains power supply
I am powering 2 stepper motors with an L298N driver each (from a 9V 2A external power supply powered from the mains: https://www.amazon.co.uk/BERLS-Power-Adapter-Elegoo-Connectors/dp/B07GSM6YLX/ref=sr\_1\_5?ie=UTF8&qid=1550859082&sr=8-5&keywords=AC%2FDC+Power+Adapter+for+Arduino).

I am wondering how I can connect the driver 5V and GND pins to the power supply?

Thanks in advance!

# Answer
You would not connect the +5V lead to the power supply. Connect the ground between the driver, the Arduino, and the power supply. Connect the 9V from the power supply to the driver. Connect the logic lines from the Arduino to the inputs on the driver.
> 0 votes

# Answer
You'll need another supply, or a step-down supply for the 5v; same ground for all.

Also H-bridges are really inefficient to drive steppers, you should get a dedicate stepper driver.
> 0 votes

---
Tags: arduino-mega, power, l298n
---


# Question
Title: HM-10 Central mode starting a connection
I'm trying to issue a connection via HM-10 from arduino (rather than my phone). However, I'm unable to start a connection from arduino using both AT+CON and AT+CONNL. When I try AT+CON I get `OK+CONNA` and when I use AT+CONNL I get `OK+CONNE`. Here's my code:

```
#include <SoftwareSerial.h>
SoftwareSerial bluetooth(8,9);

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(50);
  bluetooth.begin(115200); //open BLE connection
  bluetooth.setTimeout(50); //set timeout
  bluetooth.write("AT+ROLE1");
  //bluetooth.write("AT+ROLE0");
  delay(50);
  bluetooth.write("AT+NOTI1");
  delay(50);
  bluetooth.write("AT+CONC40BCB403020");
  delay(50);
  //bluetooth.write("AT+CONNL");
}

void loop() {
    while (bluetooth.available() > 0) {
      String response = bluetooth.readString();
      Serial.println(response);
    }
}

```

The response that I get is:

```
OK+Set:1
OK+Set:1
OK+CONNA

```

# Answer
> 0 votes
By now you've surely moved past this, but: I found that I had to try connecting multiple times in order to get a connection to complete. Also, your timeout might need to be longer?

---
Tags: bluetooth
---


# Question
Title: Can't you easily use "quadrature" incremental rotary encoders at 2X or 4X their number of "stops"?
I bought a 12-step "quadrature" incremental rotary encoder as an input device for a project I'm working on.

When I wrote the code to track "ticks" of rotation, I made it respond to any change in the "A" pin. As a result, I got 24 steps, not 12. They appear to be evenly spaced, and still correctly indicate clockwise or counter-clockwise rotation.

It occurs to me that if I track changes of state in both the "A" and "B" pins, as long as I reverse the logic for identifying clockwize vs. counterclockwise rotation, I could get a 48 step count from the same encoder.

Thus isn't it straightforward to get 2X or 4X the steps from a quadrature rotary encoder simply by interpreting the signals differently?

# Answer
Maybe the encoder you got is being incorrectly described? I have a handful of the little thru-hole rotary encoders popular in Arduino module kits and they have 12 detents for one rotation, but they are actually 48-position-per-rotation encoders. When I use them, I have to divide the tick count by 4 to have one physical "click" count as one tick in my code.

For some of these, it's fairly straightforward to open them up and remove the detent, and thus get a higher-resolution, smooth spinning encoder. Unfortunately, others, such as the ones I have, are difficult to open without destroying them, and since they physically *snap* to the detents, aren't usable at the proper resolution.

The method you note, where you track the high/low change in either direction of both outputs is the normal way to read quadrature encoders.
> 1 votes

# Answer
The answer to my question is yes.

Normally you only count the falling edge of one of the outputs of an incremental encoder as a pulse. That gives you the specified number of ticks for that kind of encoder - 12 ticks per turn in the case of my encoder.

If you instead write your code to respond to either rising or falling edge changes on one of the pins, you get 24 ticks per revolution.

If you **instead** write your code to respond to rising or falling edge changes on **either** pin, you get 48 ticks per revolution.

The code I came up with looks like this:

```
void setup() {
  //Use this setup code for 12 ticks/revolution
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, FALLING);

/*
  Use this setup code for 24 ticks/revolution
  (trigger interrupt on rising and falling edge)
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);
*/

/*
  Use this setup code for 48 ticks/revolution
  (trigger interrupts on rising and falling edge of either pin)
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);
  attachInterrupt(digitalPinToInterrupt(rotaryPinB), encodePinB, CHANGE);
*/

//The rest of your setup code...
}

```

And the interrupt service routines (ISRs):

```
void encode() {
  rotaryValueChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  //Fast equivalent to pinAState = digitalRead(rotaryPinA) == LOW
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  rotaryValue +=  (pinAState == pinBState) ? -1 : 1;
}

void encodePinB() {
  rotaryValueChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  rotaryValue +=  (pinAState != pinBState) ? -1 : 1;
}

```

If you only set up one interrupt on rotaryPinA, the 2nd interrupt method never gets called.

The code above is specific to the Arduino Mega 2560 and other boards that have the same pin to register mappings. It uses interrupts so it doesn't miss state changes in the pins, and reads the pin states using port registers for speed.

Note that if you're only adding a falling edge interrupt you can skip the read of pin A (since when the pin state falls it will, by definition be at a logic 0 whenever the ISR gets called.)

To get this to work well I had to build the RC filter circuit described in the spec sheet for my encoder:

https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf

The diagram looks like this:

And I had to add Schmitt triggers between the filter outputs shown above and the input lines to the Arduino.

Without the Schmitt triggers it gets jitter when the voltage from the filter doesn't switch between HIGH and LOW values fast enough. The Schmitt triggers exclude spurious readings from those "dead zone" voltages.

With those changes the readings from the encoder are quite good, although it still measure ± 1 tick or so per revolution for some reason.

I wish now I had bought the version of the encoder that has detents so it rotates in discrete clicks.
> 0 votes

---
Tags: rotary-encoder, software
---


# Question
Title: I cannot compile the Arduino sketch when I remove the void loop function?
```
#include <AFMotor.h>

AF_DCMotor motor(2,MOTOR12_64KHZ);

void movefor ();

void moveback();

    void setup()

    {

    Serial.begin(9600);

    Serial.println("Motor test!");` `motor.setSpeed(200);

    movefor ();
    moveback ();
    }

        void movefor( ){
        motor.run(FORWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

    void moveback( ) {
      motor.run(BACKWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

```

While trying to compile this the error message is *error compiling for board Arduino Uno*

I want the functions outside loop so removed it.

Even if I keep void loop and leave it blank then my motors will like run forward, backward and forward afterwards continuously .

# Answer
You can't, and shouldn't, remove the loop function. Arduino sketches must have a setup function and a loop function. The setup function is called once and the loop function is called repeatedly.

Just make your loop function look like this:

```
void loop() {
    movefor ();
    moveback ();
}

```

Your motor will move forward, then move backwards, forever.

Note that you should read up on how to avoid using the delay function. You really need to use `millis()` to do your timing rather than delays. Do an internet search on "Arduino blink no delay." That's basic Arduino programming.
> 1 votes

# Answer
There must be something wrong within the motor, circuit or the motor class.

What happens is when you use a setup and loop is the following:

```
setup();
while (1) { loop(); }

```

So the loop function is executed forever, if it is empty, nothing will happen. If you say that the motor runs forward, it is probably because of a wrong implementation of the motor class.

Arduino IDE dictates there is always a loop, and having an empty loop is the same as having no loop at all.

What you can try is:

* In the setup, only execute movefor() and check what happens
* Than only execute moveback() and check what happens
* Than make combinations and see if the problem is inside movefor or moveback

For the first steps you can add a delay to easier see if there is a side effect.
> 0 votes

---
Tags: arduino-uno, arduino-ide, motor, arduino-motor-shield
---


# Question
Title: Accessing 2 dimensional array in PROGMEM inside loop
I am unable to access elements of a 2D PROGMEM array from inside a loop. Please see the following example:

```
const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  Serial.println(pgm_read_byte(&(arr[0][0])));
  Serial.println(pgm_read_byte(&(arr[1][0])));
  Serial.println(pgm_read_byte(&(arr[2][0])));
  Serial.println(pgm_read_byte(&(arr[3][0])));
  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(":");
    Serial.println(pgm_read_byte(&(arr[i][0])));
  }
  int j = 0;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 1;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 2;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 3;
  Serial.println(pgm_read_byte(&(arr[j][0])));
}

void loop() {

}

```

The output is:

```
97
101
106
114
0:12
1:174
2:12
3:148
97
101
106
114

```

I verified and re-verified the syntax so many times. could not find anyone facing similar issue. I am at my wits end why it would not print correct values inside the loop. Any ideas?

EDIT: expected output is:

```
97
101
106
114
0:97
1:101
2:106
3:114
97
101
106
114

```

# Answer
> 0 votes
```
const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(':');
    for (int j = 0; j < 4; j++) {
      Serial.print((char) pgm_read_byte_near(pgm_read_word(arr + i) + j));
      Serial.print(',');
    }
    Serial.println();
  }
}

void loop() {

}

```

output

```
0:a,b,c,d,
1:e,f,g,h,
2:j,k,l,m,
3:r,s,t,u,

```

at runtime the size of the arrays is unknown, so I print the first 4 items

# Answer
> 1 votes
After going through link given by Juraj above again, I could make it work as follows:

```
const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  Serial.println(pgm_read_byte(&(arr[0][0])));
  Serial.println(pgm_read_byte(&(arr[1][0])));
  Serial.println(pgm_read_byte(&(arr[2][0])));
  Serial.println(pgm_read_byte(&(arr[3][0])));
  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(":");
    Serial.println(pgm_read_byte_near(pgm_read_word(&(arr[i])) + 0));
  }
  int j = 0;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 1;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 2;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 3;
  Serial.println(pgm_read_byte(&(arr[j][0])));
}

void loop() {

}

```

Now it shows the expected output and access from inside loop using variable index is possible. Thanks.

---
Tags: progmem, arduino-duemilanove
---


title: Choosing a motor for my project

text:
# Question
Title: Choosing a motor for my project
Sorry For my bad English. I will start to make a mini conveyor (100 cm x 30 cm) with an Arduino Uno.

What is the best motor should I choose for my project ? \- Stepper Motor ? \- DC Motor ? Etc.

Please help me, I am Newbie.

# Answer
> 1 votes
* If you want to control how much the conveyor moves and want to move it a fix distance then stop and move again stepper would be better as you know that each step is equivalent to a certain amount of displacement. Stepper have the disadvantage that is more complicated to control so you will need a special driver.
* If you want the conveyor to move continuously at a approximately speed or moving approximately, then DC motor is a good option. It's easier to drive. But if you want the conveyor to go back and forward then you will need a H bridge for the DC motor(similar to the driver for the stepper motor). Also you can get very accurate positioning with a DC motor using a rotary encoder, but it requires a complex software to drive it properly.

# Answer
> 2 votes
I second the suggestion that a stepper motor might be a more suitable drive mechanism. There are a lot of stepper motors for sale on line for very low cost that can provide great accuracy. They are an amazing value, probably because of so many robotics projects to supply. Their native accuracy can be enhanced many times by use of what is called a "micro-step" driver. The micro-step driver can transform a stepper motor that has 200 native steps per revolution to one that effectively has 2000 or more steps per revolution. I have found repeatability to be excellent. They are used commonly to drive precision CNC machines.

And you are correct that if you don't need the fastest motion, a gear reduction can enhance accuracy even more. There are small stepper motors with affixed gear boxes sold as sets. Consider a size NEMA 17 stepper motor for a small and inexpensive, but well engineered, motor.

A coupled worm gear box has the advantage that it serves as a natural brake if there is any tendency for system weight to move the laser in certain positions, but gear reduction means that fast motion require higher motor rpm's.

The Accel\_Stepper library has worked well for me in helping to get them to function smoothly. It helps a lot to make it easy to integrate the stepper with Arduino, and it is fairly user-friendly.

---
Tags: arduino-uno, arduino-nano, motor, stepper-motor
---


# Question
Title: Trying to use an LCD 1602 to display, but I don't have a 10 KOhm potentiometer
I'm following this tutorial page and I don't have a 10k ohm potentiometer on hand. Could I replace it with resistors to simulate a manual setting and replace the resistors to adjust to a new settings.

From what I was reading this pin is for contrast and I'm sure I could manually set the contrast once and be happy with it for quick prototyping. I'll be ordering a 10k ohm potentiometer on Monday.

# Answer
> 3 votes
Yes. All a potentiometer is, is two resistors end to end. The "wiper" is the join between the two resistors.

It doesn't matter too much what value potentiometer (and hence what value resistors) you use, as long as it's "around" the 10kΩ mark (100kΩ should be fine, 50kΩ, 1kΩ etc - anything below 1kΩ may not work) - what matters is the ratio of the values of the resistor.

# Answer
> 1 votes
Yes, you always can do that, depending on the resistors you have at hand, you can combine them to make e.g. 1 KOhm, 2 KOhm etc resistors.

Probably you need a linear potentiometer (which means halfway is 5 KOhm).

In a linear potentiometer, you can use the following resistance (made up by a single or a combination of resistors in series or parallel):

# Answer
> 0 votes
Yes, but you need only one resistor to GND. The display has already one resistor inside the display. I forgot what the value should be and I don't have a display at hand right now, so you have to try which value is best.

In most examples with a LCD display, a potentiometer is used for the contrast. Not many people know that only a (variable) resistor to GND is needed.

With a fixed resistor, you are not able to quickly adjust the display when the temperature changes.

---
Tags: potentiometer
---


# Question
Title: How to make sure Arduino's PWM pulses are phase shifted?
I'd like illuminate my room solely with several RGB LED strips using Arduino's PWM (together with LED amplifier and few transistors).

I want the Arduino to control 2 independent chains of LED strips, and I want to make sure, that the LEDs would not blink simultaneously, creating a very strong stroboscopic effect in my room.

How to delay three Arduino's PWM pins half a phase relative to the other three?

# Answer
This (short) code below will achieve what I think you are asking for, on the Atmega328 (eg. the Uno, Duemilanove, etc.).

```
byte dutyCycle = 80;

void setup()
 {
  pinMode (3, OUTPUT);    // Timer 2 "B" output: OC2B
  pinMode (11, OUTPUT);   // Timer 2 "A" output: OC2A

  // Set OC2A on Compare Match when up-counting.
  // Clear OC2B on Compare Match when up-counting.
  TCCR2A = bit (WGM20) | bit (COM2B1) | bit (COM2A1) | bit (COM2A0);
  TCCR2B = bit (CS21);         // phase correct PWM, prescaler of 8
  OCR2A = dutyCycle;           // duty cycle out of 255
  OCR2B = 255 - dutyCycle;     // duty cycle out of 255
  }  // end of setup

void loop() { }

```

## How it works

The code uses Timer 2 (an 8-bit timer) to count up to 255 in phase-correct PWM mode. Outputs are to OC2A (the "A" output - pin D11) and OC2B (the "B" output - pin D3). The duty cycle is in variable dutyCycle which must be in the range 0 to 255. The timer counts up to 255 and sets OC2A on compare-equal to the dutyCycle number, and it also clears OC2B on compare-equal, when counting up. The second half of the phase-correct cycle does the reverse. Thus the two cycles are of opposite phase.

## Frequency

The frequency of the timer is 3.9 kHz. This is because the timer has a prescaler of 8, then it counts up to 255, then it takes two cycles per period (one up, one down):

```
16000000 / 8 / 255 / 2 = 3921.56 Hz

```

As Edgar Bonet pointed out in the comments, phase-correct PWM counts are not zero-relative, unlike other counting modes. Thus you divide by 255 to work out the frequency, not 256.

You could select other frequencies by choosing different prescalers.

## Proof of operation

The oscilloscope screen here shows the two outputs, out of phase with each other by 50%.

You can see from the circled cursor measurement that the OC2B pin is off for exactly the requested duty cycle (80 µs).

```
 1/ 16000000 * 80 * 8 * 2 = 8e-005 (0.00008)  --> 80 µs

```
> 5 votes

# Answer
Why not put a capacitor (and current limiting resistor) in the circuit for each color of each LED? (The output from the Arduino would lead first to a current limiting resistor, value picked to limit the current to the LED to it's max, as usual. Then a small capacitor between the signal line and ground.) That will average out the output and change a square wave output to a DC output (With a fair amount of ripple in it.) The ripple shouldn't matter, but the LEDs won't turn fully off, so the strobe effect should be all but eliminated, and the apparent brightness of each output should be the same.

Then you can use unmodified PWM and don't have to mess with the timers on your Arduino (which affects other things besides PWM.)
> 0 votes

---
Tags: led, pwm
---


# Question
Title: Comparing byte array with multi-dimensional array
I am having a byte array let us say

```
byte arr[7]={123456};

```

How to compare this array with a list of of other array like this for example

```
byte  buffers[5][7] = {123456,654321,987654,456789,765432};

```

if this method is wrong how can I declare that ?

# Answer
```
byte arr[7]={123456};

```

sets arr\[0\] = 64 - which is 123456 % 256 - and arr\[1-6\] are left at 0

And you also only want 6 (not 7) values - so the code would be

```
byte arr[6]={1,2,3,4,5,6}; // this is how to initialise an array
byte  buffers[5][6] = {{1,2,3,4,5,6},{6,5,4,3,2,1},{9,8,7,6,5,4},{4,5,6,7,8,9},{7,6,5,4,3,2}}; // this is how to initialise a 2d array

void setup() {
  Serial.begin(74880);
  delay(100);
  // this code will find a match, the vlaue of `i` will be the matched index
  int i;
  int j;
  for(i = 0; i < 5; i++) {
    for(j = 0; j < 6; j ++) {
      if(arr[j] != buffers[i][j]) {
        break;
      }
    }
    if(j == 6) {
      break;
    }
  }
  if (i < 5) {
    Serial.print("Found at index ");
    Serial.println(i);
  }

}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino motor shield orange/white pin usage
I have an Arduino motor shield like this one plugged into my Mega board.

I would like to know some more information about the orange and white pin blocks on the board. The Arduino website has the following information, but it doesn't give any explanation of what is best to use them for or which pins are mapped to the data pins etc.

* TinkerKit connectors for two Analog Inputs (in white), connected to A2 and A3.
* TinkerKit connectors for two Aanlog Outputs (in orange in the middle), connected to PWM outputs on pins D5 and D6.
* TinkerKit connectors for the TWI interface (in white with 4 pins), one for input and the other one for output.

What I want to do is connect a servo up to the board and was hoping I could use one of the orange `OUT` blocks. I haven't been successful in finding any examples of this which leaves me in doubt as to whether it is possible or not. I would just plug it in, but I'm afraid of frying the shield/mega/servo. Probably an irrational fear, but I can't afford another one of any at the moment!

I don't know which pins in the block are assigned to the data, vcc and out, so if anyone know I would be grateful for the answer.

Also, just because it is annoying not to understand, what are the `TWI` connectors for?

I hope this isn't too general a question as I could really use some answers!

# Answer
> I don't know which pins in the block are assigned to the data, vcc and out, so if anyone know I would be grateful for the answer.

Following the example on TinkerKit's Custom Distance Sensor page, we see that:

> If you look on the edge of the sensor, you can see the three pins, that are power (5V), ground and signal. The same as your TinkerKit! modules, just in a different order.
>
> The only difference is that the signal and ground cable are inverted.

So the order in the connector is Vcc Signal Ground.

Another way, and what I would do to be 100% sure, is measure resistance with a multimeter. If your meter has a continuity test feature, that's even better because it'll beep.

Anyway, put one end of the probe on pin 1 of the connector and the other end on GND and see if the resistance is very close to 0 ohms. If it's reading OL (Over-Limit) then that pin is not GND.

Put the probe on Vcc instead and it should show 0 ohm or beep. So now you know that pin is Vcc.

Do the same for the other pins and find out which one is ground. The third pin is your PWM output. It's connected to D5 or D6, check the continuity on those pins to see which one.
> 2 votes

# Answer
> ...which pins are mapped to the data pins etc.

The shield page provides a schematic

> I would like to know some more information about the orange and white pin blocks on the board

These have the reference printed on the board

---

# TWI IN and TWI OUT

They are the same and are both connected to the same I2C pins of Arduino (SCL, SDA). They are intended to help in case you want to connect more than one device.

---

# OUT 5, OUT 6

Connected to Arduino pins 5 and 6 (PWM outputs)

---

# IN 2, IN 3

Connected to Analog in A2 and A3

---

The power outputs of L298 intended to drive the motor are the blue screw connectors.
> 7 votes

# Answer
You can use Thinkerkit pins(out ~5 and ~6) for controlling servos. Just need to do a bit of tweaking here. Hobby servo motors have got 3 pins orange(signal) , red(live+) in the middle, and brown(gnd-). But, the motor shield rev3 uses the middle pin for signal. To overcome this problem, swap the middle wire with the orange one on the servo plug.

There are three small latches that prevent wires coming out of the plug, use the tip of a needle and with little force slightly lift them up then pull out the wires from the servo plug, they should come off easily.

Remember to attach pin 5 or 6 in the arduino code. I used servo.h library.
> 1 votes

# Answer
Although the 'Orange' (Out) pins of the Deek-Robot Motor Shield can be used to drive a servo by swapping the '+5vdc' and 'Signal' wires at the servo harness plug it is best to not do as this. This is because the current drive for the servo is drawn from the Arduino UNO. Given that an individual servo can draw well in access of 125ma the current draw may/will exceed the current sink limitations of the associated Arduino UNO circuitry. It is best to use an external power source, properly filtered for electrical noise, as the current source for the servo(s). This has been documented/recommended in multiple information sources.
> 1 votes

---
Tags: pins, shields, motor
---


# Question
Title: Distributing power evenly to multiple pins
It's an arduino board, model UNO R3. I have 3 5cmx10cm heating pad power required 5V DC up to 1A and can withstand up to 12V DC. These 3 heating pad are wired up onto arduino board with red wires connected to pin 8 pin 9 and pin 10 on the digital side of the arduino and the black wire connected to GND (ground). Lastly I have a toggle on and off switch connected to the arduino with the red wire attached to digital pin 2 and the black wire to 5V. The arduino uno R3 withstand 20voltage and the 5V heating pads can withstand 12V. I would like my 20V external power to heat up all 3 heating pads evenly, how can I do this? Is it possible? Thank you!

# Answer
Yes, of course it is possible. But if all you need to do it to turn these heat pads on and off, an Arduino is perhaps not the most suitable technology.

But presuming these heat pads are a component of some more complex system that responds to other inputs or outputs to/from the Arduino, you will need a few more components. You need to accomplish two things that the UNO R3 cannot accomplish by itself, because your heat pads are very much too large a load for your UNO to power directly. (The power for a single LED bulb is about the most that you can draw from an output pin.)

1. You need to reduce your 20-V external power source down to something less than 12 volts to supply your heating pads.
2. You need to switch on and off up to 1 amp of current to flow to each of the three heating pads. The UNO cannot do this directly.

There are a lot of ways to reduce your 20-volt supply down to less than 12 volts. Some are much more efficient than others. Probably the lowest cost efficient way is to use your 20-V source as the input a small DC to DC voltage down stepping converter. These are available online from Chinese vendors for very low cost. Just search for "DC-DC converter down". A quick search finds one rated at 20 amps, with adjustable voltage output can be purchased for less than $10. These are pretty efficient devices that don't waste the power that a simple voltage dropping resistor would waste.

Then you need either one or three 5-volt relays of some type to switch the power on to the heat pads. The UNO pins output of 5-volts would not provide current to heat pads, put only enough current to energize the relay(s). The relay(s) can be either solid state, or coil energized. Just be sure the relay "contacts" are rated to handle well more than 1 amp if there are three of them, and more than 3-amps if only one. An Arduino relay shield with four relays, each rated for 10 amps, can be purchased for less than $5.

If you only every want all three heat pads energized at the same time, you only need one relay, and one Arduino output to energize it.

The very simplest solution, if you only want all the pads heating simultaneously, would be to wire the three heat pads in series. Then you could apply your 20-volts directly across all three heat pads, and you would not need any device to reduce your supply voltage. Each heat pad would have 1/3 of 20 volts across it, which is well under their 12 volt tolerance. And you would only need one relay.
> 1 votes

# Answer
Can you state the full goal of the project? Are you supposed to be turning the heating pad on and off with the Arduino? (The rest of my answer assumes that that is what you want to do.)

You will need a source of DC power to drive the Arduino. (You can't power an Arduino with AC.)

You will need a 5V relay so you can turn off the power to the heating pad from a logic pin on the Arduino. There are various relay modules made to be controlled by microcontrollers like Arduinos. This one, for example: https://www.jameco.com/z/VMA406-Velleman-Arduino-Compatible-5V-Relay-Module\_2255306.html?CID=GOOG&gclid=EAIaIQobChMIr9bSioLT4AIVkpOzCh3X7gqbEAQYBSABEgLf1PD\_BwE

Then you will be able to rig the Arduino to turn the relay on and off. You'll wire the power for the heating pad through the relay. You will also need a way to lower the voltage of your power supply to the 5V - 12V range you mentioned. A 1:2 step-down transformer would be a good choice for that.
> 0 votes

---
Tags: arduino-uno
---


title: Bypass a function error

text:
# Question
Title: Bypass a function error
I have a long code written in Arduino101 that works fine. I use a prepared function (connected to a library) in my code that I have not written it. My input to this function is an array. In 99.9999..% of the time, the function works great. However, it might stops due to an unknown reason, maybe because of my wrong input. This causes the program to stop. My question is: how to bypass this function if it fails for any reason? Something like 'on error' function in normal programming.

Thanks a lot in advance,

# Answer
> 1 votes
If your function is crashing then there is no way to recover. Arduinos are unprotected real mode devices. If your code does something invalid, your program crashes and the device will likely either hang or restart.

You need to debug your function, or find the invalid data you are passing into it.

---
Tags: library
---


title: DigiKeyboard - type a backslash (\)

text:
# Question
Title: DigiKeyboard - type a backslash (\)
I'm using digiKeyboard library to type to a powershell, but I need to type a backslash (a lot of them), but I can't figure it out.

I have been looking for the solution for about 3 hours and I still can't find it. Please let me know how to make a backslash work.

The powershell command that I want to execute:

`cmd /C "start /MIN powershell iwr -Uri https://tinyurl.com/WjnAU6 -OutFile c:\windows\temp\b.jpg;sp 'HKCU:Control Panel\Desktop' WallPaper 'c:\windows\temp\b.jpg';$a=1;do{RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True;sleep 1}while($a++-le59)"`

It just changes the wallpaper with a downloaded image, try in on your friend.

# Answer
To include `\` in a string so it can be printed you have to escape it. `\` is itself the escape character, so doubling it up "escapes the escape character" so it is interpreted as a normal character.

So to print `"c:\windows"` you would actually have to type `"c:\\windows"` and the `\\` gets changed by the compiler into just `\`
> 0 votes

---
Tags: digispark
---


# Question
Title: Do I need an external power supply for the SG90 micro servo?
I have a Uno R3 and although I can add an external power supply for the SG90 micro servo it would make the project more complicated. Can I power the servo using the 5v pin of the Uno R3?

I measured the current and it does not seem to pass 160mA and in normal use, it uses only 60mA.

# Answer
> 1 votes
I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA. You may want to test your servo under this condition before deciding to power it with an Uno.

# Answer
> 0 votes
Does your servo have to push or pull anything? Or is this just to practice writing code for an unattached SG90 and see it move? If it's the former, the servo will draw more current than an Arduino can deliver so you'd need a separate power supply. If it's the latter, you can get away with it. The SG90 is about the least demanding (of current) servo available and you can drive an *unloaded* one directly off the Arduino. It's current-peaks should be short enough to limit thermal damage to the Arduino pin driver. Just make short test runs and don't leave it see-sawing for any length of time.

---
Tags: power, servo
---


# Question
Title: The sketch burned two H Bridges, need help to find out how to modify
This is Arduino RC control car, the sketch tested good in a small motor, but burned two 60A drivers when put into 24V,500W motors, need help to find out whats wrong?

```
#include <VirtualWire.h>

//motor A connected between A01 and A02
//motor B connected between B01 and B02

int STBY = 2; //standby  // mod: was 10 --2 ??

int count;

//Motor A
int PWMA = 9; //Speed control   // need mod: was 3 change into 9
int AIN1 = 8; //Direction  // was 9
int AIN2 = 7; //Direction

//Motor B
int PWMB = 10; //Speed control   // need mod: was 5 change into 10
int BIN1 = 5; //Direction   // was 6
int BIN2 = 4; //Direction   ///was 16 put into p7 cause of Arduino uno no p16.

const boolean FORWARD = HIGH;
const boolean REVERSE = LOW;

float speed_Max = 252; //pwm usually goes from was:0-255 ////0-255 changed into 0-252

float speed_Min = 0;
float analogInput_Max = 1023;
float analogInput_Min = 0;
float analogInput_Middle_X = 515;//ideally it would be analogInput_Max / 2
float analogInput_Middle_Y = 495;//ideally it would be analogInput_Max / 2
float deadBand = 0;
float middleMax = (analogInput_Max / 2) + deadBand;
float middleMin = (analogInput_Max / 2) - deadBand;
boolean pastDirection = FORWARD;

void setup()
{
  // Configure Timer 2 for PWM @ 14 kHz.
  TCCR2A = 0;           // undo the configuration done by...
  TCCR2B = 0;           // ...the Arduino core library
  TCNT2  = 0;           // reset timer

  TCCR2A = _BV(COM2A1)  // non-inverted PWM on ch. A
           | _BV(COM2B1)  // same on ch; B
           | _BV(WGM20);  // mode 10: ph. correct PWM, TOP = ICR1

      TCCR2B = (TCCR2B & 0b11111000) | 0x01; //3.92116 [kHz] //** use this code got 3.9khz but joystick works not too good
    {

    Serial.begin(9600);  // Debugging only
    Serial.println("setup"); //Prints "Setup" to the serial monitor

    vw_set_rx_pin(6);       //Sets pin D12 as the RX Pin
    vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(2000);      // Bits per sec
    vw_rx_start();       // Start the receiver PLL running

    pinMode(23, OUTPUT); //Relay one ////M1 added 2 was 2 -- 4
    pinMode(25, OUTPUT); //Relay two
    pinMode(27, OUTPUT); //Relay four
    pinMode(29, OUTPUT); //Relay five
    pinMode(31, OUTPUT); //Relay sex
    pinMode(33, OUTPUT); //Relay seven
    pinMode(35, OUTPUT); //Relay eight
    pinMode(37, OUTPUT); //Relay three
    pinMode(39, OUTPUT); //Relay three
    pinMode(41, OUTPUT); //Relay eight
    pinMode(43, OUTPUT); //Relay three
    pinMode(45, OUTPUT); //Relay three

    digitalWrite(23, HIGH);
    digitalWrite(25, HIGH);
    digitalWrite(27, HIGH);
    digitalWrite(29, HIGH);
    digitalWrite(31, HIGH);
    digitalWrite(33, HIGH);
    digitalWrite(35, HIGH);
    digitalWrite(37, HIGH);
    digitalWrite(39, HIGH);
    digitalWrite(41, HIGH);
    digitalWrite(43, HIGH);
    digitalWrite(45, HIGH);
     }

  pinMode(STBY, OUTPUT); //// pin: the number of the pin whose mode you wish to set; mode: INPUT, OUTPUT, or INPUT_PULLUP.

  pinMode(PWMA, OUTPUT);
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);

  pinMode(PWMB, OUTPUT);
  pinMode(BIN1, OUTPUT);
  pinMode(BIN2, OUTPUT);
}

void loop() {

button(); //// disable 'button', no work. remove '//' enable, button works good
joystick(); //// disable 'joystick', no work. remove '//' enable, joystick works good, but no motor control yet

 }

void joystick() {

  uint8_t buf[VW_MAX_MESSAGE_LEN]; // This declares a variable array. instead of 7 variables buf1, buf2 etc...
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    int column = 0;
    String message;
    int commands[30];
    // Message with a good checksum received, dump it.
    for (i = 0; i < buflen; i++)
    {
      //DEBUG:
      //Serial.print(char(buf[i]));

      if (char(buf[i]) == '|') {
        commands[column] = message.toInt();
        message = "";
        column++;
      } else {
        message += char(buf[i]);
      }
    }

    //one more time to capture the last value since the message does not end with |
    commands[column] = message.toInt();

    // DEBUG
    //    Serial.print("X: ");
    //    Serial.print(commands[0]);
    //    Serial.print(" Y: ");
    //    Serial.println(commands[1]);

     motorControl(commands[0], commands[1]);

  }

}

void move(int motor, int speed, boolean direction) {
  digitalWrite(STBY, HIGH); //disable standby

   if (motor == 1) {
    digitalWrite(AIN1, direction);
    digitalWrite(AIN2, !direction);
    analogWrite(PWMA, speed);
  } else {
    digitalWrite(BIN1, !direction);
    digitalWrite(BIN2, direction);
    analogWrite(PWMB, speed);
  }
}

void motorControl(float x, float y) {
  boolean currentDirection = y >= analogInput_Middle_Y;

    //map(value, fromLow, fromHigh, toLow, toHigh);
  if (currentDirection == REVERSE) {
    y = map(y, analogInput_Middle_Y, analogInput_Min, speed_Min, speed_Max) ;
  } else {
    y = map(y, analogInput_Middle_Y, analogInput_Max, speed_Min, speed_Max);
  }

  int subtractFromLeft = map(x, analogInput_Middle_X, analogInput_Min, speed_Min, y);
  int subtractFromRight = map(x, analogInput_Middle_X, analogInput_Max, speed_Min, y);

  if (subtractFromRight < 0) {
    subtractFromRight = 0;
  }

  if (subtractFromLeft < 0) {
    subtractFromLeft = 0;
  }

  int Throttle_RIGHT = y - subtractFromRight;
  int Throttle_LEFT = y - subtractFromLeft;

  boolean currentDirection_LEFT = currentDirection;
  boolean currentDirection_RIGHT = currentDirection;

  if (Throttle_LEFT < 1 && Throttle_RIGHT > 1) {
    currentDirection_LEFT = !currentDirection;
    Throttle_LEFT = Throttle_RIGHT;
  }

  if (Throttle_RIGHT < 1 && Throttle_LEFT > 1) {
    currentDirection_RIGHT = !currentDirection;
    Throttle_RIGHT = Throttle_LEFT;
  }

  move(1, Throttle_LEFT, currentDirection_LEFT);
  move(2, Throttle_RIGHT, currentDirection_RIGHT);

  }

void button()
{
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    digitalWrite(13, true);  // Flash a light to show received good message
    // Message with a good checksum received, dump it.
    Serial.print("Got: ");

    for (i = 0; i < buflen; i++)
    {
      int c = (buf[i]);
      Serial.print(c);
      Serial.print(" ");
      if (c == 65 ) {
        digitalWrite(23, !digitalRead(23));  //// A--RELAY A1
      }

      if (c == 66 ) {
        digitalWrite(25, !digitalRead(25));  //// B--RELAY A2
      }

      if (c == 67 ) {
        digitalWrite(27, !digitalRead(27)); //// C--RELAY B1
      }

      if (c == 68 ) {
        digitalWrite(29, !digitalRead(29)); //// D--RELAY B2
      }
/*
      if (c == 69 ) {
        digitalWrite(37, !digitalRead(37)); //// E--
      }

      if (c == 70 ) {
        digitalWrite(39, !digitalRead(39)); //// F--
      }
*/
      if (c == 71 ) {
        digitalWrite(31, !digitalRead(31)); //// G--RELAY C1
      }

      if (c == 72 ) {
        digitalWrite(33, !digitalRead(33));  //// H -- RELAY C2
      }

      if (c == 73 ) {
        digitalWrite(43, !digitalRead(43));  //// I --
      }

       if (c == 74 ) {
        digitalWrite(35, !digitalRead(35));  //// J --
      }

       if (c == 75 ) {
        digitalWrite(37, !digitalRead(37));  //// K --
      }

      if (c == 76 ) {
        digitalWrite(39, !digitalRead(39));  //// L --
      }
      if (c == 77 ) {
        digitalWrite(41, !digitalRead(41));  //// M --
      }
      if (c == 78 ) {
        digitalWrite(35, !digitalRead(35));  //// N --
      }

    }
    count++;
    // Serial.print(count);
    Serial.println("");
    digitalWrite(13, false);
  }
}

```

My new driver is came, I just scare to use it, heard that DC motor will draw upto 300A at the start, what should I do to reduce the start current?

# Answer
> 4 votes
As you wrote in comment you use this H bridge:

https://www.ebay.com/itm/60A-DC-Motor-Driver-Module-High-Power-motor-Speed-Control-Dual-Channel-H-bridge/122479397950

The description how to use it is clear:

But the listing doesn't say what will happen when you set state of `A1,A2=1.1` to that H-bridge.

When you set value of `A1,A2=1.1` to a unprotected (cheap) H-Bridge you get a direct short to ground through 2 transistors burning them instantly

Your code actually does not protect against that:

```
   if (motor == 1) {
    digitalWrite(AIN1, direction);
    digitalWrite(AIN2, !direction);
    analogWrite(PWMA, speed);
  } else {
    digitalWrite(BIN1, !direction);
    digitalWrite(BIN2, direction);
    analogWrite(PWMB, speed);
  }
}

```

If previous value of direction is 0 (`A1,A2=0,1`) and you want to set direction to 1 (`A1,A2=1,0`) when arduino runs the line `digitalWrite(AIN1, direction);` for few cycles you actually end up with `A1,A2=1,1` and MOSFETs go bye bye.

Try setting AIN1, AIN2 (or BIN1, BIN2) to 0 before adjusting the direction

```
   if (motor == 1) {
    digitalWrite(AIN1, LOW);
    digitalWrite(AIN2, LOW);

    digitalWrite(AIN1, direction);
    digitalWrite(AIN2, !direction);
    analogWrite(PWMA, speed);
  } else {
    digitalWrite(BIN1, LOW);
    digitalWrite(BIN2, LOW);

    digitalWrite(BIN1, !direction);
    digitalWrite(BIN2, direction);
    analogWrite(PWMB, speed);
  }
}

```

This way you are guaranteed that you always have at least one `0` there.

**EDIT:**

You wrote that the module contains IR2103s it should protect you from the problem I described above. (But my suggested fix is not dangerous so you can use it just in case)

There is another possibility. Maybe the rapidly changing of the direction induces high voltage spikes in the motor, and that burns the circuit. Do you see any power diodes there? Look at the image I pasted above it has 4 diodes that should safely discharge those spikes. Make sure your code does not change direction every few milliseconds.

---
Tags: arduino-uno, sketch
---


# Question
Title: Using ESP8266-01 via Arduino(no flash) without AT commands(using serial monitor)
I'm trying to build a smart Keychain using Arduino uno wifi(org, so Im using it like it's Arduino uno), ESP8266-01 And neo6m GPS device.

My esp8266 wasn't new, and it came without AT firmware. I flashed it so it could have AT commands but it's not completely working.

Anyway, the flash is using 115200 baud and I'd like to use serial monitor to communicate it using arduino(and blynk app). Is there a way could I do it without flashing the esp for 9600 baud rate?

Thanks!

# Answer
Arduino Uno WiFi Dev Ed has the on-board esp8266 wired to additional Serial interface (I2C to Serial adapter). With UnoWiFiDevEdSerial1 library you can use the on-board esp8266 and have Serial free for Serial Monitor and sketch upload. The EspProxy tool enables upload to the on-board esp8266 over the ATmega (passing bytes between Serial and Serial1). I am the author of the UnoWiFiDevEdSerial1 library.
> 1 votes

---
Tags: esp8266, flash, arduino-uno-wifi-dev-ed
---


title: RC-oscillator calibration in real time

text:
# Question
Title: RC-oscillator calibration in real time
This pesky watchdog RC oscillator is at the limit of its 10% tolerance already at room temperature. i was looking to bringing it to more like 5% (it stems from an internak 128 kHz RC oscillator) and the whole -40 ... 125 deg Celsius operating range. Can this reliably be done by reading the temperature of the MCU and applying an algorithm ? Any such working algorithm ?

The *calibration* is actually the adjusting of the number of cycles (of say, 125ms) the watchdog will run for. i.e. for 12.5 seconds I would run the watchdog timer 100 times, nominally. How do I temperature-compensate the 100 figure ?

# Answer
> 1 votes
Your description is pretty detailed but you've missed to tell, which device you are talking about.

I assume you are talking about the ATmega 328P in an Arduino Uno.
AFAIK you can only calibrate the so called `Calibrated internal RC oscillator`, which is used for the main operations.
You cannot calibrate the `Internal 128kHz RC oscillator` from the watchdog.

I think you might have some overhead from your sleep/wake cycles.
Instead of sleeping 100 times to get from 125ms to 12.5s you could sleep for 8s + 4s + 0.5s. Thus sleeping only 3 times. Which might save you some battery life.

# Answer
> 1 votes
We've been using the WDT delta as a temperature sensing method:

https://thecavepearlproject.org/2019/02/25/no-parts-temperature-measurement-with-arduino-pro-mini-to-0-005c-or-better/

Point being that once you have those calibration constants, you could use them use them to correct for WDT variation. OR you might be able to get away with a much shorter interval than the 1sec we use, with the micros reading as your WDT correction factor more directly.

---
Tags: oscillator-clock, temperature, watchdog
---


# Question
Title: Sending double data from Matlab to the Teensy 3.6 via the microUSB
I've been hitting against a wall for over a week now. My current project is to use a Teensy 3.6 to send data over an SPI bus to a chip which is effective going to be a signal generator. I've made a GUI in Matlab to control this function generator in 'real-time' by sending over values such as frequency and amplitude. For my initial case, I just want to output a sine wave. to do this I am using the built in math function sin and just getting the amplitude and frequency from Matlab. However, when I send over my data I'm getting nothing on the output, but when I hard program in the values, it works just fine. From this I assume I am not sending the data over correctly OR not converting it correctly upon receiving it.

My order of operations are:

1. send my variable to the Teensy 3.6 using fwrite in Matlab

```
serialID = serial('COM5','BaudRate',115200);
fopen(serialID);
val = 2.55;
fwrite(serialID, val, 'double');

```
2. receiving the data on the Teensy 3.6 using Serial.read()

```
byte temp[8];

for (int c = 0; c<8; c++){
    temp[c] =Serial.read();
}

```
3. converting my byte array to a double using a union

```
double byteToDouble(byte DoubleInBytes[8]) {
    //Receives 8 bytes values and return them into a double value

    union {
       double   Out;
       byte   In[8];
    } U ;

    for (int c = 0; c < 8; c++) {
        U.In[c] = DoubleInBytes[c];
    }

    return U.Out;
}

```

I'm at a loss as to what I might be doing wrong. I've tried to use the serial monitor to monitor variable states but I can't use that while Matlab is using the COM port.

Any helpful tips would be appreciated.

# Answer
> -1 votes
I got a bit more traction on this issue on the Arduino forums and was able to answer it over there. I'm posting the link here to complete this post with a working answer. Hope it helps!

https://forum.arduino.cc/index.php?topic=598595.new#new

Thanks!

---
Tags: teensy, serial-data, matlab
---


# Question
Title: Serial plotter isn't displaying my supplied data
I want to use serial plotter feature of Arduino by using DHT11 as humidity sensor at a time. But I'm getting problem as plotter is not loading by the code I have. Please help me what is the problem because of which serial plotter is not loading.

Here is the Code I wrote:-

```
#include <dht.h>
#define dht_apin0 A0 // Analog Pin sensor is connected to

dht DHT0;

void setup() {

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity Sensor\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT0.read11(dht_apin0);

    Serial.print("Current humidity = ");
    Serial.print(DHT0.humidity);
    Serial.print("%  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()

```

# Answer
You can't send arbitrary information (percent signs, text etc) to the plotter. The plotter *only* understands numeric values. You have to separate these number values from each other with commas, then do a `println` in your last value:

```
Serial.print(percent);
Serial.print(F(","));
Serial.print(tankPercent(depth));
Serial.print(F(","));
Serial.print(litres);
Serial.print(F(","));
Serial.println(tankLitres(depth));

```

In your case, it'd be simply:

```
Serial.println(DHT0.humidity);

```

You can go a bit further if you want to switch between either serial output, or serial plotter. In one case, I just set a constant variable for graph or plain data, then have a function for each (my above `Serial` statements are actually within a function called `displayGraph()`). The data function would be something like you had originally, example:

```

void displayData(float depth, float percent, float litres){

  // water level depth (inches)

  Serial.print(F("current missing inches: "));
  Serial.println(mixtureDistance());

  // cubic inches

  Serial.print(F("total cubic inches: "));
  Serial.println(TANK_TOTAL_CUBIC_INCHES);

  Serial.print(F("current cubic inches: "));
  Serial.println(tankCurrentCubicInches(depth));

  // litres

  Serial.print(F("total litres: "));
  Serial.println(TANK_TOTAL_LITRES);

  // ... etc
}

```

I also have projects where I use a switch that if on, sets a flag to output in serial graph format, and if off, uses the serial data routine.

Then, in your sketch `loop()`, you'd do something like:

```
graph
  ? displayGraph(depth, percent, litres)
  : displayData(depth, percent, litres);

```

...or a bit more verbose rather than using the tertiary operator:

```
if (graph){
  displayGraph(...);
}
else {
  displayData(...);
}

```

Here's a Q&D serial plotter example of my `displayGraph()` function above. In the top-right corner of the image, the four colours represent the four pieces of data I'm sending in, in order:

In my case, those represent the exponential moving average of the percentage of how full a liquid tank is, the second is the raw data I'm building that average on, third is the exponential moving average of how many litres are remaining in the tank, and lastly, again, the raw data for that average.

The sharp movements are simply me slapping the tank to get some variable and unstable readings for example purposes.
> 2 votes

---
Tags: arduino-uno, programming, sensors
---


# Question
Title: Memory usage: #define vs. static const for uint8_t
I'm writing an Arduino library to communicate with an I2C device, and I'm wondering what the best way is to declare all the register addresses so as to save memory.

Using `#defines`:

```
#define REGISTER_MOTOR_1_MODE 0x44
#define REGISTER_MOTOR_2_MODE 0x47

```

Or using `static const`:

```
static const uint8_t REGISTER_MOTOR_1_MODE = 0x44;
static const uint8_t REGISTER_MOTOR_2_MODE = 0x47;

```

(Obviously I have more than just two registers I need to declare, but I thought two would illustrate the point just fine)

# Answer
> 8 votes
You'll find no noticeable difference memory-wise between the two.

The only real difference is that the `const` method also imposes a type to the value, which can be useful for function overloading or mathematical operations.

# Answer
> 6 votes
A `#define` is a preprocessor macro. As Gerben says in his comment, it's just an automated find-and-replace.

If you use it to hold things like C string constants, e.g. `#define ERROR_STRING "You messed up, bud!"` it could actually cause your program to take more memory, since that same string literal will be duplicated every time you reference it. In that case a static const would be both type-safe AND reduce memory usage.

# Answer
> 3 votes
Theoretically both approaches should consume the same amount of space and will probably result in the same code.

---

However, rather than that meaning "pick any one", what that actually means is that you should turn your attention to other factors when deciding which one to use.

As a rule of thumb you should generally avoid macros because they don't respect scoping rules due to how they work.
This can lead to some serious problems in certain cases.
See Why are preprocessor macros evil and what are the alternatives?.

---

However, I'd like to point out a third option: `constexpr`.

```
constexpr uint8_t motorMode1Register = 0x44;

```

`constexpr` implies `const` and is a better expression of the intent that the value should be capable of being evaluated at compile time.
`constexpr` literally means "this is a constant expression and thus can be evaluated at compile time".
As a result of this, `constexpr` variables can be used in situations where other variables cannot, such as template parameters.

See Constexpr vs Macros.

---
Tags: c++, memory-usage
---


# Question
Title: ATTiny85 I2C connection with Arduino Nano
I am trying to send and receive data using I2C between an Arduino Nano and an ATTiny85. The ATTiny is mounted on this board: Link

I've tried to reach the slave with the simple I2C scanner, but I don't find anything.

Those are the codes:

Master (I2C scanner):

```
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(500);           // wait 5 seconds for next scan
}

```

And this is the code of the ATTiny85 (slave):

```
#include <TinyWire.h>

#define led_pin 1

byte own_address = 10;

void setup() {
  // config led_pin as Output for driving an LED
  pinMode(led_pin, OUTPUT);

  // config TinyWire library for I2C slave functionality
  TinyWire.begin( own_address );
  // sets callback for the event of a slave receive
  TinyWire.onReceive( onI2CReceive );
}

void loop() {

}

/*
I2C Slave Receive Callback:
Note that this function is called from an interrupt routine and shouldn't take long to execute
*/
void onI2CReceive(int howMany){
  // loops, until all received bytes are read
  while(TinyWire.available()>0){
    // toggles the led everytime, when an 'a' is received
    if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
  }
}

```

Once I've programmedo both the boards I've connected SCL and SCK pins of the boards together.

If i open the serial monitor of the master this is what i get:

> I2C Scanner Scanning... Unknown error at address 0x20 Unknown error at address 0x21 No I2C devices found
>
> Scanning... Unknown error at address 0x78 No I2C devices found
>
> Scanning... No I2C devices found
>
> Scanning... Unknown error at address 0x08 Unknown error at address 0x09 Unknown error at address 0x60 No I2C devices found
>
> Scanning... Unknown error at address 0x70 No I2C devices found

And so on. Can someone explain me were I'm doing errors?

# Answer
> 1 votes
Problem solved!

I've modified the code, this is the final one:

```
#include <TinyWire.h>

#define led_pin 1
#define I2C_SLAVE_ADDR  0x11

void setup() {
    // config led_pin as Output for driving an LED
    pinMode(led_pin, OUTPUT);

    // config TinyWire library for I2C slave functionality
    TinyWire.begin( I2C_SLAVE_ADDR );
    // sets callback for the event of a slave receive
    TinyWire.onReceive( onI2CReceive );
}

void loop() {

}

/*
I2C Slave Receive Callback:
Note that this function is called from an interrupt routine and shouldn't take long to execute
*/
void onI2CReceive(int howMany){
    // loops, until all received bytes are read
    while(TinyWire.available()>0){
        // toggles the led everytime, when an 'a' is received
        if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
    }
}

```

Like this the I2C scanner sees the board at the address 0x11.

The wirings are the following:

* Arduino pin SCL to ATTiny85 pin SCL (P2)
* Arduino pin SDA to ATTiny85 pinSDA (P0)
* Take care of wire to the same ground both the boards.

---
Tags: c++, arduino-nano, i2c, attiny85
---


# Question
Title: Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?
Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?

This is about an Arduino Uno.

# Answer
This is the main function of the Arduino core:

```
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

`serialEventRun()` runs the `serialEvent()` function, if it is assigned, so yes, **a delay in serialEventRun will delay the loop**.
> 1 votes

# Answer
In an Atmega328p, the Uno's processor, there is only 1 CPU; it can only do one thing at a time. If it is executing code in the SerialEvent() function, then by definition, it is *not* executing code in the loop() function or anywhere else.

There is a minor exception to this: interrupt service routines will run briefly when their respective interrupts occur. In fact, one way a delay() function can operate depends on timer updates that take place as interrupts. (The other way is by executing a loop whose execution time is accurately known, a specified number of times).

But interrupt service routines do one, very short, job, and return the CPU to whatever it was doing immediately before (delay() within the SerialEvent() function), so no other user code can be executed until the delay ends.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Specific formatting of floats and converting them to an array of chars
I have an oled display which can only display 4 digits + decimal point. I need a way to format the number into 4 significant figures; Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.

Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

# Answer
Normally `sprintf()` would be the solution - however the `sprintf()` in the AVR LIBC is a cutdown version with no floating point support.

Instead you have to use `dtostrf()` to get the job done:

```
dtostrf(val, 6, 4, buffer);

```

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.

Another (nasty) way would be to go via `String` (although I would never recommend using `String` for anything, ever):

```
String s(val, 4);
const char *buf = s.c_str(); // this points to the internal char buffer.

```
> 2 votes

---
Tags: arduino-nano, array, float
---


# Question
Title: STM32 Nucleo F401RE in Arduino IDE - how to enable more than 1 Serial?
I just received a Nucleo F401RE and can't get my sketch to work on it because the compiler says Serial1 is not defined. My sketch uses multiple serials because I need to use the usb serial monitor while also communicating to another device on a different serial port.

Here is a screenshot of the flags I selected.

According to the F401 specs it has at least 6 different serials, so the real question is: is there an easy way to use Serial1 and so on straight out of the box in the Arduino IDE?

I'm quite new and unexperienced to this field, so please excuse me if this question is too trivial.

# Answer
Frederic Pillon on Github has been very helpful and suggested me the solution, which is to define the serial via:

```
HardwareSerial Serial1(PA10, PA9);

```

instead of just giving Serial1 for granted as you would do on a regular Arduino mega
> 2 votes

---
Tags: serial
---


title: How do I provide a negative current?

text:
# Question
Title: How do I provide a negative current?
I'm trying to use an ATMega328 board to control a board of a broken UPS device. I replaced all the internals of the UPS by custom components, so the only things which remain are the chassis and the front board.

On this board, there are five buttons, and three LEDs.

All those components are connected to the ground, each one through its own resistor. By connecting the different pins to the ground and to analog pins of the ATMega328 board, I can successfully detect when the buttons are pressed.

Things, however, get tricky when I want to turn the LEDs on. They have their anode connected to the ground (through a 47Ω resistor), and their cathode connected to a dedicated pin. This means that if I apply voltage to this pin, the LED remains off.

The LED, however, turns on if I connect the ground to a 5V pin on ATMega328 board and the cathode pin to the ground of the ATMega328 board. However, connecting the ground to 5V makes it impossible to read the state of the buttons (or should I wire them somehow specifically?)

Therefore, **how do I feed negative current from the ATMega328 board?**

There is a similar question on this subject, but while the author wants to “understand the underlying electronics of the arduino and microcontrollers in general,” I, instead, just want to know how to make it work. Reading the answers from the linked question, I have an impression that this is possible, but they don't explain *how* to do it.

# Answer
If the LEDs turn on when you apply 5V to *ground* then what you have identified as GND on the board is actually VCC. There is no such thing as *negative current*: current is either **sourced** or **sinked**, depending if it’s exiting or entering into a node.

The diodes (LED) are one way valves, so you have a clear current direction: once that is established, identifying a button press can work either triggering when it gets LOW or when it gets HIGH, in other words that can be easily reversed.

If previously you where detecting a button press with `digitalRead(BTN_PIN) == HIGH` then just switch to `digitalRead(BTN_PIN) == LOW` and you have your solution.
> 3 votes

# Answer
The answer by Roberto Lo Giacco was helpful, but I still had hard time understanding what is happening and how should I wire the boards properly. Since others may encounter similar problems, I'll explain the solution in my own words.

Note that an answer to a similar question helped me as well.

---

When a digital pin is set to high with `digitalWrite(LED_PIN, HIGH);`, it's similar (probably not in electrical terms, but at least in terms of interface) to connecting to 5V what was previously connected to the pin.

Similarly, `digitalWrite(LED_PIN, LOW);` is similar to connecting to GND what was previously connected to the pin.

This means that when the LED is connected as usual, cathode to the GND and anode (through a resistor) to a digital pin:

* `digitalWrite(LED_PIN, HIGH);` turns the LED on, and:
* `digitalWrite(LED_PIN, LOW);` turns it off.

Now, if the cathode is connected to the digital pin, the anode (through a resistor) can be connected to 5V. In this situation:

* `digitalWrite(LED_PIN, HIGH);` turns the LED off.
* `digitalWrite(LED_PIN, LOW);` turns it on.

On the photo in my question, the black wire is connected to GND. Instead, it should be connected to 5V. Other wires remain unchanged.

When it comes to the buttons, in order to determine whether the button is pressed or not, I was doing this:

```
if (analogRead(ESC_PIN) == 0) {
    // The ESC button is pressed.
}

```

When the button wasn't pressed, the values from `analogRead` were quite random, ranging from 50 to 250, or something like that. A zero value would indicate that the button was pressed.

With the new wiring (5V instead of GND), the new values from `analogRead` range from 350 to 900 when the button is not pressed. When the button is down, the value becomes 1023. Therefore, the new condition is simply:

```
if (analogRead(ESC_PIN) == 1023) {
    // The ESC button is pressed.
}

```
> 0 votes

---
Tags: pins, current
---


# Question
Title: Read from serial monitor and put it in a array of byte
I'm a new here and this is my first question. I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor. This is the code that I tried:

```
byte A[6];

void setup()
{
}

void loop() {
  A[6] = Serial.read();
  Serial.write (A);
}

```

# Answer
If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.

The problem you make is you always store the value in the 6th element of the array A, however A only has elements A\[0\] to A\[5\], so A\[6\] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.

To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.

Like:

```
byte arr[6];
index arrIndex;

void setup()
{
   arrIndex = 0;
}

void loop() {
  // Read serial.
  arr[arrIndex] = Serial.read();

  // Increase counter
  arrIndex++;

  // If the maximum is read, print values and reset it.
  if (arrIndex == 6) {
     // Print the elements.
     for (index = 0; index < 6; index++)
     {
        Serial.write(A[index]);
     }

     // Restart counter.
     arrIndex = 0;
  }
}

```

An improvement: instead of 6 everywhere, use a define:

```
#define MAX_ELEMENTS 6

```
> 1 votes

---
Tags: serial
---


title: GPS detecting stationary?

text:
# Question
Title: GPS detecting stationary?
can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,

```
uint8_t speedZero() {
uint8_t spd = gps.speed.mph();
  if (spd < 5) {
    return 0;
  } else {
    return spd;
  }
}

```

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.

# Answer
> 1 votes
I found this to get me started.

http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/

---
Tags: gps, tinygps, speed
---


# Question
Title: How do you make a switch case run until another serial input is detected?
I am trying to create a Traffic Light Controller.
There are three modes to the controller:
Mode 1 - the traffic light operates RED-YELLOW-GREEN-YELLOW and should repeat
* (The other modes are not necessary apart from knowing the user can select the mode.)\*

I want to loop the function of the mode until I receive an input from the serial monitor. If no input is detected, then it should continue with the current mode.
At the moment I am using **Serial.read()** at the start of the main loop function before my switch statement to select the mode. However, this needs an input, but I want the switch cases to loop until an input is received.

All help will be much appreciated.

# Answer
Use something like this (it is pseudo code so convert it to your sketch):

```
enum EState { NORMAL, SPECIAL } _state; // States
enum ENormalState { RED, YELLOW1, GREEN, YELLOW2 } _normalState; // State only valid when _state == NORMAL
unsigned long _time; // _time only valid when _state == NORMAL

void loop()
{
   if ('serial input available')
   {
      if ('input == ...')
      {
         _state = NORMAL;
      }
      else if ('input == ...')
      {
         _state = SPECIAL;
      }
      ...
   }

   switch (_state)
   {
   case NORMAL:
       if (_time + ... > time())
       {
          // Change to next state
          switch (_normalState)
          {
          case RED:
              _normalState = YELLOW1;
              _time = time();
              break;

          case YELLOW1:
              _normalState = GREEN;
              _time = time();
              break;
          ...
          }

       setLight(_normalState); // Change the light according to the _normalState
       break;

   case SPECIAL:
       ...
       break;

   ...
   }
}

```

Ideas to improve/explain:

* Try to make some specific functions for setting the light according to the current state
* You do not need a delay
* Split functions (like above, make a separate function for normal state, and specific state
> 1 votes

# Answer
thankyou for your responses.
I managed to solve this myself by using a while loop to store the code inside each switch case, my working code is below, utilising **Serial.peek()** and by changing the input ending in the serial monitor to **no line ending**.

```
while ((Serial.peek() == -1)){
          regularMode(ledRed, ledYellow, ledGreen);
}

```

Serial.peek() gets the next item from the serial stack, if there is nothing there, it returns '-1' so i can check against that as shown above.
> 1 votes

---
Tags: serial, programming, loop
---


# Question
Title: Good quality sound using a microcontroller
I am a hobbyist. Doing some experiments with sound quality. I'll pin point my problem and requirements.

1. **Problem statement** :I want to play audio files ( recorded in human voice, not music files, just some plain human speech files)
2. **I have tried** : a project with an Arduino microcontroller and MicroSD card but audio quality was not at all good from the link below https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/ https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player It just used an arduino UNO board, microSD using SPI, a speaker and an LM386 Audio Amplifier.

I read about the details and got to know that I need a DAC for better quality (as PWM cannot serve the purpose), and a speaker also. But there are a number of things available and I dont understand which one to buy and start a project.

Can you share the details of some micro-controller board with a DAC which suffice my purpose, memory to store audio files (or I can use a microSD card device), and a speaker project which I can follow and make one. I am looking for a board based solution, after getting some results, I can go for separate micro-controller and DAC.

Thanks in advance.

# Answer
> 1 votes
Here is the schematic and breadboard layout I was using. Coding can be found in this Arduino.cc thread

https://forum.arduino.cc/index.php?topic=180769.60

# Answer
> 3 votes
One would think that single channel for voice would be enough. Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel. 12 bits at 16 MHz for max 8 KHz bandwidth would be good. Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "

I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs. Or you could get a DAC only card from Gravitech.us

I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it. You can find it by searching "sample, record, playback later" and it should pull it up.

---
Tags: audio
---


# Question
Title: Arduino SDFat Libray overwrites last value
I'm trying to create a comma delimited file using this SDFat library

Calling this code creates my file

```
const char Header[24]="Desired RPM,Output RPM\n";
...
foo()
{
  SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
  SpeedCache.write(Header);
  SpeedCache.sync();
}
...

```

After running, I have a file containing

> Desired RPM,Output RPM'\n'

When I call the following function, I want it to add `int target` and `int reference` to the bottom of the file.

```
bool SDClass::SetLine(SdFile Cache,int target, int reference)
{
  bool good = false;
  char NewLine[32];
  Cache.seekEnd();
  sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
  Serial.println(good=Cache.write(NewLine));
  Cache.sync();
  return good;
}

```

On the first call, this works so for an input of `SpeedCache,50,100` I get

> Desired RPM,Output RPM'\n'
>
> 50,100'\n'

However, if I then write an input of `SpeedCache,5,10` I get

> Desired RPM,Output RPM'\n'
>
> 5,10'\n'

How do I adjust my function so that I will get:

> Desired RPM,Output RPM'\n'
>
> 50,100'\n'
>
> 5,10'\n'

# Answer
You just need to open the file in APPEND mode:

```
SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

```

> O\_APPEND
>
> The file is opened in append mode. Before each write, the file offset is positioned at the end of the file, as if with lseek.

You should also pass your file around by *reference* so it doesn't keep creating new copies of the internal structure:

```
bool SDClass::SetLine(SdFile &Cache,int target, int reference)

```
> 2 votes

# Answer
How do you pass the file by reference?

```
SdFat sd;
SdFile DataFile;

isSD = DataFile.open(FileName, O_WRITE | O_CREAT | O_AT_END);

```
> 0 votes

---
Tags: arduino-mega, fat
---


title: Send files via network

text:
# Question
Title: Send files via network
I want to send a file from an Arduino to the server or another Arduino.

I wrote a code that's open the file then write the content of the text on an array and then send it.

That would work if the data is small, but when i try to send, .wav it will takes lots of time if i do it that why (storing each byte in array). I want to send the whole file at on time. Is there a way or a library helps ?

```
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SD.h>

const int push1 = 2;

File myFile;
char a[400];
int c= 0;

// network parameters
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
IPAddress localIp(10,131,41,72);    // local ip address
IPAddress destIp(10,131,41,74);      // destination ip address
unsigned int port = 9631;               // destination port

// EthernetUDP to send and receive messages.
EthernetUDP Udp;

// timing

// setup the arduino and shields
void setup() {

    pinMode(push1, INPUT);

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // start ethernet and udp
  Ethernet.begin(mac, localIp);   // static ip version
  //if(Ethernet.begin(mac) == 0) {     // dhcp version
  // report failure to obtain network parameters
  // Serial.println("DHCP error");

  // no point in carrying on, loop indefinitely:
  // while(true)
  // ;
  //}

  // open UDP port
  Udp.begin(port);

  // show the local ip address (useful for dhcp)
  Serial.print("Local IP: ");
  Serial.println(Ethernet.localIP());

  // initialize previous millis variables

}

// do tasks
void loop() {

if(digitalRead(push1) == LOW){

   myFile = SD.open("R.wav" , FILE_READ);

  if (myFile) {
    // read from the file until there's nothing else in it:
    Serial.println("i will send now");
    while (myFile.available()) {
        a[i] = myFile.read();
        i++;
        }
      Udp.beginPacket(destIp, port);
     Udp.write(a);
      Udp.endPacket();
      Serial.println("Sending UDP message");
      Serial.println();
    }
    // close the file:
    myFile.close();
  } else {
   // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }  } }

```

# Answer
You may try:

```
Serial.println("Sending UDP message");
Udp.beginPacket(destIp, port);
while (myFile.available()) {
  Udp.write(a);
}
Udp.endPacket();
Serial.println("Message sent!");

```

Or send the message part by part (for example 100bytes or 500bytes at a time)

Though, what makes you think that Arduino would be a platform that can rapidly send large files over network? Potentially you are better off with an Raspberry Pi.
> 2 votes

---
Tags: arduino-uno, ethernet, networking
---


# Question
Title: Does the Node MCU v3 (LoLin) not have a builtin led?
Trying a simple led blinking program I could not get the builtin led on a LoLin Node MCU v3 working. The `LED_BUILTIN` constant is set to pin 16 / GPIO16 / D0.

Reading several articles and QA I think that the Node MCU boards are supposed to have a the on-board led on pin 16. However, if I address this port nothing happens.

With the same code I can blink the data led which is on a RX pin, pin 2.

Is the builtin led missing on the LoLin Node MCU v3, or could it be that the led on my board is broken?

# Answer
the ESP8266 has a builtin led that is attached to D4 as labeled on LoLin boards which maps to GPIO2. One thing to Note is that the led is active low. In other words ... setting PIN 2 to '0' will turn the LED ON and setting PIN 2 to '1' will turn the LED OFF

Lolin Builtin\_Led Picture

This is the only LED on the LoLin boards and differs from other devkits that have an LED on GPIO16.
> 33 votes

# Answer
I have nodeMCU v3 and Pin 2 worked for me.

```
#define LED_BUILTIN 2

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

```
> 7 votes

# Answer
The NodeMCU with the CP2102 serial and a slightly narrower pin footprint does have 2 LEDs.

```
$led1 = BUILTIN_LED;  //D0, 16, BUILTIN_LED: OnBoard LED
$led2 = 2;    //Pin 5 D4/2 Internal LED for LoLin V3

```

The `$led1 = BUILTIN_LED` (on GPIO 16) is \**not\* on the LoLin NodeMCU v3.
> 3 votes

---
Tags: nodemcu
---


# Question
Title: How to combine two different sensor sketches to one complete sketch?
How to combine two different sensor sketches to one complete sketch for a complete circuit that attaches to one Arduino Uno?

**Sharp Dust Sensor**

```
int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}

void loop(){
  digitalWrite(ledPower,LOW); // power on the LED
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin); // read the dust value

  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH); // turn the LED off
  delayMicroseconds(sleepTime);

  // 0 - 5V mapped to 0 - 1023 integer values
  // recover voltage
  calcVoltage = voMeasured * (5.0 / 1024.0);
  dustDensity = 0.17 * calcVoltage - 0.1;

  Serial.print("Raw Signal Value (0-1023): ");
  Serial.print(voMeasured);

  Serial.print(" - Voltage: ");
  Serial.print(calcVoltage);

  Serial.print(" - Dust Density: ");
  Serial.println(dustDensity); // unit: mg/m3

  delay(1000);
}

```

**MQ-135 Sensor**

```
int airquality = A2;
void setup()
{
  Serial.begin(9600);

}
void loop()
{

  int sensorValue = analogRead(A2);
  Serial.print("Air Quality = ");
  Serial.print(sensorValue);

  Serial.print("*PPM");
  Serial.println();
  delay(1000);

}

```

# Answer
I will leave a simplified answer and I would recommend to read https://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/ or similar to get a understanding of how to code.

An Arduino sketch has a structure.

1. Initialising values
2. A `void setup()` this code only run once the MCU is started
3. A `void loop()` and this code runs continuously.

So to merge two sketches you need to combine the code that is in the same sections and of course avoid duplicate code and ensure that you have unique variable names

**Sharp Dust Sensor**

```
int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}

```

**MQ-135 Sensor**

```
int airquality = A2;
void setup()
{
  Serial.begin(9600);
}

```

**Combined code**

```
int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2
int airquality = A2;

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}

```
> 3 votes

# Answer
There is no way of "automatically" combine two sketches into one. That's because resources of Arduino are very limited. For example UNO it has only 4 timers. If both of the sketches want to use same resource they will not work properly.

If you want to combine two sketches into one you have to write a new sketch that combines mechanisms of both sketches. It's not easy, because `delay` and `delayMicroseconds` are going to give you problems, but you should be able to do that using `micros()` and `millis()` plus some modular math.
> 2 votes

---
Tags: arduino-uno, programming, sensors
---


# Question
Title: How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)?
With my ESP32 Board, Wemos Lolin32, I would like to make a http GET request to "http://www.arduino.cc/asciilogo.txt", read the text file and print the text file to the serial monitor.

**The question is:** Why isn't basically the txt file written to the serial monitor? How can it be achieved? Do I need some kind of conversion of the char?

I am using similar code to that from this example https://www.arduino.cc/en/Tutorial/HttpClient. Basically the code can be reduced to this minimal example:

```
#include <WiFi.h>
#include <HttpClient.h>

void setup() {

  Serial.begin(9600);

  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }
  Serial.println("Connected to the WiFi network");

  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("SETUP FINISHED");
}

void loop() {
  Serial.println("Connecting to httpClient");

 HttpClient httpClient;
  httpClient.get("http://arduino.cc/asciilogo.txt");
  while (httpClient.available()) {
    char c = httpClient.read();
    //Serial.print(c);
    Serial.write(c);
  }
}

```

**The expected result is:** I would like to see the characters from the txt file (https://www.arduino.cc/asciilogo.txt) in the serial monitor.

**The actual result is:** The connection to the WiFi can be established. In the serial monitor either question marks or strange symbols are displayed.

I have checked the baud and it is the same in the code and in the monitor. I tried to change this value, but it did not help.

# Answer
When switching from HttpClient to HTTPClient and using String payload = http.getString(); Serial.println(payload); I can achieve the expected result.
> 0 votes

# Answer
it is `http://arduino.cc/asciilogo.txt`. without www. www is redirected to https. you can verify it from a browser
> 1 votes

---
Tags: esp32
---


# Question
Title: How to chose softserial library use on Arduino project?
I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial. Because library too libraries i don't know which one can help complete my project.

# Answer
I think your problem is that you need 4 serial ports.

With software serial that's just not going to happen:

* SoftwareSerial can only receive on **one** serial port at any given time.
* AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
* NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.
> 5 votes

---
Tags: arduino-nano, softwareserial, uart
---


title: Fast data logging

text:
# Question
Title: Fast data logging
I want to store noise data (basically from A0) from an Arduino Uno to an SD card with faster writing speed, preferably by using 512 data together and the write it at once. What should be the code?

# Answer
1. Read the values into an array big enough to store them
2. Write the array with the `write(const uint8_t *buffer, size_t size)` method.

Each `write` then gives you a block of binary data (512 values, 1024 bytes if they're 16-bit integers) written to the SD card. What you do with it then is up to you.

Note: an Arduino UNO only has 2kB of memory. If you have 512 integers that's half your memory gone. The SD card library needs another 512 bytes or more for its internal sector buffer. That's another 25% of your memory used. Already you're up to 75% of your memory gone.
> 2 votes

---
Tags: arduino-uno, datalogging, serial-data, sd
---


# Question
Title: Path relater errors on compilation in Arduino IDE 1.8.5 under Windows XP
For the XP under the Russian locale I'm getting the strange output when trying to compile Marlin project for Anycoubic 3d printer according to instruction https://3dtoday.ru/blogs/trialon/marlin119-for-anycubic-kossel-linear-plus

avr-g++: error: C:\DOCUME~1\ИЖИ: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino\_build\_153827\sketch\Marlin.ino.cpp: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino\_build\_153827\preproc\ctags\_target\_for\_gcc\_minus\_e.cpp: No such file or directory

avr-g++: warning: '-x c++' after last input file has no effect

avr-g++: fatal error: no input files

compilation terminated.

exit status 1 Ошибка компиляции для платы Arduino/Genuino Mega or Mega 2560.

# Answer
I have realized that the root cause was the windows user with the Cyrillic name. So creating a new user wiht base Latin name and running Arduino IDE from it helped
> 2 votes

---
Tags: compilation-errors
---


title: Can't flash ESP8266 anymore (NodeMCU)

text:
# Question
Title: Can't flash ESP8266 anymore (NodeMCU)
So I've been happily making away with these nodeMCU boards now for a while but I came across a strange issue when updating some code on my board.The problem was that I couldn't flash anymore with Arduino's IDE (OR the NodeFlasher tool)

The error I was getting in Arduino's IDE was:

```
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

```

I tried flashing over all the memory with the flash tool but that didn't work, I also tried connecting D3 to 3.3v output, that did nothing. I've also tried holding the flash button down while flashing without any effect.

# Answer
The fix ended up being to use a 220ohm resistor between D3 and GND (It has been pointed out, though I haven't tested it, that just wiring D3 to ground on startup should have the same effect). Then unplugging the USB cable, plugging it back in, then flashing the blink program to test. That got it going. I tried a 10kohm resistor too per some documentation I read but that didn't end up working. Wanted to post in case someone else stumbled on this issue.

**Source**

GitHub Issue

**Helpful Articles:**

ESP8266 bootloader modes

NodeMCU Pinout
> 3 votes

---
Tags: esp8266, nodemcu, flash
---


# Question
Title: Getting different values inside vs. outside a function while using global array
function `splitter` is designed to get a string of parameters and create a an array of parameters. If only part of parameters were given, the rest of them will get default values.

for example : input string `1,2,3,4` would fill `parameters` array with values `{"1","2","3","4"}`, but if input string is `1,2`, `parameters={"1","2","20","0"}` while `parameters[3]` and `parameters[2]` were given its default values.

**BUT**

when assigning default values, inside `splitter` the correct values are stored in `parameters` but when using `print_output` function to show `parameters` values - different values are shown.

in output supplied, when input is `1,2`, default values should be pasted, to `parameters[2]`, and `parameters[3]` , while input is `1,2,3,4` no need to use defaults.

**OUTPUT:**

```
Running string 1,2
param_2 was set to default value:20
param_3 was set to default value:0
output:
1
2
0
0
Running string 1,2,3,4
output:
1
2
3
4

```

**CODE:**

```
#define PARAM_AMOUNT 4
#define COLOR 1
#define LED_DELAY 20
#define BRIGHTNESS  50
#define LED_DIRECTION 0

char *parameters[PARAM_AMOUNT] = {"0", "0", "0", "0"};
int param_def[] = {COLOR, BRIGHTNESS, LED_DELAY, LED_DIRECTION};

void setup() {
  Serial.begin(9600);
  Serial.println("Running string 1,2");
  splitter("1,2");
  print_output();

  Serial.println("Running string 1,2,3,4");
  splitter("1,2,3,4");
  print_output();
}

void splitter(char *inputstr) {
  char * pch;
  int i = 0;

  pch = strtok (inputstr, " ,.-");
  while (pch != NULL)
  {
    parameters[i] = pch;
    pch = strtok (NULL, " ,.-");
    i++;
  }

  //  update default values
  for (int n = i ; n <= PARAM_AMOUNT - 1; n++) {
    sprintf(parameters[n], "%d", param_def[n]);
    Serial.print("param_");
    Serial.print(n);
    Serial.print(" was set to default value:");
    Serial.println(parameters[n]);
    delay(50);
  }
}

void print_output() {
  Serial.println("output:");
  for (int n = 0 ; n <= PARAM_AMOUNT - 1; n++) {
    Serial.println(parameters[n]);
  }
}

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

```

# Answer
> 1 votes
It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:

```
char parameters[PARAM_AMOUNT][PARAM_LEN];

```

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.

Then in `splitter` function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.

`strcpy(parameters[i], pch);` will copy the token returned by `strtok` into your array. `pch` points into `inputstr` and the delimiters in `inputstr` are replaced by 'strtok' with zeros

---
Tags: programming
---