# Question
Title: How to start a block of code after a certain time?
I'm using a ATMega328P-PU on a breadboard as an arduino. How do you start a code after say 20 seconds have elapsed since startup? Example code:-

```
if(condition)
{
     //Start sending morse code!
}

```

My current code uses `millis()` and fails miserably. The speaker does not get activated. I'm using the standard circuit mentioned at the Arduino website My current code:-

```
time = millis();
  if(time>=20000)
      txEnable=true;
      val = analogRead(analogPin);
  if(val!=0)
  {
    standby=false;

  }
  else
  standby=true;
  if(txEnable==true && standby==true)
 {

  if(!callsignSender->continueSending())
    {
        callsignSender->startSending();
    }

 }

```

# Answer
The following bare-minimum code will switch pin 13 to high after 20 seconds:

```
void setup() {
  // assuming pin 13 has a LED connected (as on most Arduino boards)
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW); // would also work without this line
}

void loop() {
  unsigned long time = millis();
  if (time >= 20000) {
    digitalWrite(13, HIGH);   // set the LED on
  }
}

```

Try if this works for you, i.e. if a LED connected to that pin will light up 20 seconds after reboot.

If not you will need to find the problem: Is your ATmega running at the correct speed? Is your code executed at all? Are the peripherals working?
> 1 votes

---
Tags: arduino-uno, time, millis
---


# Question
Title: Storing in a global variable using inline assembly
What I'm trying to do is pretty basic: I have a global variable and I'm trying to store some value in it (specifically, the SP\_H and SP\_L values).

The variable is an array of structs and I'm trying to access one of those structs.

This is what I am doing:

```
typedef struct_t { uint8_t sp_h, sp_l; } struct_t;

struct_t arr[MAX_STRUCTS];

void some_inline_assembly_function()
{
  volatile asm(

  // Determine where to store the new SP_H and SP_L register

  "lds r26, ???                \n\t" // <-- How do I store the address
                                            of arr[0].sp_h or arr[0].sp_l
                                            in the X registers (r26,27)
  "lds r27, ???                \n\t"

  // This part stores the stack pointer low and high byte indirectly
     using the X registers (r26,27), which is what I want.

  "in    r0, __SP_L__          \n\t"
  "st    x+, r0                \n\t"
  "in    r0, __SP_H__          \n\t"
  "st    x+, r0                \n\t"
  ::);
}

```

If this looks familiar, it is because it probably is. I'm trying to implement simple context switching (pushing the entire task context into the stack and retrieving another one). What I'm trying to accomplish is storing the current PC\_H and PC\_L to a global variable so that the "shceduler" knows where to start popping the registers and restore the context.

Yes, I know FreeRTOS does this. I need to know how to do this myself.

Thanks a bunch.

# Answer
The address you are looking for is a symbol known by the linker. Then you can have the linker put the *value* of the symbol straight into your code: no need to load from memory. In other words, you use the `ldi` instruction to load the required address as an *immediate* value. You should also reverse the order of the struct definition, since you are storing SPL at the lowest address.

```
typedef struct { uint8_t sp_l, sp_h; } struct_t;

struct_t arr[MAX_STRUCTS];

void some_inline_assembly_function()
{
  asm volatile(
    // Determine where to store the new SP_H and SP_L register
    "ldi r26, lo8(arr)     \n\t"  // X is loaded with the symbol arr
    "ldi r27, hi8(arr)     \n\t"  // which is the address of arr[0].sp_l
    // Here you may want to add 2 * an array index.

    // This part stores the stack pointer low and high byte indirectly
    // using the X registers (r26,27), which is what I want.
    "in    r0, __SP_L__    \n\t"
    "st    x+, r0          \n\t"
    "in    r0, __SP_H__    \n\t"
    "st    x+, r0          \n\t"
  ::);
}

```

Notice the `lo8()` and `hi8()` assembler macros: they split the address into low and high bytes. Actually the assembler translates them into R\_AVR\_LO8\_LDI and R\_AVR\_HI8\_LDI relocations records, and the linker does the real job.

**Edit**: I think I just realized why you were thinking of using `lds` in the first place...

Instead of using array indices, you may want to access the array through a pointer (declared `struct_t *pointer`). When programming in C or C++, a pointer identifier behaves, for most purposes, just like an array identifier. However, at the assembly level, using a pointer involves an extra indirection, as you have to read the contents of the pointer from RAM. In this case you would indeed be using `lds` instructions:

```
; Copy the global 'pointer' into the X pointer register.
lds r26, pointer    ; low byte
lds r27, pointer+1  ; high byte

```

As a side note, if you are programming in C++, then you have to declare `extern "C"` any identifier that you want to use both in C++ and in assembly. Otherwise the C++ compiler will mangle its name and you would need to use the mangled name in the assembly source.
> 3 votes

---
Tags: avr, assembly, avr-toolchain
---


# Question
Title: Passing a long string from SoftwareSerial to Serial
I'm currently playing around with a GPRS shield on an Arduino Uno, for which I have to write raw AT commands over the `SoftwareSerial`. At the moment, I just want to be able to talk to the GPRS from my PC, so I've written a really basic program to send serial in two directions:

```
#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);

void setup()
{
  GPRS.begin(19200);
  Serial.begin(19200);
}

void loop()
{
  if (GPRS.available())
  {
    Serial.write(GPRS.read());
  }

  if (Serial.available())
  {
    GPRS.write(Serial.read());
  }
}

```

So the communication looks something like this:

```
         HW               SW
+----+ Serial +-------+ Serial +------+
|    |        |       |        |      |
|    +-------->       +-------->      |
| PC |        |Arduino|        | GPRS |
|    <--------+       <--------+      |
|    |        |       |        |      |
+----+        +-------+        +------+

```

This seems to work fine for shorter commands:

```
AT+CPIN?

+CPIN: READY

OK

```

But I'm really interested in doing a `NETSCAN` to see what networks are available. When I try it, I get this:

```
AT+CNETSCAN

------MOST SUITABLE CELL------
Operator:"YES OPTUS",MCC:505,75

```

And that's all. I pulled out a logic analyser to spy on the serial pins themselves, and it appears that the complete message is being sent back to the Arduino from the GPRS module perfectly okay - but for some reason, it gets cut off before it reaches my PC.

This is what the logic analyser sees over the SW (top two tracks) and HW (bottom tracks) serial lines:

So it appears that the entire GPRS response is being read by the Arduino before it starts to send anything back to the PC, and I assume that some sort of buffer has been overrun and I only get the start of the message.

So - how should I go about passing through long strings between serial ports like this? I assumed that using `if (X.available())` instead of `while` would alleviate any issues with long strings (because it appears that this way the two serial ports should take turns with one byte at a time), but is that assumption incorrect?

# Answer
> 1 votes
The output of the logic analyser is pretty clear. The problem will be a buffer overflow. One question is whether it is the receive buffer or the send buffer.

My best guess is the receive buffer: What could go wrong with your code is that the interrupts used by SoftwareSerial take precedence over the ones used by HardwareSerial. So *maybe* that's the reason why nothing is sent before the full message is received.

The `SoftwareSerial` library has a debug flag (`_DEBUG`) which you can enable to pulse a pin as an overflow indictator.

What I would try is to swap Software- and HardwareSerial (i.e. use SoftwareSerial for the communication with the PC). If the problem is as described above it should then vanish because the HardwareSerial does not block interrupts (nor the program flow) while receiving a byte.

---
Tags: serial, gsm, softwareserial
---


# Question
Title: Relay built in to cable with arduino interface
To be able to switch 220 volt stuff on and off using arduino, I need a relay (I assume). Is there really no nice extention cable with built in relay so you dont need to cut and connect high voltage.

I imagine a Power strip With a simple input port that can be controlled from the andruino, just like a relay board. When I Google this I get a lot of USB controlled and remote controlled, but none that works with an andruino project.

# Answer
> 1 votes
PowerSwitch Tail is what you are looking for.

---
Tags: power, relay
---


title: Comparison of an Arduino's performance?

text:
# Question
Title: Comparison of an Arduino's performance?
How does an AVR-based Arduino's CPU performance compare to a vintage PC (Apple II, PC-XT, TRS-80, et.al.)?

How many megaflops of number crunching can one get out of an AVR-based Arduino?

# Answer
OK, so I just ran some **really** old benchmarks on a LightBlue Bean (AVR 328p Arduino at 16 MHz). The Bean ran the Byte Sieve benchmark slightly slower than a VAX 11/780. The Bean also ran some of my old floating point computations about 2X faster than the 11/750 (this VAX model has no FPU to be fair to the AVR). That puts the Bean's math performance at somewhere around 70 kFLOPs (with few divides in the mix). A DEC VAX is several times faster than vintage 8-bit personal computers, an IBM PC-XT being roughly 1/3 to 1/2 a VAX "MIP" in benchmark performance, with an Apple II being slower still.
> 1 votes

---
Tags: performance
---


# Question
Title: Erratic behaviour using Serial.print() when powering only from power supply
I'm using an arduino uno with a thermal printer and the following code:

```
#include "Adafruit_Thermal.h"
#include "skull.h"
#include "SoftwareSerial.h"
int printer_TX_Pin = 8;  // This is the yellow wire
int printer_RX_Pin = 9;  // This is the green wire
Adafruit_Thermal printer(printer_RX_Pin, printer_TX_Pin);

void setupPrinter() {
  printer.begin();
};

void doPrint(char* output) {
  Serial.print("Will print: ");
  Serial.print(output);
  Serial.print("\n");
  printer.println(output);
  printer.feed(2);
}

void setup() {
  setupPrinter();
  doPrint("This is a test to see if it will print only from power supply");
}

void loop() {
}

```

That code works fine if the arduino and printer are plugged into 5v and the arduino is also plugged in to a computer with USB. Once I remove the USB cable it starts printing:

```
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will

```

over and over infinitely. In other programs it prints a slightly garbled first line then stops. When I remove the serial.print lines, this doesn't occur. Why would that be?

# Answer
> 3 votes
It seems likely that your Arduino is repeatedly resetting, which means it's starting the program again from the beginning all the time. This can be caused by insufficient power.

