# Question
Title: How to implement elapsed millis as the timer for my motor spinning time?
I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.

I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.

So, my question is, how do I implement the elapsed millis as my timer for my spinning motor? please, guys, help me with this... Just guide me through and give me guidance.

This is my code that I have tried using elapsed millis. Any suggestion is welcome.

```
#include <elapsedMillis.h>
#include <Keypad.h>
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
elapsedMillis timeElapsed;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
{
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{

  Serial.begin(9600);
  lcd.begin(20,4);
  myservo.attach(11);

   lcd.setCursor(0,0);
  lcd.print("S=");
  lcd.setCursor(0,1);
  lcd.print("T=");
  lcd.setCursor(0,2);
  lcd.print("S=");
  lcd.setCursor(0,3);
  lcd.print("T=");
  lcd.setCursor(10,0);
  lcd.print("S=");
  lcd.setCursor(10,1);
  lcd.print("T=");
  lcd.setCursor(10,2);
  lcd.print("RPM");

}

 void loop()

{

  int stage1speed = getTheNumber();
  lcd.setCursor(2,0);
  lcd.print(stage1speed);
  lcd.print("sv");
  int stage1time = getTheNumber();
  lcd.setCursor(2,1);
  lcd.print(stage1time);
  lcd.print("sec");

  int stage2speed = getTheNumber();
  lcd.setCursor(2,2);
  lcd.print(stage2speed);
  lcd.print("sv");
  int stage2time = getTheNumber();
  lcd.setCursor(2,3);
  lcd.print(stage2time);
   lcd.print("sec");

  int stage3speed = getTheNumber();
  lcd.setCursor(12,0);
  lcd.print(stage3speed);
  lcd.print("sv");
  int stage3time = getTheNumber();
  lcd.setCursor(12,1);
  lcd.print(stage3time);
  lcd.print("sec");

   if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
        && stage3time > 0 )

   {

    if(timeElapsed <= 1000*stage1time)

    {

     myservo.write(stage1speed);

     }

    if(timeElapsed <= 1000*stage2time)

    {

     myservo.write(stage2speed);

     }

    if(timeElapsed <= 1000*stage3time)

    {

     myservo.write(stage3speed);

     }
  }

}

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
           int value = atoi(buffer);  // Convert to an integer
            break;
        }

    }
    return atoi(buffer);
    }

```

# Answer
> 1 votes
`delay()` is only the tip of the iceberg. The problem with `delay()` is that it is a *blocking* function: nothing else can be done during the delay. If you want to control your motor and at the same time be responsive to the user, you must avoid blocking your program. This means not only getting rid of `delay()`, but also getting rid of *any blocking function*.

Here your problem is on `getTheNumber()`. This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return `-1` on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you `loop()` will restart very often, and the program will work with no significant latency.

As for managing the servo stages, simplest thing would be to write a finite state machine. I would write it with four states: IDLE, STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 → IDLE would be time-based, using the `elapsedMillis` object to track the time spent in each state. The transition IDLE → STAGE1 would be triggered by the user input.

```
static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
switch (state) {
    case IDLE:
        if (userRequestedToStartAgain()) {
            myservo.write(stage1speed);
            state = STAGE1;
            timeElapsed = 0;
        }
        break;
    case STAGE1:
        if (timeElapsed >= stage1time) {
            myservo.write(stage2speed);
            state = STAGE2;
            timeElapsed = 0;
        }
        break;
    case STAGE2:
        if (timeElapsed >= stage2time) {
            myservo.write(stage3speed);
            state = STAGE3;
            timeElapsed = 0;
        }
        break;
    case STAGE3:
        if (timeElapsed >= stage3time) {
            myservo.write(idleValue);
            state = IDLE;
        }
        break;
}

```

---
Tags: arduino-uno
---


# Question
Title: Does ADC conversion to a voltage rely on the actual value of the +5 V pin?
**Questions:**

1. Does the conversion of the ADC count to voltage depend on the actual voltage of the +5 V pin?
2. If yes, what is the accepted method of getting that voltage from the board?

**Background/Detail:**

I have a circuit in which I have an Arduino Nano (clone) running from a USB connector (from a hub). The job of the Arduino is to measure the voltage on a battery which will drive a second circuit switched on/off by the Nano. For reference it is a battery tester.

There is a Nokia 5110 screen which displays the voltage from the very simple sketch below.

```
void setup() {
  Serial.begin(9600);
  display.begin();
  // Init done

  // You can change the contrast around to adapt the display
  // for the best viewing!
  display.setContrast(50);

  // Text display tests
  display.setTextSize(1);
  display.setTextColor(BLACK);
}

void loop() {
  display.clearDisplay();   // Clears the screen and buffer
  display.setCursor(0,0);
  display.print("Vin=");
  int rawVIN = analogRead(VIN);
  float floatVin = (rawVIN*4.75)/1023.0;
  display.println(floatVin);
  Serial.println(rawVIN);
  display.display();
  delay(1000);
}

```
* I measured the voltage of the battery using a DVM and it is 4.13 V, yet the Nano reports 4.35 V.
* I have a common ground between the battery and Arduino.
* Because the connection to test the voltage can float, I have a pulldown resistor to stop wild fluctuations (\>10 kΩ)

After some investigation I found that the +5 V was actually outputting 4.75 V and changed my sketch from

```
float v = (rawVIN*5.0)/1024.0;

```

to

```
float v = (rawVIN*4.75)/1024.0;

```

and the voltage reading on the Arduino was now correct. I did this not because I understand what I did, I did it because I had a hunch it might change the value to the correct one.

# Answer
The ADC inside the Arduino does not measure voltage, but rather a voltage *ratio*. Namely the ratio from the voltage at the analog input to the voltage at the Vref pin.

In the default configuration, the Vref pin is internally tied to the +5 V line. You can select to use instead an internal reference as Vref:

```
analogReference(INTERNAL);

```

This reference is about 1.1 V, and is is quite immune to fluctuations on the +5 V. The problem is that you cannot measure voltages higher than the reference.

For your battery tester, if you want some sort of “absolute” measurement, you could use the internal reference and a voltage divider to ensure the measured voltage is below 1.1 V.

**Edit**: Another option which does not require a voltage divider is to use Vcc as a reference to measure *both* the analog input and the internal 1.1 V “bandgap“ reference. Measuring the 1.1 V against Vcc is an indirect way to measure Vcc. This is not supported by the Arduino core library, but you can do it by programming directly the control registers of the ADC:

```
// Return the supply voltage in volts.
float read_vcc()
{
    const float V_BAND_GAP = 1.1;     // typical
    ADMUX  = _BV(REFS0)    // ref = Vcc
           | 14;           // channel 14 is the bandgap reference
    ADCSRA |= _BV(ADSC);   // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait until complete
    return V_BAND_GAP * 1024 / ADC;
}

```

Beware that the very first reading after boot may be bogus.
> 15 votes

# Answer
A USB-powered Arduino Nano will have an ADC voltage reference which can't be relied on, due to the +/- 5% tolerance of the incoming USB voltage. On top of that, the Nano has an MBR0520 Schottky diode (D1) that will drop between 0.1 and 0.5 V depending on its own manufacturing tolerances, its temperature, and the current draw of your board.

**What can you do about it?**

The MCU on-board the Arduino Nano is an ATmega328P. The Nano's ADC can scale its analog voltage readings according to several available references (and you can choose the one that suits you better). You can do this through the `analogReference (type)` function, and chose among the following reference `type`s:

> * DEFAULT: the default analog reference of 5 volts (on 5 V Arduino boards) or 3.3 volts (on 3.3 V Arduino boards)
> * INTERNAL: An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega) \[...\]
> * EXTERNAL: the voltage applied to the AREF pin (0 to 5 V only) is used as the reference.

Source: analogReference

This is the ADC schematic for what's inside the ATmega328 so you can see what's going on there:

Source: ATmega328 datasheet

So the straightforward solution is building a weak voltage divider to get the voltage you want to measure below the INTERNAL 1.1 V reference, and then configure `analogReference` accordingly.

The voltage divider needs to be weak (high R values) so you don't draw too much current out of the battery, but not too weak as to be loaded by the ADC input impedance.

**Bonus**

However, if you need a voltage reference higher that the internal 1.1 V bandgap reference of the ATmega328 you're still out of luck. A option would be to use the 3.3 V LDO regulator output from the on-board FT232RL, which is available to you at pin 14 of the header, but I don't think it's reliable either. The FT232RL datasheet specifies it at 3.0 - 3.6 V (nominal 3.3 V)

So a universal solution would be to build an external voltage reference based on a cheap TL431. That could give you a reliable reference up to 4.0 - 4.25 V with a +/-1% accuracy.

The external voltage reference circuit would be something as easy as this, (and the TL431 is available in the breadboard friendly TO-92 package!):
> 9 votes

# Answer
I have a page about the ADC converter on the Atmega328P. Somewhat down the page I describe voltage references. You can use the TL431 chip to provide assorted reference voltages, for example 4V:

By changing the resistors you can get other voltages (it looks like you want around 4.2V).

The output voltage is not influenced by the input voltage (5V in this case).

The linked page describes how you might choose resistor values.
> 3 votes

# Answer
> Does the conversion of adc count to voltage depend on the actual voltage of the +5v pin?

yes and no: the adc module cares about Vref, which can be supply via Vdd, internally, or externally.

> If yes what is the accepted method of getting that voltage from the board?