For the standard 5v Arduino boards, the minimum recommended voltage for an external power supply is usually 7v. An on-board regulator brings it down to 5v.

Technically, you *can* run them directly from an external 5v supply. However, you have to ensure that it's properly regulated, and that you bypass the on-board regulator.

Obviously you also have to ensure your external supply is capable of sourcing sufficient current. If you're just running an Arduino and a small thermal printer then it's probably OK, but it's certainly worth checking.

---
Tags: arduino-uno, serial, power, usb
---


# Question
Title: Can I measure the current (mA) of my project with just a multi meter?
I have a project and wish to choose the correct battery back for it such that it will last the required amount of time between each recharge of the battery pack. I am using an Arduino Duemilanove with various attachements and shields.

I can measure that the draw on the project at the point the USB connects from my PC to the Arduino board (by attaching the multimeter to the Vcc and GND solder points on my Arduino board) which reads 5V DC as expected. Is there a way I can meausre the current (without any additional equipment) ?

I suspect somehow using Ohms law and measuring the resistance between two points would be the answer (knowing the voltage is 5V) but I can't work it out (as in where to measure) with my lack of any electrical knowledge.

# Answer
> 4 votes
No, you won't get the right result measuring resistance. Integrated circuits contain lots of semiconductors which are inherently non-linear.

You need to somehow put your multimeter in series with the power supply, set to the mA range. The easiest way I can think of is to use an external battery (7v or higher) and make up a custom cable with standard barrel jacks. As your board appears to have a linear voltage regulator, the current measured will be very close to the current consumed when powered from the USB port.

# Answer
> 1 votes
A reasonable method is to place a small value resistor in series with the supply, connect a capacitor from the Arduino side of the resistor to ground and then measure the voltage drop across the resistor.

If you set the resistor value such that the highest current drawn drops less than about 0.1 Volts then it will have minimal effect on most circuits.
For example if max current is 100 mA then as R = V/I, Rmax \<= V/I = 0.1/100 ma = 0.1V/0.1A = 1 Ohm.
So generally
Rseries \<= Vdrop\_max / Imax\_A (I in Amps) or Rseries = Vdropmax x 1000 / Imax\_mA (I in milliAmps)

Then I\_ma = Vmeter x 1000 / R

Example:

Max current = 350 mA.
R \<= V/I = 0.1V /0.350 A = \<= 0.286 Ohm. A 0.1 Ohm - which is a readily available standard value, will probably be good.

Then if meter reads say 0.033 volt (33 millivolts) then
ImA = V\_mv / R = 33/0.1 = 330 mA.

A larger resistor value, giving a larger voltage drop, can be used if the circuit will tolerate the resultant lower supply voltage.

---

Measure the drop with a meter set to 0.2 V (200 millivolts). Nit all meters have a 0.2 V range but even some reasonably cheap ones do have and it is worth having a meter with this range for various purposes.

Connect a capacitor from Arduino 5Vin to ground - the more uF the better. 100 uF probably OK, 1000 uF better ... .

This method will smooth out short current peaks and give you an average current. This aspect can be expanded on if of interest.

---
Tags: current, arduino-duemilanove
---


# Question
Title: object with multiple instances with internal data store separate for each instance
I'm trying to keep track of a timer, and the internal variables seem to be overrun by one another.

I just want two instances of the Output class, which can keep track of the \_elapsed\_time so I can check if the time elapsed. It's a poor-man's real-time for a game. I know there are libraries available and I'm planning to use them, but I would really appreciate knowing what's going on here: I want a buzzer pin, and status led pin to 'blink' at different intervals. They both work individually, but when I have them both uncommented they work somewhat serially...

```
#include "Arduino.h"

#include "MTC.h"

#include <SoftwareSerial.h>   //Software Serial Port

//HARDWARE SETTINGS
#define PIN_STATUS                  13
#define PIN_BUZZER                  A2

Output *STATUS(0);
Output *BUZZER;

void setup()
{
    Serial.begin(9600);
    STATUS = new Output();
    STATUS->Begin(PIN_STATUS, STATE_OFF);
    BUZZER = new (Output) Output(3);
    BUZZER->Begin(PIN_BUZZER, STATE_OFF);
}

void loop()
{
    static bool run_once = true;

    if (run_once == true)
    {
        run_once = false;
        Serial.print("Running");
        Serial.flush();
    }
    delay(250);

    //Serial.println("still running");

    STATUS->SetStrobe(3000);

    //BUZZER->SetStrobe(4000);

}

```

and class:

```
#ifndef MTC_h
#define MTC_H

typedef int OUTPUT_STATE;
OUTPUT_STATE STATE_OFF = 0;
OUTPUT_STATE STATE_ON = 1;
OUTPUT_STATE STATE_STROBE = 2;

class Output
{
private:
    int _pin;
    OUTPUT_STATE _last_state;
    unsigned long _cycle_duration;
        unsigned long _last_elapsed;

public:
    Output();                                           //constructor: set pin data store
    void Begin(int pin, OUTPUT_STATE state);                                //set hardware to output and defaul state
    void Set(OUTPUT_STATE state);                               //toggle operability
    void SetStrobe(unsigned long duration);                     //strobe operability
};

Output::Output()                                    //constructor: set pin data store
{

}

void Output::Begin(int pin, OUTPUT_STATE state)
{
    _pin = pin;
        _last_elapsed = millis();
    pinMode(_pin, OUTPUT);
    digitalWrite(_pin, state);
    _last_state = state;
}

void Output::Set(OUTPUT_STATE state)
{
    if (_last_state != state)
    {
        digitalWrite(_pin, state);
        _last_state = state;
    }
}

void Output::SetStrobe(unsigned long duration)
{
    static OUTPUT_STATE _last_strobe_state = STATE_OFF;

    unsigned long elapsed = millis() - _last_elapsed;
    if (elapsed >= duration)
    {
        if (_last_strobe_state == STATE_OFF)
        {
            digitalWrite(_pin, STATE_ON);
            _last_strobe_state = STATE_ON;
        }
        else
        {
            digitalWrite(_pin, STATE_OFF);
            _last_strobe_state = STATE_OFF;
        }
        _last_state = STATE_STROBE;
        _last_elapsed = millis();
    }
}
#endif

```

# Answer
Your `Output::SetStrobe()` is wrong, it uses a `static` variable (`_lasr_strobe_state`) that is thus shared between all instances of `OUTPUT`, which is NOT what you want.

You have to change it into a non-static member of class Output instead:

```
class Output
{
private:
    int _pin;
    OUTPUT_STATE _last_state;
    // NEW member here!!!
    OUTPUT_STATE _last_strobe_state;
    unsigned long _cycle_duration;
        unsigned long _last_elapsed;

public:
    Output();     //constructor: set pin data store
    void Begin(int pin, OUTPUT_STATE state);//set hardware to output and defaul state
    void Set(OUTPUT_STATE state);            //toggle operability
    void SetStrobe(unsigned long duration);  //strobe operability
};

```

Then you initialize it in the constructor:

```
Output::Output():_last_strobe_state(STATE_OFF)
{

}

```

And you remove it (static declaration) from method `SetProbe` (the rest of the method does not change):

```
void Output::SetStrobe(unsigned long duration)
{
    unsigned long elapsed = millis() - _last_elapsed;
    if (elapsed >= duration)
    {
        if (_last_strobe_state == STATE_OFF)
        {
            digitalWrite(_pin, STATE_ON);
            _last_strobe_state = STATE_ON;
        }
        else
        {
            digitalWrite(_pin, STATE_OFF);
            _last_strobe_state = STATE_OFF;
        }
        _last_state = STATE_STROBE;
        _last_elapsed = millis();
    }
}

```
> 1 votes

# Answer
This is not a real answer, as @jfpoilpret already gave a perfectly valid one. Just a few observations and suggestions from looking at your code. I write is as an answer only because it is too long to fit in a comment.

1. The member variable `_cycle_duration` is not used. You could remove it and save a couple of bytes per Output instance.
2. `if (run_once == true)` is equivalent to `if ((run_once == true) ==
true)`. They are both considered bad style. Preferred style is to just write `if (run_once)`.
3. On the Arduino, it is generally good practice to avoid dynamic allocation whenever possible. Of course, it is not always possible, but in this instance it is quite easy: declare STATUS and BUZZER as objects instead of pointers (as in `Output STATUS;`), then replace `->` by a single dot (`.`).
> 0 votes

---
Tags: library
---


title: Multiple interrupts in same sketch

text:
# Question
Title: Multiple interrupts in same sketch
I am trying to create an Arduino program that combines a pulse sensor (that measures the Beats Per Minutes) and a music shield. I am experiencing some difficulties with the coding because the pulse sensor has an extensive interrupt routine that occurs every 2ms while the music shield has its own interrupt. Through research I have found that the Arduino Uno cannot have two interrupt routines at the same time.

> Is it possible to code around this issue in order to have both the interrupt routines worK?

I am attaching the code below:

```
//Include Music Shield Library
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

// Define everything needed for the Music Shield
#define BREAKOUT_RESET  9     // VS1053 reset pin (output)
#define BREAKOUT_CS     10    // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8     // VS1053 Data/command select pin (output)
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7       // VS1053 chip select pin (output)
#define SHIELD_DCS    6       // VS1053 Data/command select pin (output)
#define CARDCS 4              // Card chip select pin
#define DREQ 3                // VS1053 Data request, ideally an Interrupt pin

//Explain what musicplayer means
Adafruit_VS1053_FilePlayer musicPlayer =
  // create breakout-example object!
  //Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS, DREQ, CARDCS);
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//Variables for the Pulse Sensor
int pulsePin = 0;                   // Pulse Sensor purple wire connected to analog pin 0
//These variables are volatile because they are used during the interrupt service routine!
volatile int BPM;                   // used to hold the pulse rate
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // holds the time between beats, must be seeded!
volatile boolean Pulse = false;     // true when pulse wave is high, false when it's low
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

//Define integer range for the switchcase map function
const int sensorMin = 70;           // sensor minimum, dicovered through research MAY CHANGE
const int sensorMax = 230;          // sensor maximum, discovered through research MAY CHANGE

//Now we are going to set up the sensor and the shield.
//The swtichcase does not need setup because we are not using the serial monitor for it.
void setup(){
Serial.begin(115200);
  Serial.println("Adafruit VS1053 Simple Test");
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
//Now we setup the rest of the shield.

  if (! musicPlayer.begin()) {      // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

  SD.begin(CARDCS);    // initialise the SD card

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(05,05);

  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);  // DREQ int

}
//Void setup is done, now we tell the arduino what to do with all this information.

void loop(){
   // read the sensor:
  int sensorReading = analogRead(A0);
  //A0 should be BPM
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 4);

//In our map range 0=70-110, 1=110-150, 2=150-190, 3=190-230, 4=end(DEAD)
// do something different depending on the
// range value:
//Track 1 is resting music, track 2 is medium beat, track 3 is fast beat, and track 4 is continous beeps.
  switch (range) {
  case 0:    // 70BPM - 110 BPM
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("track001.mp3");
  case 1:    // 110 BPM - 150 BPM
    Serial.println(F("Playing track 002"));
    musicPlayer.startPlayingFile("track002.mp3");
  case 2:    // 150 BPM - 190 BPM
    Serial.println(F("Playing track 003"));
    musicPlayer.startPlayingFile("track003.mp3");
  case 3:    // 190 BPM - 230 BPM
    Serial.println(F("Dangerous"));
    musicPlayer.startPlayingFile("track004.mp3");
  case 4:    // DEAD
    Serial.println(F("DEAD"));
    musicPlayer.startPlayingFile("track005.mp3");
    break;
  }
  delay(1);        //This is the delay of the switchcase.
                   //The Music Shield Requests 100, so this MAY CHANGE
}

volatile int rate[10];                    // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P =512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 512;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void interruptSetup(){
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

    //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3){       // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T){                        // T is the trough
      T = Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P){          // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
      IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if(secondBeat){                        // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for(int i=0; i<=9; i++){             // seed the running total to get a realisitic BPM at startup
          rate[i] = IBI;
        }
      }

      if(firstBeat){                         // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++){                // shift data in the rate array
        rate[i] = rate[i+1];                  // and drop the oldest IBI value
        runningTotal += rate[i];              // add up the 9 oldest IBI values
      }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true){   // when the values are going down, the beat is over
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }

  sei();                                   // enable interrupts when youre done!
}// end isr

```

# Answer
> 2 votes
I wrote most of the SFEMP3Shield library. Where it appears that AdaFruit based much of theirs on. That said I have used Timer1 library with mine just fine to invoke the filling of the VS1053.

Where I am suspicious that AdaFruit's Library's did not Interrupt lock out the SPI packets. As I did on the SFEMP3Shield library, as to keep other things from messing up the frame. Where a brief skim of your code, initially looks fine.

You have not described your symptoms. Where as using 2ms IRQ's and noting the VS1053 library reads the SdCard in 500byte chunks I image these reads are blocking and corrupting your 2ms ISR.

You can try to slow them down, just to see if they stop getting messed up.

You can try to using the polling method of the VS1053, instead of interrupts.

You can try to use the more feature mature SFEMP3Shield library and its documentation noting that it also uses the more mature SdFat. As the stock SD library may be part of your problem.

---
Tags: shields, interrupt
---


# Question
Title: How to communicate the Arduino board with SIM900?
I have a problem. I bought a SIM900 board, but I can not connect there with the Arduino. To send AT commands on the serial the SIM900 doesn't respond, but the LED indicating that the network is on. I've tried to change the baud rate of 9600 to 19200 in the firmware of the Arduino, but it still fails. I think I'm having a problem with the connections of the SIM900, since this board strikes me as obscure (could not find the schematic on the Internet)

The board I have is identical to this:

I'm 90% sure that I am connecting to the wrong pins. But I tried to reverse the jumpers and even some soldered pins on UART.

# Answer
I'll tell you what worked for me, because I didn't find the schematics of this board. But your board may work differently, so it is always good to check the datasheet and the schematic (if you have one).

## **Power**

Be sure to use an external 5V source that can supply up to 2A without dipping significantly.

## **Code**

```
#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);         //7 = TX, 8 = RX
unsigned char buffer[64]; port
int count=0;
int i = 1;                         //if i = 0, send SMS.
void setup(){
  //delay(10000);
  GPRS.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);             // the Serial port of Arduino baud rate.
  Serial.print("I'm ready");
  Serial.print("Hello?");
}

void loop(){
  if (GPRS.available()){         // if date is comming from softwareserial port ==> data is comming from gprs shield

    while(GPRS.available()){          // reading data into char array
      buffer[count++]=GPRS.read();     // writing data into array
      if(count == 64)break;
    }
  Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
  clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
  count = 0;                       // set counter of while loop to zero
}

if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
  GPRS.write(Serial.read());       // write it to the GPRS shield
  if(i == 0){
    GPRS.print("AT+CMGF=1\r"); //sending SMS in text mode
    Serial.println("AT+CMGF=1\r");
    delay(1000);
    GPRS.print("AT+CMGS=\"+554988063979\"\r"); // phone number
    Serial.println("AT+CMGS=\"+554988063979\"\r");
    delay(1000);
    GPRS.print("Test\r"); // message
    Serial.println("Test\r");
    delay(1000);
    GPRS.write(0x1A); //send a Ctrl+Z(end of the message)
    delay(1000);
    Serial.println("SMS sent successfully");
    i++;
  }
}

void clearBufferArray(){              // function to clear buffer array
  for (int i=0; i<count;i++){
    buffer[i]=NULL;                  // clear all index of array with command NULL
  }
}

```

## **Connection**

## **Testing...**

Open the serial monitor Arduino, set the baud rate in 19200 in "Both NL & CR". If not work, set to "Carriage Return". Type "AT" and wait for an OK.

## **Help**

If you need help, these links were useful to me:

1. http://www.seeedstudio.com/wiki/GPRS\_Shield\_V1.0
2. http://www.seeedstudio.com/wiki/GPRS\_Shield\_V2.0
3. http://www.elecfreaks.com/wiki/index.php?title=EFCom\_GPRS/GSM\_Shield
> 4 votes

---
Tags: gsm
---


# Question
Title: Using an Arduino board to program an AVR
I think the arduino board is awesome. Though I'm not interested in the library and IDE at all... Is there a way, to use an AVR 328p, as you normally would, on an arduino board?

I like how arduino's can be programmed through serial, can get powered through serial and I often use serial as a debugging option. Making my own board (with ICSP programmer) would not be able to do this (withouth bootloader).

---

**The Question**

Do I have to use all the stuff from arduino?

* Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
* Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
* Can I still program through serial then? (Does the bootloader care which compiler I used? Does Eclipse/AVR studio have the options to program through serial?)
* Other stuff I should take in mind. (Annoying things like AVR studio not having a COM port window, though that's an easy fix.)

Edit: We've programmed an AVR 328P (GNU-GCC / Eclipse / ICSP) in school, so I know it takes quite some work to get the compiler set up, working with Eclipse. You don't have to completely describe the proces :) Just to avoid someone spending hours on an answer that's easily found on the internet. (On my search for this subject I could only find people doing the other way around, getting an 328p chip to work with arduino)

# Answer
> 2 votes
1. Do I have to use all the stuff from arduino?

A = No!

3. Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
4. Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
5. Can I still program through serial then? (Does the bootloader care which

Of Course! I use `Eclipse IDE` and I programming boards with Arduino bootloader directly in `C/C++` using avr-gcc and avrdude.

## **Configuring Eclipse**

First, let's download a plug-in for integrating `AVR GCC` and `Avrdude` \+ `Eclipse IDE`

To install the plug-in, point to the menu "Help\> Install new software":

We will set a new location to download the plugin. Click the "Add ..." and type: AVR - Eclipse and the URL: http://avr-eclipse.sourceforge.net/updatesite

Now select the plugin that appeared in the list and click "Next":

Next, next, "I Acept the terms...", restart...

Now we install the plug-in, we will set it up. Point to the menu "Window\> Preferences." Click in "AVRDUDE". The following screen:

**On the next screen "AVR DUDE" let's set our recorder. Click "Add" to "Programmer configuration". Search for "Arduino".**

Or, if you prefer, you can program making use of avr libraries in own Arduino IDE. Try to upload the following code into an Arduino board! While a blink costs almost 1,056 bytes of memory using an Arduino Uno, the following code uses only 164 bytes and does the same thing :)

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

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clr_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define tst_bit(Y,bit_x) (Y&(1<<bit_x))
#define cpl_bit(Y,bit_x) (Y^=(1<<bit_x))

#define LED PB5

int main( ){
    DDRB = 0xFF;

    while(1){
        cpl_bit(PORTB,LED);
        _delay_ms(200);
    }
}

```

If you use Linux, you can take a `sudo cat/dev/ttyACM0` to detect what lies serial and `echo "string" >> /dev/ttyACM0` to send data.

---
Tags: atmega328, eclipse, avr-gcc, gcc
---


title: Unable to see SPI clock in oscilloscope

text:
# Question
Title: Unable to see SPI clock in oscilloscope
I am using the following code and when I am probing pin 13(SCK), I can't see any clock signal in the oscilloscope.

```
#include <SPI.h>
int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

void setup()
{
 pinMode(SCS,OUTPUT);
 pinMode(EXTCOMIN,OUTPUT);
 pinMode(SCLK,OUTPUT);
 digitalWrite(SCS,HIGH);
 tone(EXTCOMIN,50);
 SPI.setClockDivider(SPI_CLOCK_DIV16);
 SPI.begin();
}

void loop()
 {
 }

```

# Answer
> 2 votes
(META: This question has been answered in the comment section of the question itself. (And I'm also unable to comment to say that he should answer his own question...) That's why I'm putting this answer here.)

You might want to look into the basics of SPI, the clock will only oscillate when there is an actual data transaction in progress. (This will prevent desynchronisation by a bit. And will make both sides know when data is being send. Often along with a SS) You can check this by continiously sending something in your code and then probe the clock pin with an ossciloscope.

You might want to accept this as an answer, so that nobody it's clear this question is already answered.

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


# Question
Title: What is the best transmitter/receiver to use with an Arduino RC?
I want to customize an RC car that I have because the controller is gone. I'm going to use an Arduino with a custom motor controller but I have no idea what to use for the transmitter/receiver. I've seen some IR sensors being used but I want something that uses a frequency channel. Has anyone had experience doing this? What is the easiest way to go about accomplishing a remote controlled Arduino car?

# Answer
That depends largely what is controlling it

Some options include:

* wifi, if you have an expansion board, from a PC or phone (spec says: 66ft/20m)
* bluetooth works great, directly from your phone (spec says: 32ft/10m - 320ft/100m)
* 433mhz ASK transmitter/receiver from another Arduino or other hand-designed circuit (spec says: 100m/320ft)
* Infrared receiver - from a TV remote! (range unknown, depends on remote & conditions; would not trust it 10m outside without testing).
* Cellphone network - longest range (nationwide!). If you get a cheap android to do some of the work, you can use the phone's compass & gps & extra processing power, as well as the camera(s)!
* Remote control. I know you said you lost yours, but in case someone else is looking here, you can hook up an rc receiver to an Arduino fairly easily. https://www.sparkfun.com/tutorials/348 for more info.

Many of these ranges specified will depend on the antenna. If your car can tell it's lost signal, then it can stop; otherwise you have to outrun it, or wait for it to hit a wall.

Edited to include cellphone network, and added ranges to options
> 1 votes

# Answer
Here is a link to a pair of Arduino compatible wireless transceivers. One of the listed applications in the description is "remote control systems such as RC vehicles," so I think this product would suit your project well.

According to the reviews / answers to questions on Amazon, the transceivers have an reliable range of just around 120 feet, so this component would be entirely appropriate in a remote-controlled build.
> 1 votes

---
Tags: motor, remote-control
---


# Question
Title: do two arduinos that are linked to a common 9v rail and ground still need a common negative connection for a serial tx rx connection?
so that there a 2 wires rather than 3 to connect between the two for purposes of serial communication. And the same question for 3 arduino megas on a common rail and using serial connections?

# Answer
All voltages are ground referenced, hence the ground is the only (supply) connection required. Remote modules can be self-powered and signals will still be discriminated as long as ground is connected.
> 3 votes

---
Tags: serial, arduino-mega, wires
---


title: Arduino Nano For Home Automation

text:
# Question
Title: Arduino Nano For Home Automation
My question is about the arduino Nano or Micro and the smallest and cheapest way to control a bigger power source. I would wire it with a socket so that I could send a command from the board and a light would turn on for example.

# Answer
> 1 votes
A relay is a common way to allow a smaller power source to safely control a larger one. A relay is like a switch.

Here's some reference material about using a relay with a microcontroller. You shouldn't have much trouble finding more material now that you know what you're looking for.

# Answer
> 0 votes
So your question is: "How to control a bigger power source using the Arduino Nano or Micro".

This tutorial on youtube gives an explanation: https://www.youtube.com/watch?v=sOz41WQF7wE

It's about a motor, but the answer is the same. You should use a relais/mosfet

This one is actually pretty great also: https://www.youtube.com/watch?v=Te5YYVZiOKs

---
Tags: arduino-nano
---


# Question
Title: How to generate gcode for Arduino Mega 2560 and Ramps 1.4 CNC Router
I had a Prusa I3 3D Printer which use Arduino Mega 2560, Ramps 1.4 and Pololu - A4988 Stepper Motor Driver.

I want to convert my 3D printer to CNC Router using my Dremel with Flexible shaft like this.

I found the one project on instructables.com at here http://www.instructables.com/id/Arduino-Controlled-CNC-3D-Printer

They give config for Mega 2560 as CNC router. But i don't know how to generate g-code for these cnc router.

Please help me to generate g-code from STL, DXF and Image(PNG or SVG) files to use with this type of cnc router.

# Answer
> 4 votes
For generating g-code from an SVG, you could try to parse the SVG into a set of relative commands, and using the relative commands to generate G-code. Since you were originally using the frame as a 3d printer and now you want to use this as a CNC machine, you could try to invert the data. But, for generating the code I would go read up on how to parse the various file formats, and read the specs on each of the formats. However, most of the file formats you listed are proprietary, and you won't be able to find an open spec for them.

Of the formats that you listed, it would probably be the easiest to parse the SVG, as it's an open spec, and is a lot like XML.

This is going to be really difficult to actually do, because you're essentially reimplementing a full CNC controller.

I would start with getting 2 dimensional stuff down like drawing shapes and setting routing depth.

# Some Resources

Here are some resources that might help you with parsing the various file formats. I only listed the ones that have an open standard.

---
Tags: arduino-mega
---


# Question
Title: What are the differences between the 1.0.x and 1.6.x IDEs?
What is a summary the main differences between the Arduino 1.0.x and 1.6.x IDEs? Why do some Arduino products, such as the LightBlue Bean, still require use of the 1.0.6 IDE?

# Answer
I think Arduino's version history is a bit confusing. I'm not an expert but I think this explanation will help. First let's note that version 1.6 was released 2015.02.09. However, back in 2012, version 1.5 BETA was created and it remained in beta for several years. Meanwhile, the 1.0.X version evolved independently here's an excerpt from the changelog

* ARDUINO 1.0.6 - 2014.09.16
* ARDUINO 1.0.5-r2 - 2014.01.08
* ARDUINO 1.0.5 - 2013.05.15
* ARDUINO 1.0.4 - 2013.03.11
* ARDUINO 1.0.3 - 2012.12.10
* ARDUINO 1.0.2 - 2012.11.05

So you can see that 1.0.6 isn't as old as one may think. Many vendors probably chose not to develop their products against the 1.5 version (or branch) because of its beta status. 1.5 being in beta for as long as it did lends to a confusing version history. I did get the impression that LightBlue Bean is working on compatibility with 1.6.x because their getting started page mentions

> Download and extract the Arduino app, version 1.0.5. We currently do not support newer versions of the Arduino IDE.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: I want to know how to record and play radio waves?
I want to make a universal remote.I have an ir receiver and transmiter. I.I can use it to control my tv and other equipment.I want to also control my dish network in the US. I checked and think that the dish uses 395mhz but i am not sure.**How can i replicate a dish remote radio signal**.I know it is radio signal and not ir. **What part do I need for the arduino?**

# Answer
> 1 votes
This is only a partial answer, but should be enough to get you started.

The parts are:

1. Build a receiver http://www.somerset.net/arm/fm\_only\_lowtech.html
2. Tune it to the right frequency
3. Use it to detect the codes sent from your remote
4. Build a transmitter http://makezine.com/projects/super-simple-fm-transmitter/
5. Tune it to the right frequency
6. Transmit the codes
7. Success!

Step 3 is probably best done with a scope - you should find someone who has one, who can operate it, because they can be damaged.

---
Tags: remote-control
---


title: Arduino Nano Motor

text:
# Question
Title: Arduino Nano Motor
If I had four of these motors and attached them to the Arduino Nano on four separate digital pins or analog pins without transistors and a 9v power supply attached to the regular power supply input would that work?

# Answer
> 1 votes
Yes, but don't expect to win any races.

If you use `analogWrite(HIGH)` on your digital pins (3, 5, 9, 10, and 11) your motors should receive 40 mA max at 5V (see http://arduino.cc/en/Main/arduinoBoardNano). So the motors will run, just not very fast.

A switching transistor would be a very simple addition that would allow you to achieve higher current input to the motors and get their full potential.

If you want to reverse the direction of the motors you'll need to investigate getting a cheap motor driver board.

---
Tags: motor, arduino-nano, robotics
---


# Question
Title: Why does opening the Tools menu take so long?
Every time I open the `Tools` menu, the IDE freezes for a few seconds. Why is that? It happens on both of my computers, and nothing I do makes a difference in how long it takes. I've tried restarting the IDE, unplugging my Uno, and many other things, but nothing helps.

I'm on windows, running IDE version 1.0.2.

# Answer
It's an RXTX issue. RXTX is the native serial library used to make the IDE talk to the boards.

On some Windows installation, with some Bluetooth things (both dongles or integrated), when enumerating serial devices, these dongles scan the air for remote serial devices. Hence, the IDE stays stuck, waiting for RXTX serial device enumeration to end. This issue has been acknowledged a lot of times, see for example #1375, #532, #200 and #143

As far as I understand, this issue does not affect linux or mac because of the different way the scan occurs. On linux it's a plain filtered file listing of `/dev`. Similarly it's on mac. On windows, it uses native API calls.

Some fixes are available in the 1.5 series but I suggest switching to the latest 1.5.6 release as RXTX was replaced by JSSC, a more modern and simpler library.
> 7 votes

# Answer
Frederico Fissore already pointed out that this delay is due to the serial libraries. From a functional perspective: The Arduino IDE tries to enumerate all available COM ports which simply takes some time.

Quote from the official troubleshooting guide:

> **Why does do the Arduino software and the Tools menu take a long time to open (on Windows)?**
>
> If the Arduino software takes a long time to start up and appears to freeze when you try to open the Tools menu, there by a conflict with another device on your system. The Arduino software, on startup and when you open the Tools menu, tries to get a list of all the COM ports on your computer. It's possible that a COM port created by one of the devices on your computer slows down this process. Take a look in the Device Manager. Try disabling the devices that provide COM ports (e.g. Bluetooth devices).
> 7 votes

# Answer
I was having the same problem under Windows 7 x64 and had already removed all com ports and unknown devices as suggested above. For me, the solution was to rename "ListComPorts.exe" in the **hardware\tools** subfolder to "ListComPorts.exe.xxx" - this prevents the Arduino IDE from using this file and appearently it reverts to using the internal COM port detection mechanism (using DEVICE\_ARRIVAL/DEVICE\_REMOVAL messages??) . The tool menu now opens immediately every time.
> 2 votes

# Answer
I had the same issue on my laptop (win 7, 64). Renaming file ListComPorts.exe to ListComPorts.exe.xxx as mentioned above worked. I also had to switch to a standard USB port (not 2.0) for sketch to load properly.
> 0 votes

---
Tags: arduino-ide
---


title: Include my header files

text:
# Question
Title: Include my header files
let's suppose I have folder called AES, in this folder is file "AES.ino" where is code and folder "AESLib" what is library. In "AESLib" is file called "AESLib.h",

now when I try to include AESLib.h with

```
#include "AESLib/AESLib.h"