by configuring the adc module. the device datasheet should have registers / bits that need to be set up for that.
> 2 votes

---
Tags: arduino-nano, analogread, voltage-level, adc, analogreference
---


# Question
Title: What are the problems with using an Arduino in a production environment?
I am thinking about making a real project using arduino to earn money.

What could be the objective reasons (from both a technical and a business perspective) to not use an Arduino in a real profitable project?

# Answer
> I want to know if there is anyone that has used Arduino boards in a real project?

I have seen it being done, quite a few times.

> What are the problems that you have faced?

Pros:

1. quick to market;
2. low cost accessories;
3. large code base to drop from;
4. ...

Cons:

1. only workable for certain applications -\> high cost per mcu (vs. bare chips), no possibility of passing certification of any rigor, no respect from others / clients, ...
2. quite inflexible an eco-system: porting code to / from others can be problematic.
3. poor project management capabilities.
4. ...

Each of those pros / cons can be addressed and may not be relevant for your particular application.
> 6 votes

# Answer
As a rule, no it's not a great idea.

Arduino boards are a prototyping platform. They are designed to make trying ideas out easy, not for permanent installation in a device. That's not to say you can't permanently install it in something of your own making, but when it comes to making a professional product it's not good, for a number of reasons:

1. An Arduino board is expensive compared to a plain MCU.
2. It's not a professional image.
3. It's not (typically) rugged and reliable enough.
4. Manufacturing something around a board like an Arduino is expensive.

The most professional way of using an Arduino would be to use something like an Arduino Mini and directly mount it on a custom PCB. But since you are making a custom PCB anyway, why would you incur the extra expense of an Arduino board when it is far cheaper to just build the required components directly into your board design? Also, when bulk manufacturing, you need to have as much of the build automated (i.e., surface mount to be populated by a pick-and-place machine) in order to keep costs down, and having to manually mount an Arduino onto a board adds extra expense (you have to pay a person to do the job themselves).
> 4 votes

---
Tags: project
---


title: Arduino Interrupt example not working

text:
# Question
Title: Arduino Interrupt example not working
The example program is from here: https://www.arduino.cc/en/Reference/attachInterrupt

When I paste in the code and run it, the LED is on all the time (It's supposed to blink):

```
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

```

This is my setup:

# Answer
I think you misunderstood this example: it is not expected to automatically blink!

The LED is suposed to change state at every change of level on pin 2. This supposes that you wired something (e.g. a push button) to pin 2 and that this will make pin 2 change level when something happens (e.g. you press the button or you release it).

On your diagram, there is nothing wired on pin 2, so what you observe is just normal.

If you want to see `attachInterrupt` in practice, then connect pin 2 to a button with the other button lead connected to `GND`.

Then you can observe what happens when you play with that button.
> 6 votes

# Answer
if you want to blink your LED by giving interrupt by push button then you can try this..

```
int pushButton = 2;
int LED = 13;
volatile bool flag = false;
volatile byte state = LOW;

void setup()
{
    pinMode(pushButton, INPUT_PULLUP);
    pinMode(LED,OUTPUT);
    attachInterrupt(digitalPinToInterrupt(pushButton), &setFlag, FALLING);
}

void loop()
{
    if (flag)
    {
        digitalWrite(LED, state);
        delay(100);
        state = !state;
    }
}

void setFlag()
{
    flag = true;
}

```
> 1 votes

# Answer
to expand on my comments to Prayuktibid's code, here is what I would propose in the loop:

```
void loop()
{
    if (flag)
    {
        //blink the led
        digitalWrite(LED, !digitalRead(LED));   //digitalWrite(LED, state);
        //delay(100);
        //reset the flag
        flag = false;                           //state = !state;
    }
}

```

the rest remains unchanged.

here is how it works:

it works as you would expect, without resorting to delays.

edit: btw, the approach shown above (of setting a flag in the isr, processing that flag in the main loop, and resetting the flag after the processing) is a fairly standard way of utilizing interrupts - pretty much the #1 choice unless you have some special reasons to deviate from it.

edit2: to just follow up on that state above (about trying to process the flag in the main loop).

for something this simple, you can also do it in the isr, making the code much closer to your original code:

```
void loop()
{
        digitalWrite(LED, flag);                //digitalWrite(LED, state);
}

void setFlag()
{
    //flip the flag
    flag = !flag;                               //flag = true;
}

```

the code above produced the same waveform as the code posted earlier.

the lessons learned: there is more than one way to solve a problem, as long as you do it right, :)
> 1 votes

---
Tags: arduino-uno, interrupt
---


# Question
Title: What shift register would I need for input OR output?
Background:

A few days ago I received a 23LC1024 1Mbit SRAM chip, which works like a charm. However, before I ordered that one, I ordered a LP621024D-70LL which also is a 1 Mbit SRAM but in DIP32 format, meaning LOTS of pins.

Now I made a breadboard setup with 3 shift registers 74HC595 to be able to set the address (tested with LEDs but should work).

However, when trying use a shift register for the data which can be read or write, I don't think I can use a 74HC595 since it is only for output. However, I also don't think a 74HC165 (shift in register) would work (if I had one).

Questions:

1. What kind of shift register would I need, one that can do both input and output? I read about I2C registers but that seems to be a bit of overkill.
2. I only have 74HC595 shift registers for setting the address, would that slow down SRAM? I mean are there faster registers? Not that I want to buy it, but just curious.

Here is a picture of a working LP621024D-70LL ... too bad the chip is barely visible , on the left are 2 74HC595s and right are also 2 (right one not used), these 3 shift registers take care of the address (17 bits -\> 3 bytes). The SRAM itself is hidden under the center of the cables.

# Answer
since you already have input, use an 74HC165 8-bit parallel-in/serial out shift register. They are cheap.

another cheap option with I/O is an expander like the PCF8574, which are almost cheap
> 2 votes

# Answer
From the web page about the 23LC1024:

> The memory is accessed via a simple Serial Peripheral Interface (SPI) compatible serial bus.

Using the SPI hardware on your Uno will be a *lot* faster than using software-based shifting. See my page about SPI.
> 1 votes

---
Tags: arduino-uno, shift-register, sram
---


title: Arduino I/O Shield relay won't switch

text:
# Question
Title: Arduino I/O Shield relay won't switch
I have an Arduino Uno and the I/O Shield wired up and I'm trying to switch (i.e. engage) a relay on the I/O Shield, but nothing seems to be working.

I've identified the input pins correctly and am able to send digital signals to it and it responds correctly. I also see the LED next to the relay light up when I do a digital write on the Arduino to a specific relay pin.

I'm starting to think that I might need to use an alternative power source or that I am not using the Arduino API correctly to switch the relay. At the moment I do a `digitalWrite(13, HIGH)`, delay, and then do a `digitalWrite(13, LOW)` \- pretty simple.

The shield is just powered by the Arduino at the moment, and I haven't been able to find where I might be able to plug in power, so I'm assuming the Arduino supplies it with all of the power it needs.

```
#include <Arduino.h>

int relayPin = 13;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
            digitalWrite(relayPin, HIGH);
        delay(5000);
        digitalWrite(relayPin, LOW);
        delay(5000);
}

```

# Answer
> 1 votes
Based on your newly-added photo, you are using the Velleman VMA05 I/O Shield (or the KA-05 kit version).

This shield **requires** a 12V 500mA (minimum current capability) power supply input to the Arduino Uno, as that board uses relays with a 12V coil. Your symptoms (LED lights but relay does not switch) suggest that you are using a lower voltage, or lower current, power supply to your Arduino. If so, then the fix is: Use the required power supply to the Arduino.

> I'm assuming the arduino supplies it with all of the power it needs.

Yes - but *only* if you meet the minimum requirements of the power supply which you connect to the Arduino. As documented in the Vellemen VMA05 datasheet and manual, this must be a 12V supply (not lower, not higher) capable of a minimum of 500mA.

(You would likely be able to use a 12V supply capable of a slightly lower current output, if you only wanted to have one or two relays active at the same time. However if more relays were active simultaneously, the risk would increase of incorrect or erroneous behaviour, due to the additional current necessary for each relay coil, in addition to powering the Arduino, eventually exceeding the capabilities of the power supply.)

# Answer
> 1 votes
Unless you share a schematic, it will be very difficult to provide a good answer.

Here are the things that you might be doing wrong:

1) Using a power supply which is not able to provide enough current to the relay.

2) Using a power supply of wrong voltage as required by relay coil. The relay might be needing 12 V and you might be trying to power it up with a 5 V power supply.

3) You might be trying to drive the relay directly with your GPIO pin (without using any external transistor switch).

4) Trying to raise a dead relay. There is a possibility that the relay is damaged. Check it by powering it up directly using a battery or another adequate power supply that you got.

# Answer
> 1 votes
Yes, 12V / 500mA supply is the minimum required for this board to work correctly. 9V will make the LED turn on but not pull the relay contacts properly. Also, I have had two of these boards where the back EMF diodes across the relay coils have gone short circuit causing excessive heating in the associated switching transistors. The solution is to replace these diodes with a more suitable 1N4001 type since the 1N4148 that is supplied with the kit is really a small signal diode and really not suitable for this purpose.

---
Tags: relay
---


# Question
Title: Liquid Crystal LCD Display Prints f in all rows and columns
The problem is that the Liquid Crystal LCD display only prints "f" on every row and every column.