```

in my AES.ino, then Arduino command line tool complain that its not able to find "AESLib.h"

Where could be the catch?

Thanks

# Answer
Maybe this similar post is what you are looking for. In your case, you should use the path to the sketch folder as 'PROJECT\_ROOT'.

Here's the link: https://arduino.stackexchange.com/a/9575/7741

Hope it helps.
> 0 votes

# Answer
I have the same problem using the Arduino IDE 1.5.6 beta. Adding the library(s) using the menu (Sketch-\>include library-\>something) makes it work until the IDE is closed.
> 0 votes

---
Tags: c++, library
---


# Question
Title: Possibilities and limitations for onboard data acquisition
I could define myself as a "nerdy cyclist", so while my interest in Arduino is steadily growing (have not bought or used yet), my first idea for a project would be:

1. Instrument a bicycle with some sensors (accelerometer, reed switch, etc) and an Arduino;
2. Ride long distances (that is, four hours or more, sometimes non-stop);
3. When at home, download some sort of "data file" (from SD card, I think);
4. Analyze results with Python/Matlab/whatever.

So my questions:

* Is any model of Arduino suitable for this purpose?
* What is the expected sample rate vs number of channels? 100Hz per channel would be excellent for my purposes, for example.
* Can I keep incrementally saving to SD "forever" (that is, while battery and card space are available)?

# Answer
First of all your idea project is feasible. And to answer to your questions:

1. There is no right Arduino for your project simply because theoretically every Arduino board can do the job. But as you said it has to be portable you might use Arduino nano/mini or even Uno if you have enough room or space.
2. The acquisition rate depends on the on the type of sensor you have. So if you have let's say one analog reading you can use the built in function in Arduino which is capable of making about 10000 readings at time. So if you have multiple outs you can easily for the calculation. There are also sensors which has a digital output in this case in order to read your value you communicate with Tue sensor board through Two wire interface or I2C communication interface, for this there is a library you can use. Usually the speed at which this communication work s very high, at 100kHz( if I'm not wrong).

3.Yes you can save data on the SD card until you don't exceed the memory or the battery doesn't die.

I have a suggestion for your project, as you're going to acquire some sort of data and then analyze it on your computer, do less calculations on your Arduino board and let the PC handle the hard work.

Useful links:
> 1 votes

# Answer
Another idea - I believe if you are making electronics you must be using some smart phone? If I am correct why don't u utilize your smart phone with Arduino? 1) Connect sensors to Arduino 2) Use Bluetooth or WiFi shield 3) Store data locally until memory available 4) Transfer to your phone or to web via phone network every hour or 5 hours. This will make battery consumption less and also make device Compaq.

Regards, Pathik SHAH
> 0 votes

---
Tags: datalogging
---


# Question
Title: motor affecting time calculation between hardware interrupts
My robot uses an Arduino Mega 2560. It has 6 IR receiver modules connected to its 6 external pins namely 2, 3, 18, 19, 20, and 21.I have connected the Pololu MC33926 dual motor driver arduino shield to my arduino(here is the connections diagram : https://www.pololu.com/docs/0J55/3.c ). I generate a 56KHz IR signal with an LED from another Arduino. The IR receiver modules convert the 56KHz signal into a active low digital signal. My signal consists of a signature bit followed by 32 bits of data. a binary 1 is represented by a signal of length 1200 uS and a binary 0 is represented by a 600uS signal with intervals of 600uS. I employed a state machine in my code which checks the duration of time between falling edge and rising edge. and vice versa and compares it to the duration expected. If anything is not expected it discards as noise and goes back to the idle state. If the duration is as expected it goes to the next state and then takes in the entire 32 bits and converts this binary format into a decimal value. I print this value on a 7 segment display on my robot. It works perfectly when the motor's are not running. Now this is the case when the motors are running. It does not receive the signal. I have tested every component individually and these are the results:

1. The receivers still receive the signal perfectly, and their output to the Arduino is also as expected. No problem there.
2. Earlier the Arduino was being powered through the Motor driver. Just to make sure that was not the problem I separated the Arduino's power supply from that of the motor driver. Still the same issue, i.e. the robot does not receive a valid signal(at this point i realized the arduino receives a valid signal but isnt able to decode it accurately).
3. We then printed out the values of time differences between each rising and falling edge on the interrupt pins. These values seem correct and within the tolerance range when the motors are switched off. But when the motors are switched on these values are not right. Of the 32 duration's measured, atleast two are not right(for eg. instead of 300 uS it calculated 88uS) due to which the signal is being discarded as invalid.
4. I thought that the PWM being generated to control the speed of the motors on digital pin 9 and digital pin 10(OC2B AND OC2A). Even though the PWM signals were being generated(without the motors connected) the signal was still being read as valid and the robot was receiving the signal. So its not that either.

The only anomaly I have found are the readings of the durations of the interrupt intervals. Can somebody please tell me what connection I have done wrong. Its mostly not with the program since it works otherwise. Something with the motor is making the Arduino act weirdly. Any help will be greatly appreciated. I have to scale up these robots to build a swarm and I am still stuck in the first step.

Thanks a lot.

# Answer
> 1 votes
Noise from electromagnetic sources is always an important issue that must be addressed. The aims are to minimise noise generation at source, reduce transmission of noise between source and the "target" affected circuitry and reduce noise impact at the target.

**Motor controller circuit diagram here**

The shield power supply link MUST have been removed.
Shield must have all own powering.
Coupling via a common eg 5V supply has a high chance of being problematic.
The two 5V supplies (arduino & shield) could have a common higher voltage source but need separate regulators and proper noise removal in each supply.

Placing extra capacitance across the arduino Vin or main power source MAY help.

I assume that the motors are driven in either direction during operation. If not then a reverse diode across the motors should help.
If bidirectional, try reversed diodes from each motor lead to Vout (= V+ motor drive voltage).

The shield's Vout filter capacitors C7 & C8 care 47 uF each.
Vout could usefully have 1000 or so uF added somewhere on the board.

I do not know how much motor current is drawn and exact control strategy. This MAY interfere with motor drive but probably not: Identify one motor which "has issues". Add a small series resistance in each lead with a capacitor across the leads on the motor side. Here "small" means "does not noticeably affect performance". eg 1 Ohm if Imotor \< to \<\< 1 amp. Capacitor needs to be biplar for bidirectional motor control - eg a 1 uF ceramic or plastic (polyester, mylar, ...) cap.

'If all else fails'\[tm\] opto coupling the driver interface is possible BUT should not be needed.

Try above.
Report.
Ask more questions if needed.

# Answer
> 0 votes
Thanks for the above answer. It got me thinking on the right track. After some reading through the motor driver data sheet I realized that I forgot totally about the by-pass capacitors. After connecting a 0.1uF cap between two terminals of the motors and another two between the terminals and the casing the results are much better. It can receive a valid signal from another robot(though not as well as when the motors are turned off). Any suggestions where else I could place by pass cap's to further eliminate electrical noise?

Again, Thanks a lot guys. really appreciate the help.

---
Tags: motor, hardware
---


# Question
Title: Reprogram Arduino Mega 2560 using Duemilanove?
Experiencing that Mega 2560 uploading problem. Tried updating the IDE, worked for a while but symptoms went back. Now i want to reprogram that chip.

I'm asking this question cuz hardware ain't free and shipping is not instant.

I don't have a programmer. So we already know that we can program an arduino board with another arduino board as a programmer. However i just have a Duemilanove available. Will this work? Please do not answer if you're not sure.

# Answer
> 1 votes
Yes it is possible.

You can follow this tutorial: http://www.gammon.com.au/forum/?id=11635 The uno is basically the same as the Duemilanove

---
Tags: bootloader, isp
---


# Question
Title: Use Arduino Uno to program the on-board Atmega328 in C
I have an Arduino Uno board. I have seen how it is possible to program external AVR's through the Arduino Uno board, for instance an ATtiny. But I'm starting with c for atmel µc and I just want to program Atmel328's through the Arduino hardware, and being able to use the arduino pins for outputs etc.

So my question is, can I use the Arduino Uno board together with avrdude and avr-gcc to program the on-board atmel328 in C? And thus being able to use the Arduino pins for output and input?

# Answer
You're question is not so clear. But from what I understood you are asking if you can program the Atmega328 with c using low level instruction and by setting manually all the registers in order to use IO ports of atmega. If that's what you're asking I will suggest you to use you're arduino ide to program the Atmega using register names as shown on the official datasheet. Doing so you can start learn the internal parts of the micro and at the same time you can avoid buying an external programmer. But if really want to load you're program or hex file you have to buy an external programmer. I hope that helped

PS if you are using the arduino ide and writing manually the registers remember not to set incorrectly the configuration registers because that will make you're Atmega useless and you will need to buy an external programmer.

Edit: For better understanding you can refer to this link. Programming arduino in c
> 1 votes

# Answer
Yes, the Uno is designed to be very simple to program. The only extra hardware you need is a USB cable to connect it to your computer.

If you're completely new to this then the simplest way to start is by following the official "Getting Started" guide. Note that the section on drivers is particularly important.

The guide explains how to use the official Arduino IDE for programming the microcontroller. It automatically handles compiling and uploading your code via gcc and avrdude. It's technically configured to compile as C++ code, but plain C code should be fine too.

I don't recommend that IDE for long-term use though as it's really only aimed at beginners (it has a number of limitations and other problems). Using the command-line tools directly is certainly possible if you'd prefer that. However, you may also like to consider alternative IDEs which have support for Arduino plug-ins.
> 0 votes

---
Tags: avr, avrdude, avr-gcc
---


title: Error while saving data in text file

text:
# Question
Title: Error while saving data in text file
I created a function that saves the timestamp in a text file, but it saves unreadable. Full of invalid characters, example: **Ÿ@Â O ƒº!¥ Ÿ@Â O ƒº!¥ Ÿ@Â O ƒº!¥ Ÿ**

```
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"

RTC_Millis rtc;
File txt;
const char * getCurrentTimestamp()
{
    char dateBuffer[40];
    DateTime now = rtc.now();
    sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
    return dateBuffer;
}

void saveLog()
{
  txt = SD.open("dados.txt", FILE_WRITE);
  txt.print(getCurrentTimestamp());
  txt.close();
}

void setup() {
  pinMode(53, OUTPUT);
  SD.begin(4);
  Serial.begin(9600);
  rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {
  Serial.println(getCurrentTimestamp());
  saveLog();
  delay(1000);
}

```

My code is very simple, do not understand where I went wrong. if I copy the following code snippet for **saveData()** function and save the **dateBuffer** variable, everything works normally.

```
char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());

```

how to save the timestamp correctly in the file through the function **getCurrentTimestamp()** ?

# Answer
> 2 votes
Your function, `getCurrentTimestamp()` saves the date string in an automatic variable - it is on the function's stack frame which gets freed as soon as that function returns. Either `Serial.println()` or `savelog()` is overwriting it.

The proper way to do what you're trying to do is to make the buffer live for the duration of both function calls. One way is to use a global buffer. Another is to declare the buffer in `loop()` and pass it to both functions.

# Answer
> -1 votes
As far as I know you should use

```
text.write(getCurrentTime());

```

That because (if I'm not wrong) you need to send it as ASCII characters so the text editor will be able to read them in the right way.

---
Tags: arduino-mega, sd-card, rtc
---


# Question
Title: Use Arduino pro micro to program pro mini?
So I got a pro micro and 2 pro minis and I was wondering if I could use the pro micro to program my minis? Anyone has any links or guides on how to do this, if at all possible?

# Answer
I don't know if it will still work but I will suggest you this. As arduino micro is Leonardo compatible and you r two arduino minis are based on atmega328. You should be able to use the tutorial posted above to use micro as programmer for the two mini. Hope that helped.
> 1 votes

---
Tags: arduino-pro-mini, arduino-pro-micro
---


title: RTC MCP7940M not counting up

text:
# Question
Title: RTC MCP7940M not counting up
I'm able to set a time and to read it back without any problems but it doesn’t tick up. It stays the same. Even if I restart the serial monitor and thereby resets the buffer(?). So it seems to me that I'm able to set the registers but somehow the oscillator isn't working, do I have to tell it to use the external oscillator? Datasheet. Using Uno Rev3.

I've connected it like this:

Never mind the BAT54 diode and the "RTC+MCU\_VCC" node, its all just backup power from a capacitor. The supply voltage is alright.

The code I've been using is a modified version of this.

```
// SDA analog pin 4
// SCL analog pin 5

#include <Wire.h>
const int MCP7940 = 0x6F; // Address of MCP7940 see data sheets
const char* days[] =
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const char* months[] =
{"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December"};

// Initializes all values:
byte second = 0;
byte minute = 0;
byte hour = 0;
byte weekday = 0;
byte monthday = 0;
byte month = 0;
byte year = 0;

void setup() {
  Wire.begin();
  Serial.begin(9600);
  delay(2000); // This delay allows the MCU to read the current date and time.

  Serial.print("The current date and time is: ");
  printTime();
  Serial.println("Please change to newline ending the settings on the lower right of the Serial Monitor");
  Serial.println("Would you like to set the date and time now? Y/N");

  while (!Serial.available()) delay(10);
  if (Serial.read() == 'y' || Serial.read() == 'Y')

  // This set of functions allows the user to change the date and time
  {
    Serial.read();
    setTime();
    Serial.print("The current date and time is now: ");
    printTime();
  }

  Serial.println("Thank you.");
}

// Continuous function for converting bytes to decimals and vice versa
void loop() {
}
byte decToBcd(byte val) {
  return ((val/10*16) + (val%10));
}
byte bcdToDec(byte val) {
  return ((val/16*10) + (val%16));
}

// This set of codes is allows input of data
void setTime() {
  Serial.print("Please enter the current year, 00-99. - ");
  year = readByte();
  Serial.println(year);
  Serial.print("Please enter the current month, 1-12. - ");
  month = readByte();
  Serial.println(months[month-1]);
  Serial.print("Please enter the current day of the month, 1-31. - ");
  monthday = readByte();
  Serial.println(monthday);
  Serial.println("Please enter the current day of the week, 1-7.");
  Serial.print("1 Sun | 2 Mon | 3 Tues | 4 Weds | 5 Thu | 6 Fri | 7 Sat - ");
  weekday = readByte();
  Serial.println(days[weekday-1]);
  Serial.print("Please enter the current hour in 24hr format, 0-23. - ");
  hour = readByte();
  Serial.println(hour);
  Serial.print("Please enter the current minute, 0-59. - ");
  minute = readByte();
  Serial.println(minute);
  second = 0;
  Serial.println("The data has been entered.");

  // The following codes transmits the data to the RTC
  Wire.beginTransmission(MCP7940);
  Wire.write(byte(0));
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(weekday));
  Wire.write(decToBcd(monthday));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.write(byte(0));
  Wire.endTransmission();
  // Ends transmission of data
}

byte readByte() {
  while (!Serial.available()) delay(10);
  byte reading = 0;
  byte incomingByte = Serial.read();
  while (incomingByte != '\n') {
    if (incomingByte >= '0' && incomingByte <= '9')
      reading = reading * 10 + (incomingByte - '0');
    else;
    incomingByte = Serial.read();
  }
  Serial.flush();
  return reading;
}

void printTime() {
  char buffer[3];
  const char* AMPM = 0;
  readTime();
  Serial.print(days[weekday-1]);
  Serial.print(" ");
  Serial.print(months[month-1]);
  Serial.print(" ");
  Serial.print(monthday);
  Serial.print(", 20");
  Serial.print(year);
  Serial.print(" ");

  Serial.print(hour);
  Serial.print(":");

 Serial.print(minute);
 Serial.println();
}

void readTime() {
  Wire.beginTransmission(MCP7940);
  Wire.write(byte(0));
  Wire.endTransmission();
  Wire.requestFrom(MCP7940, 7);
  second = bcdToDec(Wire.read());
  minute = bcdToDec(Wire.read());
  hour = bcdToDec(Wire.read());
  weekday = bcdToDec(Wire.read());
  monthday = bcdToDec(Wire.read());
  month = bcdToDec(Wire.read());
  year = bcdToDec(Wire.read());
}

```

# Answer
> 6 votes
Okey, I've been very tired when doing this but I think the problem was with bit 7 at adress 00h. The "seconds byte". That bit is called ST and turns on or off the oscillator. Doing a bitwise OR like this: `Wire.write(decToBcd(second) | 128);` sets it to "1" (128 = B10000000) and it's running now.

# Answer
> 0 votes
you have a small flaw in your readTime function. If you don't want very strange seconds from the device you should combine the two nibbles packed into the seconds byte. Like this:

```
void readTime() {
  Wire.beginTransmission(MCP7940);
  Wire.write(byte(0));
  Wire.endTransmission();
  Wire.requestFrom(MCP7940, 7);

  int rawsecond = Wire.read();
  second = bcdToDec( rawsecond & 112) + bcdToDec(rawsecond & 15);
  minute = bcdToDec(Wire.read());
  hour = bcdToDec(Wire.read());
  weekday = bcdToDec(Wire.read());
  monthday = bcdToDec(Wire.read());
  month = bcdToDec(Wire.read());
  year = bcdToDec(Wire.read());
}

```

Thanks for the sample - helped me quite a bit.

---
Tags: arduino-uno, i2c
---


# Question
Title: How can I make a garage door laser sensor?
I would like to make a sensor that detects when my car is clear of a certain point. So, when backing in my car to my garage, I would have a beam and sensor. When the beam is broken, an LED light would turn on and then when the beam gets through, the light turns off and I know that the car will clear the garage door.

I am pretty sure I have to use either an Arduino or Raspberry Pi, but I'm completely new to home automation. There are a few other things I'd like to do but this is a good starter.

I don't know where to start.

# Answer
I would recommend using laser and LDR. This will be very efficient and will not cause any problem due to light or ultrasonic deflecting. It will be precise by mm if you do thing right way. I made a simple porject back in 2005 using laser, LDR and relay.

Here what you need to do.

Get a laser, any laser will work. www.ebay.com/itm/6mm-650nm-DC-5V-5mW-Mini-Laser-Dot-shaped-Diode-Module-WL-Red-Copper-Head-Tube-/291089398593?pt=LH\_DefaultDomain\_2&hash=item43c647bb41

Get a PhotoResgister www.ebay.com/itm/Reliable-Hot-New-20-PCS-Photoresistor-GL5528-LDR-Photo-Resistors-Light-Dependent-/161434780484?pt=LH\_DefaultDomain\_2&hash=item2596434344

Put ldr in the dark box and drill a hole in it so that no other light can enter 2mm diameter hole will work.

Connect the LRD to your board. Fire laser and change status of indicator led by the value of ldr.

Check this link for refrence www.instructables.com/id/Arduino-Laser-Tripwire/?ALLSTEPS
> 5 votes

# Answer
I am pretty sure that Arduino would be enough for this project since the proper computation should not be that complex. Arduino Uno seems to be the simplest to start, at the same time not being too big for your application domain. However, you could also consider some smaller Arduino model, there would not be any "computational power" problem probably.

You could use an Infrared Proximity Sensor to check whether a car is present or not, here is a link that could be useful for this: http://arduinomega.blogspot.it/2011/05/infrared-long-range-sensor-gift-of.html

In this way, the system would light ON one or more LED(s) whenever the measured distance turns out to be less than some threshold value that you decide (maybe using a test-driven approach), and then light it/them OFF once the distance returns over the fixed threshold.

Hope this will be helpful.
> 1 votes

# Answer
I cant make out from the picture if you have consider this thought. Install sensor at height so car tail breaks the beam. Also It might not be ideal solution if you have multiple car lets say one Range rover SUV and another hatchback. You might want to consider having multiple sensor from ground to around 4-5 feet.
> 1 votes

# Answer
You want a light sensor like at http://rookieelectronics.com/light-sensor-using-arduino/ \- the usual way is infrared (same as remote controls), so you can't see it. You might want to blink the light, to get a more accurate signal (i.e. turn the led on; test the brightness; turn it off; test the brightness; find the difference) in different light conditions.

Personally, I would probably use a http://www.dx.com/p/hc-sr04-ultrasonic-sensor-distance-measuring-module-133696#.VRH9k3WjlIc Ultrasonic distance sensor - but there are lots of ways to accomplish this.

Not an Arduino answer, but.... a friend of mine put his car in the exact place it should be, then hung a tennis ball from the roof, at the right place so it just touches the windscreen. Now, when he pulls into the car, he moves forward until the tennis ball touches his windscreen, and he knows he's in exactly the right place.
> 0 votes

# Answer
I know some projects are just for the sake of the project alone but have you considered this no-tech solution?

http://www.instructables.com/id/Automatic-garage-parking-aid/
> 0 votes

---
Tags: sensors, led
---


title: How to Display data from Strings?

text:
# Question
Title: How to Display data from Strings?
I am working in an interactive project in displaying texts in POV which people can click to generate different texts automatically.

I wrote a String to store the text first, but it seems cannot display it. Then I change the code to use `char*` to store the text, but it still does not work.

Can anybody help to solve this problem....?

```
char* myStrings[] = {
  "a", "c", "d", "f",
  "b", "e", "v", "B", "C"];