When I tell it to print something, then the display prints "f" on every square(row, column) for a brief second, then each square shows three white bars stacked up parallel to each other (quite like an "=" sign except that there's one more bar on top").

I am also using a tmrpcm library, so I'm guessing that interrupts might have to do with this, but I have no idea how to solve the problem.

The link to the tmrpcm library is as follows: https://github.com/TMRh20/TMRpcm

Thank you so much. I need to get this done by tomorrow 8 A.M., so I'm pretty desperate.

```
#include <LiquidCrystal.h>
#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
#include <TMRpcm.h>           //  also need to include this library...

TMRpcm tmrpcm;   // create an object for use in this sketch
char mychar;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

volatile int pauseOnOff;

void setup(){

  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  else{
    Serial.println("success!");
  }

  tmrpcm.play("Closer.wav");

  lcd.begin(16, 2);

  lcd.print("hello, world!");
}

void loop(){

}

```

# Answer
I don't know the source of the problem, but here are a few things that might help diagnose where the problem begins or what it is due to.

(a) To track execution progress, and detect which statement, if any, ruins LCD operation: Create a routine to display current line number in code to LCD and Serial; make a macro `ss` to use for invoking that routine; invoke the macro before and after each line containing a `tmrpcm` action by calls like `ss;`. See following example.

```
void shoLine(int line) {
  Serial.println(line);
  lcd.home ();     // Set cursor to 0,0
  lcd.print(line);
  lcd.print(' ');
  delay(200);  // /Delay long enough to see stuff appear
}
#define ss shoLine(__LINE__)

```

Note: Move `lcd.begin(16, 2);` to be the first statement in `setup()` when using this method of debugging.

(b) If you find that the first few LCD calls are ok and then LCD output stops working, try turning off interrupts during LCD output. That is, put a `cli()` or `noInterrupts()` call before an `lcd.print()`, and an `sei()` or `interrupts()` after it, and see if it then works. If so, that might serve as a last-ditch workaround. (I don't know whether LCD output routines use any interrupts; I doubt they do; but if they do, this method won't work.)

(c) If the LCD doesn't display correctly at all, even before the first `tmrpcm` action, it may be that the combination of `tmrpcm` with other code is using too much memory. Carefully check the memory-usage reports when you compile your sketch.
> 2 votes

---
Tags: arduino-uno, lcd, tmrpcm
---


title: Slave SPI does not work

text:
# Question
Title: Slave SPI does not work
I am trying to use both an SRAM (23LC1024) and SD card reader on an SPI bus.

My connections (for SPI):

* Arduino pin 11 (MOSI) -\> SRAM pin 5 (SI/SIO0)
* Arduino pin 12 (MISO) -\> SRAM pin 2 (SO/SIO1)
* Arduino pin 13 (SCK ) -\> SRAM pin 6 (SCK)
* Arduino pin 10 -\> SRAM pin 1 (CS )

In this way, I can read data from the SRAM.

To connect the SD I connected:

* SRAM pin 2 (SO/SIO1) -\> SD MISO
* SRAM pin 5 (SI/SIO0) -\> SD MOSI
* SRAM pin 6 (SCK ) -\> SD SCK
* Arduino pin 9 -\> SD CS

Currently the SD card works, but read-byte commands to the SRAM always gives the same (wrong) value.

If I remove the wire between SRAM pin 2 and SD MISO the SRAM gives correct values, but the SD card does not have a MISO connection and seems to always return the same data (but still functions).

I also tried to first make the connections from the Arduino to the SD and than to the SRAM (but same result, not working).

What am I doing wrong?

Update: The problem is solved, however I do not understand why. I reconnected all pins, removed the shield to access the SRAM directly which worked. Than I put the shield back on (and moving the pins back) ... maybe it was something stupid that one pin did not have good contact. I'm sorry for the inconvenience.

New question (related):

Now it works with the Data logger shield, but not with the (cheap) SD reader breakout cards.

However, my eventual solution needs more proto space than is available on the Data logger shield.... do I really need to use a complete shield (and later the Arduino Mega), and a Mega proto shield ... that will be a big box. While for the data logger, I don't need the RTC neither.

# Answer
> 3 votes
It doesn't sound like you are doing anything wrong as such, it all sounds fine.

However SD cards, certainly some cheap ones, don't like to play nicely with other devices on a shared bus. Also some SD card adapters with level shifting don't play nicely.

By not playing nicely I mean tri-stating the MISO line in a timely fashion (or at all in some cases) which stops any data getting out of other devices, and can even cause damage in some cases.

You should check out the level shifting on the SD card adapter to see if it has tri-stating control of MISO (if it is shifting that line, not all do), try other brands of SD cards, and maybe add your own tri-state buffer to the SD card signals.

---
Tags: arduino-uno, spi
---


title: Analog pins for 4x4 matrix keypad

text:
# Question
Title: Analog pins for 4x4 matrix keypad
I am working on a project on nano and want to use analog pins for 4x4 matrix keypad input. My connections are for keypad are as follows:

* Digital pins are D10-D13 and Analog pins are A0-A3.
* A0-\>14,
* A1-\>15,
* A2-\>16,
* A3-\>17

Code is:

```
#include <Keypad.h> // includes the keypad library
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] = {
 {'1','2','3','A'},
 {'4','5','6','B'},
 {'7','8','9','C'},
 {'*','0','#','D'}
};

byte rowPins[ROWS] = {10,11,12,13}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {14,15,16,17}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

```

Can I use analog pins as I defined for keypad? Is "Keypad.h" library compatible with Arduino Nano v3.0?

# Answer
> -1 votes
The problem i was going through is because of **pin number 13**. Pin 13 is connected to LED and is not good option for taking input as it is connected to 3.3V internally. Because of this arduino was detecting one key pressed constantly making other key presses undetected. In this case the key was charecter \*.

> **ADVICE: Don't use pin 13 for input!**

# Answer
> 3 votes
You can use the analog pins. I prefer {A0, A1, A2, A3} in the code instead of {14, 15, 16, 17}. That makes it easier to check if you connected the wires to the right pins.

Don't use pin 13 for an input with the Arduino Nano. An LED is connected to that pin. You can use that pin as an output for something else.

---
Tags: arduino-nano, analogread, analogwrite, digital-analog-conversion
---


# Question
Title: How to load program into Arduino pro mini using FTDI cable?
Do we need a ftdi basic board to connect a ftdi 232R USB - TTL serial level converter cable via a 6 pin 0.1" male header into an Arduino pro mini/ nano 328 to upload the sketch?

# Answer
**For the Arduino Nano:**

**NO**, the Nano already includes the USB-to-TTL conversion circuitry. Just use the USB connector as you would with a Uno.

**For the Arduino Pro Mini:**

**YES**, you need an external breakout board to perform USB-to-TTL conversion. This board may use the FT232RL chip, but also any other equivalent one like the CH340G. You only need to have the adequate driver in your computer and you'll be set.

**NOTE:**

If you have "converter cable" you might not need a breakout board because this kind of cable already includes the FT232R (or equivalent). You don't need to use this cable with the Nano.
> 0 votes

---
Tags: arduino-pro-mini
---


# Question
Title: Programming standalone Atmega328p-PU with NE555N timer IC
I know I may sound a little idiotic to ask, but as I have seen in the internet that to program a standalone Atmel chip like that from of the Arduino's, you need 2 22pF ceramic capacitors and a 16mhz oscillator. As the oscillator is needed is clock the frequency of the chip, so a timer IC should work just fine, isn't it? or do I have wrong information?

# Answer
**No, you won't be able to build a 16 MHz clock signal using a 555 timer.** That's far beyond the 555 capabilities (see N.B.).

If you could squeeze out of the 555 a mere 1 MHz (which I seriously doubt), the clock stability and jitter would be so bad that it won't be usable but for simple sketches not requiring any timing accuracy. At that point, you would be far better off using the internal 1 MHz RC network of the ATmega328P as Majenko says, because you would at least save the 555 and its associated components.

Also, a 555-based clock would consume much more power than any of the alternatives already available to you (internal oscillator, external crystal...). Even the CMOS version.

My recommendation: **forget about it, it's not worth it**.

**NOTE BELOW:**

NE555N is a BJT version of the 555. BJTs suffer from what's called "storage time", a charge accumulation in the base that severely limits switching time. The NE555N datasheet states a storage time of about 10 microseconds (p.10), which limits the switching frequency to about 100 kHz.

TLC555 is a CMOS version of the 555. Because it uses FETs, its maximum switching frequency is much higher. The TLC555 datasheet (p.6) states that a typical value for the maximum switching frequency is 2.1 MHz (and at least \> 1.2 MHz).
> 5 votes

# Answer
Yes, you could use a 555. You can also go even simpler and use an RC network. Even simpler still is to use the 1MHz RC network built in to the chip.

The main drawback of these methods, and the 555 particularly, is that of stability. Using a crystal and capacitors you can get very accurate timing at high frequencies. Using a 555 you can get ballpark timing at low frequencies. Fine if all you want to do is blink an LED, but as soon as you need to do anything that requires good timing it all falls apart. That includes things like using the UART for which accurate timing is at the heart of its operation.

The internal oscillator is better in this respect since it can be calibrated using the OSCCAL register. However changes in ambient temperature can cause unacceptable drifting of the clock frequency.
> 4 votes

# Answer
The default configuration of these chips, as they come from the factory, is to use their internal 8 MHz RC oscillator downscaled at 1 MHz. So you **do not** need any extra oscillator to program them.

Once you program the chip the first time, *if* you configure it to use an external resonator/oscillator, then **you do need** to have that attached in order to *reprogram* the chip.

A 555 may be able to run the chip, but if you want to reprogram it, the programmer may not cope well with the extra-low frequency the chip would be running at.
> 4 votes

# Answer
It depends on how you're programming it.

If you're using a bootloader to accept programming commands via a serial connection then you will need to use the clock method specified by the fuses currently programmed, since the chip at that point will actually be running code programmed on it.

If you're using ISP to program the chip out-of-band then you can apply a clock source directly to the XTAL1 pin as shown in the "Serial Downloading" subsection of the "Memory Programming" section of the datasheet. In this case you will need to adhere to the timing information given at the end of the subsection.
> 3 votes

---
Tags: arduino-uno, timers, electronics, frequency, oscillator-clock
---


# Question
Title: Actual baud rate of UNO R3 Firmata protocol
Probably a silly question. But the Internet is confusing me.
The Firmata website says the default baud rate is 57600. But AFAIK, the baud rate set for UNO R3 is 9600(In Windows device manager, it say so). I'm making the Firmata client program and have to set the baud rate. I'm confused whether it's similar to the serial protocol or not.
\[Using the StandardFirmata sketch\]

# Answer
> 0 votes
The baud rate is whatever the program opening the port requests it to be. The stuff in the device manager is only the default used if nothing else is specified when the port is opened.

And the Firmata protocol just squirts bytes over serial. It's based upon the MIDI protocol, which is just serial.

---
Tags: arduino-uno, serial, baud-rate, firmata
---


# Question
Title: NodeMCU does not boot up when GPIO pin is high
I have a NodeMCU board connected to a door and there is a micro switch that makes one GPIO pin (GPIO15 - D8 in this specific case) go high when the door opens.

My problem is if I lose power while the door is opened, the GPIO15 is fed high at the next boot when power is restored. And it makes the board go to a not responding state. I have to boot it again while the door is closed (pin is low) to bring it back to work. I experienced this while flashing too. I cannot flash while this pin is high (while the door is open).

How can I fix this?

# Answer
> 10 votes
Certain pins of the ESP8266 perform special functions at bootup. GPIO15, when HIGH, makes the ESP8266 boot from an SD card.

You can read more about the special functions of the pins here.

The solution? Don't use GPIO 0, 2 or 15 for things that can affect the boot sequence.

---
Tags: pins, bootloader, nodemcu
---


title: Get Speed Using GPS Neo with TinyGPS++

text:
# Question
Title: Get Speed Using GPS Neo with TinyGPS++
I am trying to get the current speed of my car using the GPS Neo, but my code always returns that the speed from the GPS is invalid. The green led of the GPS Neo is blinking. What is the isValid() function? Below the code:

```
#include <EEPROM.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
//LOAD WIRE LIB
#include<Wire.h>
static const int RXPin = 10, TXPin = 9;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
//***************************************************************
int aux = 0;
int vel_prog = 20; //programed SPEED
float vel_atual;//  actual SPEED
int val_inc = 0;
int val_dec = 0;
int led0 = 2;//led pin
int led20 = 3;//led pin
int led60 = 4;//led pin
int led80 = 5;//led pin
int ledsinal = 6;//led pin
int buzzer = 7;//buzzer pin
int incrementa = 8;//button pin
//****************************************************************
void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  pinMode(incrementa, INPUT);
  pinMode(led0, OUTPUT);  // declare LED as output
  pinMode(led20, OUTPUT);  // declare LED as output
  pinMode(led60, OUTPUT);  // declare LED as output
  pinMode(led80, OUTPUT);  // declare LED as output
  pinMode(ledsinal, OUTPUT);  // declare LED as output
  pinMode(buzzer, OUTPUT);  // dbuzeer
  delay(10);
}

void loop()
{

  smartDelay(1000);
  val_inc = digitalRead(incrementa);  // read increment button
  if (val_inc == 1) {
   if (vel_prog > 80) {
      vel_prog = -20;
   }
      vel_prog = vel_prog + 20;
  }

  if (vel_prog == 0) {
    digitalWrite(led0,HIGH);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 20) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,HIGH);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 60) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,HIGH);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 80) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,HIGH);
  }

  if (gps.speed.isValid()){
  Serial.print(gps.speed.kmph());
  } else {
  Serial.print("*");
  }

 if (gps.speed.isValid()) {
  if (gps.speed.kmph() >= vel_prog && aux == 0) { //comparacao da velocidades
    digitalWrite(ledsinal, HIGH);  // turn LED OFF
    tone(buzzer, 2200);
    delay(5000);
    digitalWrite(ledsinal, LOW);  // turn LED OFF
    noTone(buzzer);
    aux = 1;
  }
}
}

static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

```

# Answer
> 0 votes
These lines of code will wreak havoc with reading the GPS data:

```
tone(buzzer, 2200);
delay(5000);
digitalWrite(ledsinal, LOW);  // turn LED OFF
noTone(buzzer);

```

The Arduino is "blocked" at these lines for seconds. During that time, the GPS keeps babbling and eventually overflows the input buffer. The next call to `smartDelay` only waits for 1 second, and it may not get a complete sentence.

Here is a NeoGPS version of your sketch that does not block:

```
#include <EEPROM.h>
#include <NMEAGPS.h>
#include <NeoSWSerial.h>
#include <Wire.h>

NMEAGPS gps;

static const int RXPin = 10, TXPin = 9;
static const uint32_t GPSBaud = 9600;
NeoSWSerial gpsPort(RXPin, TXPin);

//***************************************************************
int aux = 0;
int vel_prog = 20; //programed SPEED
float vel_atual;//  actual SPEED
int val_inc = 0;
int val_dec = 0;
int led0 = 2;//led pin
int led20 = 3;//led pin
int led60 = 4;//led pin
int led80 = 5;//led pin
int ledsinal = 6;//led pin
int buzzer = 7;//buzzer pin
bool buzzing = false;
uint32_t buzzTime;
int incrementa = 8;//button pin
//****************************************************************
void setup()
{
  Serial.begin(115200);
  gpsPort.begin(GPSBaud);
  pinMode(incrementa, INPUT);
  pinMode(led0, OUTPUT);  // declare LED as output
  pinMode(led20, OUTPUT);  // declare LED as output
  pinMode(led60, OUTPUT);  // declare LED as output
  pinMode(led80, OUTPUT);  // declare LED as output
  pinMode(ledsinal, OUTPUT);  // declare LED as output
  pinMode(buzzer, OUTPUT);  // dbuzeer
  delay(10);
}

void loop()
{
  // Check the buttons
  val_inc = digitalRead(incrementa);  // read increment button
  if (val_inc == 1) {
   if (vel_prog > 80) {
      vel_prog = -20;
   }
      vel_prog = vel_prog + 20;
  }

  if (vel_prog == 0) {
    digitalWrite(led0,HIGH);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 20) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,HIGH);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 60) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,HIGH);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 80) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,HIGH);
  }

  // Check the GPS
  while (gps.available( gpsPort )) {
    gps_fix fix = gps.read();

    if (fix.valid.speed) {

      if ((fix.speed_kph() >= vel_prog) && (aux == 0)) { //comparacao da velocidades
        digitalWrite(ledsinal, HIGH);  // turn LED OFF
        tone(buzzer, 2200);
        aux = 1;
        buzzing = true;
        buzzTime = millis();
      }

      Serial.print( fix.speed_kph() );
    } else {
      Serial.print( '*' );
    }
  }

  // Check the buzzer
  if (buzzing && (millis() - buzzTime > 5000)) {
    digitalWrite(ledsinal, LOW);  // turn LED OFF
    noTone(buzzer);
    aux = 0; // Need this?
    buzzing = false;
  }
}

```

Notice how it checks `millis()` every time through `loop` to see if the buzzer has been on for 5 seconds. It doesn't *block* for 5 seconds.

It only checks the speed when a new GPS fix arrives. This happens once per second, not every time through `loop`.

Your original version uses 11472 bytes of program space and 786 bytes of RAM. The NeoGPS version uses 10722 bytes of program space and 590 bytes of RAM, a significant savings.

NeoGPS is smaller, faster and more accurate than all other libraries. If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**.

The above sketch also uses my NeoSWSerial. It is much more efficient than SoftwareSerial. SoftwareSerial blocks interrupts for long periods of time, which can interfere with other parts of your sketch.

It would be even better to use AltSoftSerial on pins 8 & 9 (on an UNO).

---
Tags: arduino-nano, gps
---


title: Arduino State Machine code flow

text:
# Question
Title: Arduino State Machine code flow
New to FSM, can someone explain how the flow works? If I use a case scenario in a loop, how is an external change detected and brought back to the loop? Is all of the code/inputs, etc to be included within the case statements?

Still having a few problems. I have modified my code to include some of the suggestions. You can see that I added some print statements to allow me to monitor execution, but I can't get it to obey, such as print "trigger" when the PIR sensor is HIGH. Anyone available to explain my error(s)? I added a void check() just to bypass the keypad (not connected).

```
//////////////////////////// Initialize & Includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count = 0;
int switchPIN = 3; // alarm on test
char keypadPIN;
int z = 0;
int i = 0;
int waitTime = 5000;

//////////////////////////// Setup Keypad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// Setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);     // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW);   // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
  // Could make use of the interrupts by checking in the interrupt if the state is "Ready" and
  // then setting the state to "Alarm".
  Serial.println ("System Ready");

  keypadPIN = HIGH;
}

//////////////////////////// State Setup //////////////////////////
enum STATE {
  Ready, //system acknowledges trigger
  Unarmed, //system unarmed via keypad entry setting keypadPIN = LOW
  JustActivated, //PIR-triggered interrupt
  Alarm // confirm system unarmed then goto unarmed state else start alarm
};
STATE systemState = Unarmed;
long timeGettingArmed;

/////////////////////////// Trigger ///////////////////////////////
void trigger() {
  systemState = JustActivated;
}

//////////////////////////// State Machine //////////////////////////
void loop() {
  check ();
  switch (systemState) {Serial.println("switch");
    case Ready:
      if (PIR_SensorPin == HIGH) {Serial.println("PIR_Sensor");
        Serial.println("triggered");
        systemState = Alarm;
      } else if (keypadPIN == LOW) {
        systemState = Unarmed;
      }
      break;
    case Unarmed:
      if (keypadPIN == HIGH) {Serial.println("keypadPIN=HIGH");
        // Serial.println("Unarmed");
        timeGettingArmed = millis();Serial.println(timeGettingArmed);
         systemState = JustActivated;
      }
      break;
    case JustActivated:Serial.println("JustActivated");
      if (timeGettingArmed + waitTime < millis()) {
        Serial.println("Ready");
        systemState = Ready;
      }
      break;
    case Alarm:
      if (keypadPIN == LOW) {Serial.println("keypadPIN=LOW");
        systemState = Unarmed;
      } else {
        beep();
      }
      break;
  }
}

//////////////////////////// Alarm //////////////////////////
void beep() {
  Serial.println("at beep");
  // (sms.SendSMS("8656171435", "*** Motion Detected in Studio! ***"));
  Serial.println ("MOTION detected: SMS Sent");
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (Alarm_OutPin, LOW); delay (500);
    digitalWrite (LED_OutPin, HIGH); // delay (1000);
    Serial.println (alarm_count);
  }
  systemState = Ready;
}

void check() {
  if (switchPIN == HIGH) {
    keypadPIN = LOW; // Unarmed
  }
  else {
    keypadPIN = HIGH; // Ready/Armed
  }
}

```

# Answer
> 2 votes
### MCU State Flow

1. State ( Model )
2. User/Machine Output ( View )
3. User/Machine Interruption ( Events )
4. State Changers ( Controller )
5. *goto* 1.

Breakdown of how it works:

#1. **State**. You start with a known finite state, which is the overall mode of operation for that piece or pieces. For a `switch()`-driven machine, it's a number, typically named by an integer constant for better readability.

#2. **Output**. Based on the state, you make certain things happen. These adjustments can be done in the `switch()`, or in the `loop()` as they notice state changes. You can also write explicit sub-routines to call from the switch() to keep code tidy. You can *read* the state from any point in the program, even interrupts if needed.

#3. **Events/Interrupts**. Lying in wait, these parts spring into action when something happens that the program needs to know. Both human-origin (ex: button press) and machine-origin (ex: SD card error) fall into this group. They can set flags and publish notifications to the *controller* that something has happened, but they MUST NOT set the state directly. The last point cannot be under-emphasized. If you start "cheating" and updating state outside of the controller, you create another point of failure and another stop along the debug/enhancement tour.

#4. **State Changing `switch()` (Controller)**. This is where the actions meet the state. Only here should you change state to a new one, based on outside flags set by events. If your `switch()` is at the top of `loop()`, and you `return` in each `case`, you can call `loop()` from other points in the code to fire a state change immediately, but i like to name it in a `void()` and call it from `loop()`. The switch code should be lightweight and never use `delay()`. Lastly, most of the time a `case` does nothing, because no outside condition has changed that merits reaction, and it `break`s or `return`s right there. When something important does change, the code below that early-exit conditional performs as a state change event handler.

# Why bother

It can be a bit much at first, and seem like it's not worth the 5-10 mins up-front to name constants and write out all the `switch` bolierplate. I'm a lazy coder, and I still use this because it saves me a ton of time at every point in time besides those first 10 minutes.

Since things can only change in one place, you know exactly where to debug. It's simple to dump the outside values a `case` examines to the serial (remove before "launch"), rather than finding that chunk of code in the ether. Doing it all in one place makes it trivial to log when and what with each state change. With minor additional code you can even *undo* state changes, which can be a boon for users. Such actions are not risky because every part of the outside code knows what to do.

It breaks up tedious chains of semi-related action into independent pieces. You won't need lots of nested `if()`s if you follow the above guidelines. Even if you're not a long-time developer, simply following this pattern and slopping/pasting all the other code together, your program will be better in the end and faster and easier to build along the way.

---
Tags: arduino-uno
---


title: Strings becoming empty (Arduino Uno)

text:
# Question
Title: Strings becoming empty (Arduino Uno)
I'm running a modifed code on Arduino Uno + WiFi shield (updated), and I have seen strange behaviors with `String` ; here is my code, the goal is to parse a HTML request to know which page was requested :

```
String line = client.readStringUntil("\n");
Serial.print("Line : [");
Serial.print(line);
Serial.println("]");

String cmd = line.substring(0, 3);
Serial.print("Command : [");
Serial.print(cmd);
Serial.print("]");

```

My problem comes from what appears in the console :

```
Line : [GET / HTTP/1.1
Host: 192.168.43.200
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Ac]
Command : []

```

I was expecting the `cmd` variable to contain `GET`, and I do not understand why it contains nothing.

I suspect this behavior comes from the lack of RAM (compiler says there are only 670 bytes available for local variables), but if it's the case, I do not know how to solve it, as I'm pretty inexperienced in C++ and I need to store a String containing the values that are sent as a reply to the HTTP request.

PS. I'm also wondering why the `client.readStringUntil("\n")` method sends the full request instead of only the first line.

# Answer
> 0 votes
In general, you don't want to be copying strings around when you don't have to because it's inefficient. For parsing things like command lines, you can often just work with the existing `String` (or better yet, `string`; see Majenko's tutorial).

In this particular example, you have a string and you want to know if it's an HTTP `GET` command. That's simple enough; the first four characters will be `GET` (we check the space on the end because we don't want to interpret `GETMORE /foo` as a `GET` command).

This is extremely easy:

```
String s = "GET /foo/bar";

if (s.startsWith("GET "))
    Serial.println("GET command");
else
    Serial.println("Not GET command");

```

For stuff in the middle of a string you obviously can't use `startsWith`, but there are other functions that can help. For example, once you know it's a GET command, you know that the URL starts at position 4 (the 5th character, since counting starts at 0). You could test to see if it starts with '/foo' with

```
if (s.indexOf("/foo") == 4)
    Serial.println("Path starts with /foo.");
else
    Serial.println("Path doesn't start with /foo.");

```

That said, while this kind of thing is workable for quick tests, in the long run you probably want to move towards parsing in C in the way that Majenko's tutorial above talks about, and likely parsing as much as possible as you do the reading (rather than reading everything into memory and then parsing it) due to HTTP requests being relatively large compared to the memory you have to handle them.

---
Tags: string, memory
---


title: Increasing ADC resolution

text:
# Question
Title: Increasing ADC resolution
At this moment I am using oversampling to increase my analogread resolution. This in combination with increasing the frequency of the ADC. Is someone able to take a look at it?

```
#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int value[100];   // variable to store the value coming from the sensor
int i=0;

void setup()
{
  Serial.begin(9600) ;
 int start ;
 int i ;

#if FASTADC
 // set prescale to 16 (1MHz)
 sbi(ADCSRA,ADPS2) ;
 cbi(ADCSRA,ADPS1) ;
 cbi(ADCSRA,ADPS0) ;
#endif
}

void loop()
  {
  for (i=0;i<100;i++)
  {
   value[i]=Read12bit(0);
  }
  for (i=0;i<100;i++)
  {
   Serial.println(value[i]);
  }
  Serial.println();//Some blanks between values
  Serial.println();
  delay(5000);

}

int Read12bit(uint8_t pin){
      int Result = 0;
      analogRead(pin);                      //Switch ADC
      for(int i = 0;i < 16; i++) {          //Read 16 times
        Result = Result + analogRead(pin);  //Sum results
      }
      Result = (int)Result/4;               //Divide by 4 for 12 bit value
      return(Result);
    }

```

At this moment the resolution of this oversampled analogread is 12-bits. With a little calculation the time to read will take 0,208milliseconds. If I want to increase my resolution more i.e. 13-bit. This will take the measurement 0,832 milliseconds. This seems rather big, so my question is can I do this in another way?

EDIT **Why?** *I am trying to position multiple linear actuator using multiple arduino's connected via CAN-bus (the arduino's will not communicate with eachother unless an error occures) THe positioning has to be precise (\<0.1mm on a 30 cm rod).*