```

The code:

```
loop(){

  //xbee
  // potVal = analogueRead(potPin);
  // xbee.println(potVal);
  for (int t=0; i<sizeof(myStrings)-1; i++) {
    displayChar(myStrings[i];
  }
  for (int i=0;i<7; i++)
    digitalWrite(leds[i],LOW);
  delay(10);

```

# Answer
Like the error message says, each entry is a `char*`. Convert it to an array of characters instead.
> 1 votes

# Answer
First thing, in C++ (or C) a character in single quotes is just a single lone character, but any characters in double quotes is a string literal. for example `"hello"` is a `const char[6]` containing the characters `'w'`,`'o'`,`'r'`,`'l'`,`'d'`,`'\0'`. That extra `'\0'` is the null terminator that makes an array of chars into a c-string.

Your code is making a variable

```
char* myStrings[] = { "a", "c", ... };

```

This is an array of `char*`, which means each element is a `char*`, which in turn means each element is a full string (in your case each has 2 characters).

You want an array of single characters, which means you either drop the `*` in `char*`, or drop the `[]` in `myStrings[]`, and use either an array of single characters `{'a','b',...}`, or a single string literal `"acdfbevBC"`. Any of these lines will work in your code:

```
const char * myStrings = "acdfbevBC";
char myStrings[] = "acdfbevBC";
char myStrings[] = { 'a', 'c', 'd', ... 'C', '\0'};

```

If you never plan to print `myStrings` as a unified string, you can leave off the `'\0'`, the null terminator is there so functions that you pass it to know when it stops without you having to explicitly pass how long the string is.

Also, the first line is `const char *` because you should never overwrite a string literal. `char myStrings[]` is fine without const because the compiler is using the literal to initialize an array that gets its own place in memory, not making `myStrings` point into a separate cache of string literals.

Check out cpp reference's details here for more details on string literals.
> 1 votes

---
Tags: arduino-uno, programming, string
---


# Question
Title: Send multiple int values from Python to Arduino using pySerial
I'm trying to send 3 ints in the range of 0-180 from Python to the Arduino Uno device using pySerial (py3K). I have managed to send 1 int by using python's struct lib (not sure if it's the best or fastest way but it works).

However I'm failing to send more than 1 and every example online seems to stop at 1.

Here's the simplified code. The task is to send servo0-servo4 to the Arduino and apply those values to the corresponding servos.

Python Code

```
import serial
import struct
import time

bge.arduino = serial.Serial('/dev/ttyACM0', 9600)

# let it initialize
time.sleep(2)

# send the first int in binary format
bge.arduino.write(struct.pack('>B', 45))

```

Arduino code

```
#include <Servo.h>
Servo servo0;
Servo servo1;
Servo servo2;

void setup(){
  Serial.begin(9600);
  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  if(Serial.available()){
    int message = Serial.read();
    // control the servo
    servo0.write(message);
  }
}

```

# Answer
> 2 votes
I guess I'll answer my own question for anyone else having this issue. What I did was:

Python:

```
# write to arduino as raw binary
bge.arduino.write(struct.pack('>BBB',45,90,180))

```

Arduino:

```
#include <Servo.h>

Servo servo0;
Servo servo1;
Servo servo2;

// create array
int incoming[2];

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

  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  while(Serial.available() >= 3){
    // fill array
    for (int i = 0; i < 3; i++){
      incoming[i] = Serial.read();
    }
    // use the values
    servo0.write(incoming[0]);
    servo1.write(incoming[1]);
    servo2.write(incoming[2]);
  }
}

```

# Answer
> 0 votes
```
void loop(){
  if(Serial.available() >= 3){
    // fill array
    for (int i = 0; i < 3; i++){
      incoming[i] = Serial.read();
    }
    // use the values
    servo0.write(incoming[0]);
    servo1.write(incoming[1]);
    servo2.write(incoming[2]);
  }
}

```

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


title: How can I execute a shell command?

text:
# Question
Title: How can I execute a shell command?
This page says to run a shell command I need a "proxy code" running on my computer (Linux Ubuntu). What do they mean by this, and how should I make one?

# Answer
> 3 votes
I'm not familiar with the term *proxy code,* but I'm assuming that it's a piece of code on your computer that acts as a man in the middle.

You cannot directly use Arduino to run a shell command, so you'll need to create a program on your computer that listens to **serial** and then executes a command.

For the "proxy code" Python would be a good choice because of the **pySerial library** that plays nicely with Arduino. It seems fairly easy to execute a shell command with Python.

As per the Arduino code, something like this would work good:

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

loop() {
  if(state == true) {
    Serial.print('A');
  }
}

```

---
Tags: serial
---


# Question
Title: setup() resets from loop, when I add parameters to http get `?identity=%2B0123456789&identityType=1`
I am trying to call a HTTP GET using my Arduino via SIM900A.

When I run the commands manually via the USB port, I am able to get the commands to run. Now, when I put the same sequence on arduino, the `setup()` is called repeatedly after the `sendATcommand(httpAuthCommand, "OK", 2000);`. Looks like a reset issue.

I read, this link to put all my code into `loop` to avoid the `setup()` reset issue. But seems like this is did not fix the issue.

I have debugged it to this one change.

**This Works**

```
char httpAuthCommand[] = "AT+HTTPPARA=\"URL\",\"http://www.m2msupport.net/m2msupport/http_get_test.php\"" ;

```

**This Does Not work**

```
char httpAuthCommand[] = "AT+HTTPPARA=\"URL\",\"http://1.1.1.1:8080/mytomcatservice/mypath/mycommand/Request?identity=%2B1234567890&identityType=1\"" ;

```

I debugged this a bit more, it does not work when I add `?identity=%2B0123456789&identityType=1` to the httpAuthCommand. Something crazy while sending parameters ??

**In loop()**

```
sendATcommand(httpAuthCommand, "OK", 2000);

```

**sendATcommand method**

```
int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout){

    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;
    memset(response, '\0', 100);    // Initialice the string
    delay(100);
    while( Serial.available() > 0) Serial.read();    // Clean the input buffer
    Serial.println(ATcommand);    // Send the AT command
    x = 0;
    previous = millis();
    // this loop waits for the answer
    do{
        // if there are data in the UART input buffer, reads it and checks for the asnwer
        if(Serial.available() != 0){
            response[x] = Serial.read();
            x++;
            // check if the desired answer is in the response of the module
            if (strstr(response, expected_answer) != NULL)
            {
                answer = 1;
            }
        }
    // Waits for the asnwer with time out
    }while((answer == 0) && ((millis() - previous) < timeout));

    return answer;
}

```

Raw commands work on Chrome

> http://www.m2msupport.net/m2msupport/http\_get\_test.php
>
> http://1.1.1.1:8080/mytomcatservice/mypath/mycommand/Request?identity=%2B918177900460&identityType=1

**My Guess**

I am missing some escape sequence characters in the command (especially in the parameters section `?identity=%2B0123456789&identityType=1`).

# Answer
> 1 votes
"Something crazy while sending parameters ??"

Possibly your power supply is to weak so 5V drops low and the processor resets when the transmitter sends a message.

# Answer
> 1 votes
Could you have exceeded the rather limited RAM? First experiment: Replace the added string with "xxx....x". If you have the same problem, then it's not the contents of the string but its length. Second experiment (or jump straight to this one): Compile your strings in flash instead of in RAM. Note this will only help if you have a number of them, since your code will have to copy each one to RAM (at run-time) in order to use it, taking up some of the space you had saved. If there is only one string moved to flash, your code will need a temporary buffer of equal size (though only during the actual print call). A possible way around this is to break up the long string into a number of short ones, put all of them in flash, then print them sequentially at run time. That will need a buffer only as large as your largest substring. The cost will be increased use of flash, both for string storage and for the extra number of print calls; and slightly slower execution (probably not an issue).

This may be telling you that you need a more capable processor (one with more RAM space) or that you need to start getting creative about fitting your application into the one you've got.

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


# Question
Title: Where are these capacitors on the arduino schematic?
My arduino has these two capacitors

But I can't find any 47uf capacitors on the schematic. Is this not the value but instead a code? Where are these in the schematic?

# Answer
**What:** Looking at the schematic that you provided, it seems likely that they serve as C6 & C7.

**Why:** These are shown as 100 uF each and act as "filter" capacitors for IC4, the 5V regulator.
Within certain limits, such capacitors are not critical in value, and the manufacturer has probably decided that a factor of in the capacitance is probably acceptable.
They are probably correct :-).