**Why is 12 or 13 bit accuracy and/or resolution needed?**

*12 is probably enough. But I just like to find out the boundaries of the equipment :)*

**What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?**

Probably none 13-bit resolution is probably too high for my application anyways.

**Other reason why I like a higher resolution** First couple of voltages I cannot use. My sensor gives a 4 to 20mA signal which i convert with resistor to ground.

# Answer
Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.

I often use the MCP3553 which allows 60sps at 22-bit.
> 4 votes

# Answer
This is in response to the question.
It is an answer to the extent that it says that

* The current method may not work (several reasons given),
* There may be better ways to do it, and
* Is it necessary?

Addressing these points, or knowing that they have been addressed, is an essential part of arriving at a good solution .

If we knew the desired conversion time and actual desired resolution it would allow better answers.
If we knew what you were trying to do it might help immensely.
ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified.

Apart from the statistical sampling considerations that you are addressing, you cannot usually extend ADC bits indefinitely by oversampling with any great expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold and acquisition gating and more work.
As you try to squeeze more bits out of the ADC the assumptions become less likely to be consistently valid.

Also, implementation of the analog input circuitry initially becomes important and then immensely important as bits of ADC resolution increase (whether achieved by over sampling or other means).

12 bits = 0.0244% per step (as you know)
or 1.22 mV steps in a 5V reference system
or 0.81 mV/bit in a 3.3V reference system.
Getting your overall system working to that level of accuracy is possible but usually not achieved.
Any reference you are using will be natively much less accurate than that and those sort of accuracies will require calibration both initially and possibly ongoingly.
Ratiometric systems, where eg the excitation voltage of a bridge also serves as a reference, allow reference accuracy to notionally be perfect (as readings and excitation are the same and move together.
However, ensuring that the voltage at the controllers Aref pin wrt controller Agnd, and the bridge's excitation pin wrt the bridge's ground input are the same within usefully under 1.22 mV in a 5V 12 bit system (0.6 mV in a 13 bit system, and that the bridge and controller grounds are the same within say a few hundred uV, are an obvious necessity if the 13 bits of resolution are to be meaningful - but unlikely to be achieved without the most exquisite attention to both design & implementation. (Ask me how I know :-).)

Generally, it will be much easier to obtain and maintain ADC resolutions of as many bits as are needed by the use of purpose designed conversion ICs operating as close to the signal source as is reasonably possible. (Or using instrumentation amplifiers to acquire the signals and reliably "convey" them elsewhere.) Knowing desired conversion times and resolutions is a necessary first step.

**BUT**

Why?
Why is 12 or 13 bit accuracy and/or resolution needed?
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Such requirements - and much more accurate again, certainly do exist.
But knowing what the actual application is may help with decisions of how to meet it.
> 3 votes

# Answer
In my tests, the Arduino ADC starts to suffer from accuracy issues when you push it to 500kHz for oversampling, but 250kHz does not suffer from this problem. Also you need some kind of dither/noise, or the oversampling does not really work. I found that pulsing a digital pin with a resistor connected to ground gave me enough noise for the techinque:

https://edwardmallon.wordpress.com/2017/02/27/enhancing-arduinos-adc-resolution-by-dithering-oversampling/
> 3 votes

# Answer
you squeezing run time, I wonder, how much time you may save, if instead of looping to measure you do 16 times += and \>\>2 instead /4 an another optimization to make an own analog read function, it would be pretty simple based on original, so in additional you save time to call read function 16 times with all CPU overhead for each call.

lastly, in your own read function run the ADC in free run mode and accumulate a significant amount of data samples for oversampling.
> 0 votes

---
Tags: analogread
---


# Question
Title: Control Android Camera using Arduino over Bluetooth
I want to Control Android Mobile Camera shutter using Arduino over Bluetooth. So i can click photos using arduino.

I have HC-05 Bluetooth Module and **Arduino Nano/Arduino leonardo**.

The Connection as shown in figure.

The Android mobile successfully connected to Bluetooth Module but i am not found any code to control camera or any button on android mobile.

# Answer
I am trying out Camera Pro. It allows shutter control on Android over Bluetooth. I just got an Uno R3 and and HC-05 so I have not wired it up to try it.

There are example sketch and detailed docs here.
> 1 votes

---
Tags: bluetooth, arduino-nano, wireless, android, hc-05
---


# Question
Title: How to change this function in to a non-blocking function?
How do I modify the getTheNumber() function to satisfy the statement below?? " This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency."

Here is the code:

```
int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            break;
        }
    }
    return atoi(buffer);
    }

```

# Answer
I have a post about doing serial input without blocking.

Example code:

```
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

```
> 2 votes

# Answer
1. make buffer\[\] and i static.
2. get rid of the while() loop.

Like this:

```
int getTheNumber()
{
    static char buffer[4];
    static int i=0;
    // Input up to 3 numbers until we find a * or #
    char key = keypad.getKey();

    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
            return(-1)
        }
        // If it's a * or #, end
    else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            i=0;
            return atoi(buffer);
        }
}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: What are the unused pins in an Arduino L293D motor shield?
What are the unused pins in an Arduino L293D motor shield? I want to connect the shield using wires instead of directly mounting on top of the Arduino board.

# Answer
> 4 votes
Check out this Link. Here, you can find this explanation in Code. I hope it will helpful for you.

```
Pin usage with the Motorshield
---------------------------------------
Analog pins: not used at all...
A0 ... A5 are still available...
They all can also be used as digital pins.
Also, I2C (A4 = SDA and A5 = SCL) can be used.
These pins have a breadboard area on the shield.
Digital pins: used: 3,4,5,6,7,8,9,10,11,12
Pin 9 and 10 are only used for the servo motors.
Already in use: 0 (RX) and 1 (TX).
Unused: 2,13
Pin 2 has an soldering hole on the board, easy to connect a wire.
Pin 13 is also connected to the system led.
I2C is possible, but SPI is not possible since those pins are used.

```

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


title: Get when a button close the circuit

text:
# Question
Title: Get when a button close the circuit
That seems to be a bit stupid to myself but I can't figure out to get to know when my button is pushed (closed) or released (open).

You must know that this not just a simple push button. Actually it is more of a complex button with multiples output (Y, G, 0V, COM, NO, NC, HORM, 12V). With a multimeter i've been able to locale witch output are closed when the button is pressed. These are HORM (that is the name for two outputs -?!-) and on the other side COM and NO.

I've tried to plug that to my arduino Mega, on PIN 7, and getting the value with Digital.Read. Tho when i try to display it on the Serial, it doesn't work and return an error. (It did the same for HORM and COM/NO)

I also noticed something strange. When the button is pressed, Arduino seems to notice it because my "ON" led turns off and then turns back on. Like if the arduino was crashing. The 13th pin LED stay HIGH after the arduino goes back on.

Please, have a look at my code.

```
int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){
  val = digitalRead(inPin);  // read input value
  Serial.write(val);
  if (val == HIGH) {         // check if the input is HIGH (button released)
    digitalWrite(ledPin, LOW);  // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);  // turn LED ON
  }

  delay(1000);
}

```

Do you guys have any advice ?

Thank you very much in advance.

Also please have a look at the circuit. The only difference is that instead of having this kind of simple pushbutton, i've got my NO and COM plugged the same way.

# Answer
> 1 votes
Ok then.

I just tried that again and it simply seems that the wiring shown on the tutorial is not good at all. I made another wiring that worked exactly fine.

---
Tags: arduino-mega, button, input, atmega2560
---


# Question
Title: Managing 2 ultrasonic sensors without blocking the other
I have an ultrasonic distance sensor. When this sensor is measuring a distance below 25 cm, a second sensor has to be measuring a distance below 5 cm. If not, there should be a one minute timespan, after which a speaker should make noise until the second sensor is measuring a distance below 5 cm.

I am having trouble with this. The first sensor has a lot of code it should be running as well, so using a while-loop to wait out one minute for the other sensor and creating noise after that isn't a possibility.

How do I go about this dilemma? I read into interrupts in Arduino but unfortunately I don't know how I'd make this work.

# Answer
> 5 votes
I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible.

Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum (link), credits to "cattledog".

```
volatile unsigned long LastPulseTimeA;
volatile unsigned long LastPulseTimeB;
int durationA;
int durationB;
//unsigned long startTime;
#define trigPinA 7
#define echoPinA 2
#define trigPinB 8
#define echoPinB 3
void setup() {
  Serial.begin (9600);
  pinMode(trigPinA, OUTPUT);
  pinMode(echoPinA, INPUT);
   pinMode(trigPinB, OUTPUT);
  pinMode(echoPinB, INPUT);
attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE);  // Pin 2 interrupt on any change
attachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE);  // Pin3 interrupt on any change
}
void loop(){
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPinA, HIGH);
  digitalWrite(trigPinB, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  Serial.print("Sensor A  ");
  Serial.print(LastPulseTimeA);
  Serial.print('\t');
  Serial.print((LastPulseTimeA/2) / 29.1,1);
  Serial.println("cm");
  Serial.print("Sensor B  ");
  Serial.print(LastPulseTimeB);
  Serial.print('\t');
  Serial.print((LastPulseTimeB/2) / 29.1,1);
  Serial.println("cm");

  delay(1000);
}
void EchoPinA_ISR() {
    static unsigned long startTimeA;

    if (digitalRead(echoPinA)) // Gone HIGH
        startTimeA = micros();
    else  // Gone LOW
        LastPulseTimeA = micros() - startTimeA;
}
void EchoPinB_ISR() {
    static unsigned long startTimeB;

    if (digitalRead(echoPinB)) // Gone HIGH
        startTimeB = micros();
    else  // Gone LOW
        LastPulseTimeB = micros() - startTimeB;
}

```

# Answer
> 1 votes
fairly simple:

```
  if (time_is_up_for_sensor1()) read_sensor1(); //read sensor1 if time is up
  if (time_is_up_for_sensor2()) read_sensor2(); //read sensor2 if time is up

```

in time\_is\_up\_for\_sensor1/2(), update for the next round of reading:

```
int time_is_up_for_sensor1(void) {
  static uint32_t millis_next = 0; //next millis
  if (millis() >= millis_next) {  //time is up for sensor1
    millis_next += INTERVAL_SENSOR1; //advance to the next measurement time
    return 1;  //needs to read sensor1
  } else return 0;
}