**How to check:** You can check this yourself with an Ohm-meter set to the lowest Ohm range available - often = 200 Ohms max.

Turn off power to the board and leave it off for say 5 minutes to allow capacitors to discharge.
Locate I4 and find its input and output pins or tracks leading to them. You can often get ohmic connections at vias as the tracks change board layers.
IC4 pin1 will be grounded.
One lead of C6 & C7 are also grounded.
The pad you can see in your photo on the board edge side of the caaps is probably the -ve terminals (about 99%+ likely) (and they match the can markings) and the "stippled" surface is almost certainly system ground.

If you can confirm that the two caps are connected to ground as and where described above, then:

Apply Ohm meter probes between the non ground lead of a capacitor and each non-ground pin in turn of IC4. One of them will be a low resistance connection if they are C6 & C7. Check the other capacitor - it should connect to the other side of IC4.
Reversing the meter leads in each case may give somewhat different readings for non-hard-connected points but should be low and consistent for hard-connected by a track points.
> 4 votes

---
Tags: power
---


# Question
Title: How to share a library on Arduino Playground?
I have written an ISR-based timer library for Arduino Uno and I would like to share it on the website and get it reviewed.

But I am stuck on how to post it to playground.

# Answer
> 5 votes
The Arduino Playground library list is a wiki page (like everything on the playground). That means anyone can log in to edit it and add links to their own libraries. The "Log In" and "Sign Up" links are at the top right of the Arduino site. When you first go to edit a Playground page you'll be taken to a "Password required" page but don't worry, this is only to prevent spam and the password is pre-filled. You only need to click the "I'm not a robot" checkbox, wait for the green checkmark to appear, then click "Submit".

There are a couple of important things to note though. Firstly, the Playground library list isn't there for getting your work reviewed. It's a place to post things that are functional and ready to be used by other people. If you need someone to help with your project then you can maybe post on the Arduino forums. Alternatively, if you have specific questions, you can post here on Arduino SE.

If you're ready to post your library online, you also have to be aware that the Playground itself won't host your code. You can put a link there and maybe some documentation. However, you'll need to host your code somewhere else, such as Github.

---
Tags: library
---


# Question
Title: Portable power for an UNO with a nrf24l01+ attached?
Okay so I have an UNO that has an nrf24l01+ attached. I want it to be completely wireless so free of the 5v USB power and the 12V wall plug. In this case what can I use? I do not wish to plug the power directly into the Vin as I am relatively new and afraid that it might fry the board. So I wish to plug it into the barrel jack. So I have read that using a 9v battery to power UNO is a waste of power as most of the power is translated into heat. Also, using 4 AA batteries seem to be a good solution except that I'm not sure if it has enough power for nrf24l01+ as I've read that an arduino with nrf24l01+ on batteries creates an unstable wireless node. I would like some help on what I can power the UNO with.

# Answer
I've used the usb battery chargers (marketed to recharge cell phones) with great success on many different Arduino boards. They come in a variety of mAH capacities and are easily recharged with any powered USB port/power adapter.

Here's a link to one I've used. (I'm not affiliated with Duracell in any way).

http://ww2.duracell.com/en-US/product/instant-usb-charger.jspx
> 3 votes

# Answer
Firstly if you only need short runs, go with the usb battery pack answer, but if you need the longest time from least batteries:

As has been pointed out, for best battery consumption an arduino board is not efficient due to power regulators and led lights. For best performance you want a standalone 328 chip with its BOD (brown out detector) reduced to 1.8v and then you can run it and the nrf24 chip off 2x AA batteries.

But all this might be a bit beyond you.

One thing though that will help your battery life is a PNP transistor or Mosfet on the +ve of your nrf24l01+ module triggered by a arduino io pin. as these power amplified versions dont sleep (per say, the chip does but not the PA) so it will always be consuming a large amount of power regardless of state. So just use your io pin to power it on and off for each use.

(that is unless you need it on always for recieving, in which case this wont help)
> 0 votes

---
Tags: arduino-uno, power, battery, nrf24l01+
---


# Question
Title: Unusual behaviour when moving data to PROGMEM
I've got some working code with a definition that looks like this:

```
const unsigned char DynTextPositions[10][4][4] = {
    ...
};

```

Which is defined / referenced via a header:

```
#include <avr/pgmspace.h>
#ifndef DYNTEXTPOS_H
#define DYNTEXTPOS_H

extern const unsigned char DynTextPositions[10][4][4];

#endif

```

This data is being fed into a rendering function which draws lines based on the given positions. The data is read as follows:

```
float deltas[4][4];
// ...
deltas[n][k] = float(DynTextPositions[c+1][n][k] - DynTextPositions[c][n][k]) / 32.0;

```

As-is, this works just fine, as long as I've got my other scenes commented out. When I uncomment them, the combined data size seems to overflow the data segment. This is expected, because there's a fair bit of data, so I'm trying to move the `DynTextPositions` data into `PROGMEM`.

I've got `PROGMEM` working with some bitmaps, but it doesn't seem to work here. An example definition for a working bitmap is as follows:

```
PROGMEM const unsigned char ArduinoLogo[] = { ... };

```

However, as soon as I apply the `PROGMEM` attribute to `DynTextPositions` the rendering code seems to freak out - the positions appear to be all off-screen and completely wrong.

The only thing I can think of is that, for some reason, the data is either being considered signed rather than unsigned, or is getting corrupted along the way. Either that or the nested array is somehow being treated as a set of pointers.

Any idea why this might be?

# Answer
Including `<avr/pgmspace.h>` and using the `PROGMEM` qualifier macro are only two of the steps required in order to get this to work. Since the data will no longer be available via the data bus you will need to use the various `pgm_read_*()` macros or `*_P*()` functions defined in `avr/pgmspace.h`. These work by using the appropriate assembly code instructions to access data stored in program space, i.e. flash, on the MCU.

Under GCC 4.7 or higher when writing C code, the `__flash` named address space is available. Variables declared within this namespace do not require any additional steps to access them. Note that the Arduino IDE compiles as C++, and hence does not make this (or any of the others) available.
> 3 votes

---
Tags: arduino-uno, avr, progmem
---


title: GSM dongle instead of GSM shield?

text:
# Question
Title: GSM dongle instead of GSM shield?
I googled for this problem many times and ended up with no results, so I decided to post it here.

Can we use a GSM Dongle (usb dongle) instead of a GSM shield (like SIM900 module) to send and receive SMS in Arduino? If so how it is possible?

# Answer
**YES you can with an Arduino Yùn** The dongle will have to be handled by the linux part of the board and doing so will leave you all the I/O pin free for your project.

You might want to check out this for the howto:

https://n00bsys0p.wordpress.com/2009/08/26/sending-recieving-sms-with-a-3g-device-in-linux/
> 2 votes

# Answer
Not directly. The standard Arduino Uno doesn't have the hardware/software necessary to act as a USB host, which means it can't talk directly to other USB devices.

You *might* be able to get it work via a USB Host Shield. I don't know how compatible that is with GSM dongles though because I assume you can't install drivers on it. Additionally, if you're using a shield anyway, you might as well use a GSM shield.

If you're able to get an alternative board then another possibility might be the Arduino Yún. It has a USB host built-in which is operated by the Linux part of the board. I don't know for certain that it would handle a GSM dongle, but it may be worth looking into.
> 1 votes

# Answer
You can search for, or create your own 'breakout' board.

You could actually get an sim900 chip running on a breadboard. I think this might be most usefull to you: http://img01.cp.aliimg.com/imgextra/i2/87365807/T267qSXa4aXXXXXXXX\_!!87365807.jpg

http://www.aliexpress.com/store/product/Gprs-module-gsm-gprs-module-sim900-development-board-mini-v2-module/124015\_1030035160.html

Though this one is quite expensive. (As it doesn't even has a SIM900 on it?) There is no reason the SIM900 can't work withouth arduino board.. But the reason it's used with an 'shield' is because it's easier to connect and enables to draw power from the arduino. (You do need a good supply for the sim900, it can have peak-power levels, which might reset your arduino)

---

So yes, you could make your own dongle based on a SIM900! Which works great for Embedded/Realtime (UNO).

But also, you might want to use a board that has Linux (But bear in mind that this is 'completely' different from the UNO. Check the other answer in this case.

Edited, Chris explained me you simply can't use an usb device withouth a USB host with USB driving software.
> 0 votes

# Answer
Usually, these usb dongles consist of two parts: the usb part, and the gsm part. If you can find the spec on the gsm chip, you might be able to bypass the usb part.

Unfortunately, these circuits are usually surface mount - tiny pins, tiny traces, and lots of them. Soldering them will probably be tricky.
> 0 votes

# Answer
also im in the try of that.YOU HAVE TO USE USB TO SERIAL CONVERTOR CIRCUIT TO ACCESS ARDUINO BY UART (mosi....... miso) connections .and the software in the dongle is the problem here.the difference between the gsm shield and the dongle is .........the SOFTWARE FIREWALL you have to flash the dongle by your own risk.........try this
> -1 votes

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


title: SoftwareSerial Struggles

text:
# Question
Title: SoftwareSerial Struggles
Just trying to understand and use the SoftwareSerial

I want to connect a WiFi Module (ESP8266) If I send an AT command to the module I would like to print a response on my pc screen in the serial monitor

Some example code it tried

```
   SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     Serial.begin(57600);
     Serial.setTimeout(5000);
     dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     dbgSerial.println("ESP8266 Demo");
     //test if the module is ready
     Serial.println("AT+RST");
     delay(1000);
     if(Serial.find("ready"))
     {
       dbgSerial.println("Module is ready");

```

I would like to receive ready in the serial

# Answer
> 1 votes
Looks like you are swapping the use of `Serial` and `dbgSerial`. I think you mean to use `Serial` to print to the computer and `dbgSerial` to communicate with your module. `Serial.println` should display the message in the terminal on your computer.

---
Tags: softwareserial, esp8266
---