```

similarly for sensor2

---
Tags: arduino-uno, sensors, interrupt
---


# Question
Title: Matching the blink of an LED to midi music
I have a function that plays a song and lights an LED corresponding to the note that is being played. when the same note is played consecutively(i.e E in bar 6) instead of the LED turning on and off for each time the note is played the LED appears to remain lit. how do i get the LED to go no and off for these notes to better synchronize with the music being played? The delay of 414 is being used as quarter notes etc.

```
void songlist (int song){
if (song==1){
songpage=1;
playpage=0;
mainpage=0;
tonepage=0;
lcd.clear();
lcd.setCursor(4,0);
lcd.print("ListeningTo:");// Print a message to the LCD.
lcd.setCursor(1, 1);
lcd.print(menuP1);
//Plays Mary Had a Little Lamb
//Bar 1
 noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E,100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3C, 100); //Quarter note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOff(0x90, 0x3C, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 2
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Half note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(828);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

//Bar 3
noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Half note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(828);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 4
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x43, 100); //Quarter note: G
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x43, 0);

noteOn(0x90, 0x43, 100); //Half note: G
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[4], LOW);
delay(828);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x43, 0);

//Bar5
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3C, 100); //Quarter note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOff(0x90, 0x3C, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 6
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

//Bar 7
noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 8
noteOn(0x90, 0x3C, 100); //Whole note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(1656);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOn(0x90, 0x3C, 0x00); //"Silent" note that makes sure the note stops playing.
delay(2000);
//End song
}
}

```

# Answer
> 0 votes
First, write a helper function so that you do not have so much repeated code, and call it for each note:

```
void playNote(int midi, int row, int col, int len)
{
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    noteOn(0x90, midi, 0x00);
}

...
//Bar 1
playNote(0x40, 3, 1, 414); //Quarter note: E
playNote(0x3e, 2, 4, 414); //Quarter note: D
...

```

Then, change it so that the note-off command and the LED switching can be done at different times:

```
void playNote(int midi, int row, int col, int len, bool short_led = false)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOn(0x90, midi, 0x00);
}

```

---
Tags: arduino-mega, programming, led, midi
---


# Question
Title: Strange power comsuption into sleep mode
I've finished my project and now I'm measuring the current but there is something wrong. I'm using an Arduino Pro Mini board and the LowPower library but the consumption is about **3.5 - 5 mA** and not less than 500 uA (the board remains into sleep mode almost all the time).

When I began to work with the board its LED was removed but I think that this work was not made correctly. How can I check that LED was removed correctly?

Thanks to all.

**EDIT1:** **The strange power consumption is not associated with board's LED.**

**EDIT2:** @Gerben has suggested me to review the state of SPI pins connected to the board. I use in this project a SD card module and GSM/GPRS module but the guilty of this excessive power consumption is the first. Then I've disconnected all SD card module's pins and then I get about **60 uA**, so the problem is on those pins but I can't reduce the power consumption. SD card module pins are 10,11,12 and 13 so I've used statements like `digitalWrite(10, LOW)`, `digitalWrite(11, LOW)` and so on after reading/writing on the SD card but it is useless.

**EDIT3:** I've decided to upload a representation of my project using Fritzing. The external modules are not identical but they contain the same pins.

General view of the circuit:.

Detail of the connections:

I use these external components:

In my project there are some important details:

* GPRS module is powered individually. The other battery is dedicated to power on the Arduino board and the SD card module.
* Batteries are 6v.
* Transistors base are controlled by 2 and 3 digital pins respectively.
* The 8 and 9 pins of the Arduino board act like RX and TX pins using `AltSofSerial.h` library.

# Answer
**SOLUTION** \[by OP\]

My problem was that the SD card module was consuming when it was controlled by a transistor and my Arduino board was into the sleep mode. So I wrote into the `void setup()` the `digitalWrite(PIN, HIGH)` statements where PIN represents all pins connected to the board that belong to the SD card module (DI, DO, CS, and CK pins), to enable the internal resistor of that pins. Then, I checked the power consumption and I reached less than 100 uA.
> 1 votes

# Answer
If you physically removed the LED make sure the pads for it aren't shorted together by old solder. If they aren't then you removed it correctly.

However: 5mA may be a perfectly reasonable current consumption for your project. Without seeing a full schematic and analysing your code it's impossible to say what kind of current you would expect to see.
> 0 votes

---
Tags: power, led, arduino-pro-mini
---


# Question
Title: Why is one part of my code being executed over the part before it?
The following code doesn't behave the way I would like it to. Inside the loop function im measuring the distance in front of the robot and if it is less than 15cm than the robot should move back and if it is less than 15cm on the left then move forward. When i run the program however only the left side is being checked and acted upon whilst the the if statement about the front and moving back is not doing anything. Something to note also is that when i swap the if statements and put the front checking ahead of the left checking it works but the left side is no longer being checked. Why is it that the if statement block in front is being executed over the previous one?

```
     void loop(){

     if(front.calculateDistance() < 15){
     MoveBack(200);
     }else{
      stopMoving();
     }

      if(left.calculateDistance() < 15){
     MoveForward(200);
     }else{
      stopMoving();
     }
   }

```

This is what the move methods do (move back and stopmoving just change input directions):

```
void MoveForward(int rspeed) {
 // turn on motor A
 digitalWrite(in1, HIGH);
 digitalWrite(in2, LOW);
 analogWrite(enA, rspeed);
 // turn on motor B
 digitalWrite(in3, HIGH);
 digitalWrite(in4, LOW);
 analogWrite(enB, rspeed);
}

```

# Answer
> 4 votes
The problem is with your logic. You are saying:

1. If it's too close in front then move backwards
2. Otherwise stop all movement
3. If it's too close on the left then move forwards
4. **Otherwise stop all movement**.

That means that if it's too close in front, but not too close on the left, then it will think about moving backwards, but then immediately stop because it's not too close on the left.

You need to think more about the whole space at once, not just one individual direction. For instance, what do you do if it's too close in front *and* too close on the left? At the moment you'll crash into whatever is in front.

So you should be thinking about four conditions:

1. Too close in front AND too close on the left
2. Too close in front BUT NOT too close on the left
3. NOT too close in front BUT too close on the left
4. NOT too close in front AND NOT too close on the left.

Then you can choose the right action to perform.

If your specific setup means that it can never be too close in front at the same time as being too close on the left you can collapse it into a simpler form:

1. **IF** it's too close in front then move backwards
2. **ELSE IF** it's too close on the left then move forwards
3. **ELSE** stop all movement.

---
Tags: arduino-mega, programming, motor
---


# Question
Title: How to control low power devices when implementing Low Power Mode strategy?
As part of implementing Low Power Mode, I wish to control power to attached devices, such as the HC12 transmitter/receiver. I've read of the usage of MOSFETs to control motors and lighting systems, but don't understand the applicability of such implementations to control something like an HC12, which consumes approximately 200ma. Should I be using MOSFET and, if so which one? Else, what is a better solution? The circuit I am now working on is essentially a PRO Micro, an HC12, and a small led, though I will later add a camera module, approx. 100ma.

# Answer
> 2 votes
Yes, MOSFETs are what you want.

The temptation is to just insert any old logic-level N-channel MOSFET in the ground connection to the device like you would when driving a relay, etc. However that method is fraught with danger. You get such issues as ground-level offsets (where ground isn't actually ground but some mV above ground) which can result in logic level mismatch problems. You get the possibility of power trying to make its way to ground through the device's IO pins and your MCU, etc.

So it is best to instead use a P-channel MOSFET to switch the positive power rail to the device. If the voltage you are switching is the same as the voltage you are doing the switching with (i.e., you are switching 5V using a 5V-level GPIO pin such as on an Arduino) then that is really all you need. However if the voltage you want to switch is higher then you will need to switch the P-channel MOSFET with an N-channel MOSFET, or an NPN BJT.

Here's two schemes:

simulate this circuit – Schematic created using CircuitLab

In the left schematic M1 is kept off by R2, and pulling the control GPIO low it turns M1 on allowing the current to flow.

In the right schematic M1 is kept off by R2 in the same way, but M2, when turned on by the GPIO being driven HIGH. R3 keeps M2 off while the MCU is not ready to drive the GPIO pin yet (in the bootloader, etc).

One thing to remember when switching the power off on either schematic is to first set all the GPIO pins that communicate directly with the device to INPUT mode. That will prevent them trying to power the target device through the IO pins (which will typically have ESD diodes that would feed current to Vcc).

All MOSFETs should be logic level (except M1 in the right schematic which can have a higher threshold depending on the voltage you are switching - best to keep it all logic level though as a rule).

---
Tags: power
---


title: Executing machine code at runtime Uno

text:
# Question
Title: Executing machine code at runtime Uno
I want to create a small single threaded os for my arduino.The first thing I want to do is to allow my arduino to read a section from flash/eeprom and execute it. I have some question regarding the memory. The microcontroller is executing one command at a time from..where? Does it directly acces the flash containing the code and take every command at a time?(that would be slow) Or does it first load the entire program into sram?(also wouldn't make sense because sram is 2k while flash is 32k). Either way,if I can find in sram /flash my code( or the header to some void) then i could jump there.Am i wrong?Is it possible(to do such os)?

Something like this:

```
uint16_t addr=0x1234;
void (*function)(void)=addr;
function();

```

(or maybe with some avr like assembly code?)

# Answer
> 7 votes
> The microcontroller is executing one command at a time from..where?

Flash memory directly. The AVR core can *only* execute instructions from Flash memory. It uses a two-bus system known as Harvard Architecture, where the Instruction Bus is connected to Flash and is used to execute instructions, and the Data Bus is connected to SRAM, EEPROM, all the peripherals, GPIO pins, etc.

It is possible to jump to any location in memory in a similar way as you have depicted, but in order to know where you first need to know the functions you want to call. You can get the address of any function and assign it to a pointer, and then call that pointer as a function, but what would that achieve? You may as well just call the function directly and save time. Unless you want to store the addresses of those functions in an array or something to maybe associate them with a command to trigger the execution of that function. In which case you don't need anything "fancy", just pointers to the functions you want to use.

---
Tags: arduino-uno, flash, sram, memory
---


title: SIM800L change default baud rate

text:
# Question
Title: SIM800L change default baud rate
I am using an ATmega328P with internal clock (8 MHz) with a SIM800L module. The default baud rate of the SIM800L is 115,200 baud and I can't make them talk to each other correctly. Although I was able to make them talk very easily at a baud rate of 9600 baud. But now, with a new SIM800L I can't.

Question:

How to change the default baud rate of a SIM800L? Is it possible to run an ATmega328P at a baud rate of 115,200 baud?

Thanks in advance!

EDIT:

I know that I can run atmega328p at baud rate of 115200 with different crystal, but is it possible to it using internal crystal.

# Answer
> 2 votes
As you say, SIM800L default baud rate is 115200. So, you have to set that baud rate on arduino side. And yes, it is possible to run an ATmega328P at a baud rate of 115200 baud.

You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.

```
#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(115200);      // Set your buad rate
}

```

And you can also do without this library.

```
void setup()
{
  Serial.begin(115200);        // Set your baud rate
}

```

# Answer
> 2 votes
According to Adafruit's pdf specsheet *SIM800+Series\_Serial+Port\_Application+Note\_V1.01.pdf*, the SIM800 is set up to auto-baud when it starts out:

> SIM800 series is designed in autobauding mode by default. Autobauding allows SIM800 series to automatically detect the baud rate of the host device. In application, host device must to synchronize the baud rate with SIM800 series. Host device must firstly send characters "AT" or "at" to synchronize the baud rate. It is recommended to send "AT" until host device receives the "OK" response, which means host device and SIM800 series are correctly synchronized. Once the baud rate is synchronized, it is suggested to use AT command "AT+IPR" to set SIM800 series baud rate according the host baud rate. ...

So, you might arrange your software to keep trying at 9600 bps. If you get an ok connection at that rate, you can either keep using it or shift to a higher frequency via "AT+IPR". \[I haven't read the spec sheet enough to know whether that default autobauding is always on, or might be turned off somehow.\]

As serial-data bps goes up, required clock accuracy becomes tighter. Where a couple of percent error may be ok at 9600 bps, under a percent probably is needed at 115200 bps.

On several boards I've measured RC oscillator frequency errors of about 2%, which according to question How critical are UART frequencies? might or might not be good enough to allow high-speed serial communications.

If you can measure your ATmega328P's RC oscillator frequency, you can then apply a correction factor at startup. In the spec sheet (eg Atmel-8271J-AVR-ATmega-Datasheet\_11/2015), see §9.12.1, *OSCCAL – Oscillator Calibration Register*.

Your program can start out with the RC oscillator using the factory-set value, and then can load your own calibration value into the Oscillator Calibration Register to shift RC frequency as needed to make the board work ok for 115200 bps serial data. Or, you can overwrite (in EEPROM fuse or signature area) the factory-set value with your own number.

Figure 32-37, *ATmega48PA: Calibrated 8MHz RC Oscillator Frequency vs. OSCCAL Value*, shows typical frequencies for various Oscillator Calibration Register values. It is possible to tune clock frequency close enough that serial communications should work ok.

High-range byte values 144 through 160 typically move frequency from around 7.4 MHz to 8 MHz (at 85℃). In this range, each count shifts clock frequency by about 0.5%. See the figure for details. For example, if value 158 gives an RC frequency of about 7820 KHz, then value 159 might raise the RC frequency to about 7860 KHz.

Low-range entries 96 through 112 move frequency from around 7.5 MHz to 8.5 MHz. This overlap makes it necessary to try both low-range and high-range values when looking for the best Calibration Register value.

Note, there are inexpensive cymometers (frequency counters) on ebay, which can measure oscillator frequencies accurately enough to enable the calibration suggested above.

# Answer
> 2 votes
Well I do not think that the default baud rate is 115200. The default setting is autobaud which does not support 115200 baudrate. From the datasheet.

You can change it with the already mentioned `AT+IPR` command. From the AT manual you can also check that the default setting is autobaud, and also the selectable baud rates.

> Note: User can use AT command “AT+IPR=x” to set a fixed baud rate and the setting will be saved to non-volatile flash memory automatically.

If you use 57600 you will probably alright and you do not even have to change the baud rate settings as this value is supported.

# Answer
> 2 votes
You can change the baud rate to 9600 on the SIM800L with the command:

```
AT+IPR=9600

```

Then to save this (to last between boot cycles), give the command:

```
AT&W

```

To see the saved settings, give the following command:

```
AT&V

```

# Answer
> 0 votes
From what I have read so far, the problem is that there is no good divisor from an 8 MHz oscillator to get a within-spec baud rate above 57,600. Using the internal oscillator is also susceptible to variation with temperature, so that appears to be bad solution as well in many applications. The problem being that it may work on one MPU, but not with the next one.

As far as I can tell, the best solution is to use a 7.372800 MHz oscillator. This results in the processor running a bit slower, but it also results in the baud rate divisors being spot-on for almost all the standard and popular baud rates, meaning you should be able to run to at least 921,000 baud.

If anyone has a better solution, I would love to hear it, as I am dealing with a similar issue in something I intend to take into production that will be in a variety of environments.

---
Tags: softwareserial, atmega328
---


# Question
Title: Program crashes when I use Serial.println()?
I'm working with a fuzzy logic controller with Arduino, I'm trying to emulate an AC by entering inputs \[temperature and humidity\] using two potentiometers and the output is the AC power.

This is the basic part of the program, every thing is good, I can print the values of Temp and HU. But when I try to print the value of the Power, nothing happens, and the serial monitor displays nothing. By trial and error, I can see that `Serial.println` with power or any variable related to power crashes the program. What may be the reason?

```
    void loop()
{
    // Read Input: Temperature
    ttemp = analogRead(temp);

    Serial.println("the analoge Tempreture is ");
    Serial.println (ttemp);

    ttemp = map(ttemp, 0, 1023, 5, 65);
    ttemp = constrain(ttemp, 5, 65);

    Serial.println("the actual Tempreture is ");
    Serial.println (ttemp);
    Serial.println("-------------------------");
    delay(100);

    g_fisInput[0] = ttemp;

    // Read Input: Humidity
    hhu = analogRead(hu);
    Serial.println("the analoge Humidity is ");
    Serial.println (hhu);

    hhu = map(hhu, 0, 1023, 16, 100);
    hhu = constrain(hhu, 16, 100);

    Serial.println("the actual Humidity is ");
    Serial.println (hhu);
    Serial.println("-----------------------");
    delay(100);
    g_fisInput[1] = hhu;

    g_fisOutput[0] = 0;

    fis_evaluate();

    // Set output vlaue: Power
    int ppower1 = g_fisOutput[0];
   // Serial.println("the actual Power is ");
   // Serial.println (ppower1);
    ppower = map(ppower1,100,3000,0,255);
    ppower = constrain (ppower, 0,255);
    analogWrite(power , ppower);

   // Serial.println("the analoge Tempreture is ");
    //Serial.println (ppower);
   // Serial.println("--------------------------");

}

```

# Answer
> 1 votes
You should have provided your full Arduino code. Without setup() part of Arduino code, we can not exactly tell what might be wrong. Please provide it and I'll revise my answer as well.

Check if you have this code in your setup() function:

```
Serial.begin(9600);

```

9600 is baud rate and it could be any other supported baud rate(you can see those by opening a Serial monitor and clicking on 9600 baud rate on bottom right edge).

Related to to comments above, from experience and it can be easily "counted", RAM shouldn't be a problem in such short code.

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


title: De-Auth "attacks" using Arduino?

text:
# Question
Title: De-Auth "attacks" using Arduino?
I'm trying to use my Arduino and an ESP8266 to spam De-Auth "attacks". I am quoting attacks because I do not plan on using this for malicious or destructive purposes. I've heard that the ESP8266 supports monitor mode, but I haven't found any information about using it to spam De-Auth packets. I want to do something similar to the mdk3 command in Linux (mdk3 d).

If you need me to clarify anything, please just ask.

Thanks in advance!

# Answer
> 0 votes
If you can transmit raw 802.11, take a look at the code for aircrack-ng, specifically aireplay-ng.c - this software is known to work on arm boards.

# Answer
> 0 votes
Check this GitHub repo, could be what you are looking for: https://github.com/spacehuhn/esp8266\_deauther

---
Tags: arduino-uno, esp8266, arduino-micro
---


# Question
Title: what pins are attached to ethernet shield SD card?
I have ARDUINO ETH SHIELD 06 - Rev 03. https://www.adafruit.com/product/201 what pins are attached to Ethernet shield SD card?

# Answer
> 1 votes
Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card.

---
Tags: shields, ethernet
---