body:
Am new at this but I am working on a similar work, it is possible to use the pin 0 for your keypad, the pin is a RX pin by default making the pins(0,2,3,4,5,6,7).

As for the LCD I would suggest you use an i2c backpack, it is a parallel to serial converter and means you would only need to use 2 pins (SDA, SCL which would be connected to pin A4, A5)

Try the code below for the keypad (The code is if you have an i2c backpack)

    #include <Wire.h>
    #include <Keypad.h> //keypad library
    #include <LiquidCrystal_I2C.h> //library for the backpack

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

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns

    //define the Symbols on the buttons of the keypads
      char hexaKeys[COLS][ROWS] = {
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'*','0','#'}
    };

    byte rowPins[ROWS] = {0, 2, 3, 4}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {5, 6, 7, 8}; //connect to the column pinouts of the keypad

    //initialize an instance of class NewKeypad
    Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup(){
      Serial.begin(9600);
      lcd.begin(16,2);
      for(int i = 0; i< 3; i++)
      {
        lcd.backlight();  delay(250);
        lcd.noBacklight();  delay(250);
      }
      lcd.backlight();
    }

    void loop(){

      char customKey = customKeypad.getKey();

      if (customKey){
        lcd.print(customKey);
      }
    }


sender: user

message:
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.

sender: assistant

body:
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.

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

    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](http://en.wikipedia.org/wiki/Name_mangling) and you
would need to use the mangled name in the assembly source.


message:
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][1]
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();
     }

     }

  [1]: http://arduino.cc/en/main/standalone

body:
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?


message:
Passing a long string from SoftwareSerial to Serial

I'm currently playing around with a [GPRS shield](http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0) 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:

<!-- language: lang-cpp -->

    #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`](http://signusx.com/sim900-scanning-all-visible-cell-towers-from-all-gsm-operators/) 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:

![enter image description here][1]

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?

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

body:
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.


message:
Determining power consumption with Arduino and JeeLib

I built a basic LED blinker to serve as a car theft deterrent. Originally I was using a 9V battery and delay() but I've refined my approach to consume less power. Here's my code, utilizing the JeeLib library:

    #include <JeeLib.h>

    int led = 13;
    ISR(WDT_vect) { Sleepy::watchdogEvent(); }

    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
    }

    void loop() {
      blink_quick();
      blink_quick();
      Sleepy::loseSomeTime(8000);
    }
    void blink_quick() {
      digitalWrite(led, HIGH);
      Sleepy::loseSomeTime(250);
      digitalWrite(led, LOW);
      Sleepy::loseSomeTime(250);
    }

It just blinks twice every 8 seconds. I also used 4 AA batteries as they have a higher amperage rating. How long should this system work before I need to replace the batteries?

My thinking is that AA batteries offer 2000mAh and an Arduino typically consumes about 45mA on average. If I were running the above code with delay() instead of the JeeLib functions, it would last for 44 hours. Let's call one cycle the two blinks and the following 8 seconds of rest. I am confused about how long I should factor in for the digitalWrite(led, HIGH) and the corresponding 'low' call, because the rest of the time, the circuit is using JeeLib. I am just interested in figuring out how long I can let this run without changing the batteries, and admittedly I am not experienced enough to tell definitively.

Thanks!

body:
What board are you using? For example, the Uno has a lot of other components that will consume power, even if you sleep the main processor. Instead use something like a Pro Mini.

You can bypass the voltage regulator, and just supply 4.5v by using 3 AA batteries. You can even use just 2 AAs if you have the 3.3v version. The lower the voltage the less current the ATMega uses.

Most importantly, measuring the power consumption using a multimeter. Measure the current the led uses. Disconnect the led, and measure how much the arduino uses. Use this handy [Battery Life Calculator](http://oregonembedded.com/batterycalc.htm), and just fill in those numbers.

Run the led with the lowest current, where the led is still visible enough. Running a power-led at just 1mA will still give a decent amount of light.

In your situation, if coded correctly, power usage of the ATMega is negligible. The only real power user is the led. If you run the led at 1mA, and use a set of AA batteries, you get around 3.5 years of running time, no problem.


body:
As mentioned in another answer use a multimeter to measure.  However I would recommend using the cars battery to power the system.  A parasitic draw on a cars battery of under 1 amp is considered acceptable (per what I learned in school).  A parasitic draw is current used while the car is off.  Get a clamp ammeter and check your parasitic draw and if you have the available amperage to spare run it from your battery. To check your parasitic draw place the clamp around the ground wire (or multiple ground wires) at the battery terminal.

If you run it from your car battery you will never have to worry about changing the battery and it becomes a set and forget system.


body:
I have a lot of detail about here: [Power saving techniques for microprocessors](http://www.gammon.com.au/power)

> Let's call one cycle the two blinks and the following 8 seconds of rest. I am confused about how long I should factor in for the digitalWrite(led, HIGH) and the corresponding 'low' call, because the rest of the time, the circuit is using JeeLib.

To answer this specific question, we can work out a "power budget" by taking the large consumption time (eg. the LED being on) and working out how much that is, as a fraction.

So in your case you have the LED on for 500 ms every 8 seconds. That is:

    8 / 0.5 = 16

That is, 1/16th of the time. Or, putting it another way:

    0.5 / 8 = 0.0625

So, let's say the LEDs use 20 mA. The *average* consumption then is:

    0.020 * 0.0625 = 0.00125 A (1.25 mA)

And let's assume that while asleep it uses 1 mA. So the total consumption on average is:

    1 + 1.25 = 2.25 mA

So if you have a 2000 mAh battery, you would get:

     2000 / 2.25 = 888.88  hours

However as others have pointed out, this is pretty meaningless if you use a development board. The on-board LED, the voltage regulator, the USB chip etc. will use much more power than you save by going to sleep. You have to move to a low-power or custom design, which minimizes these extra effects.

With careful design you should be able to get the sleep usage down to around 6 µA with the watchdog timer to wake you up.


message:
Thin battery to power arduino micro with nRF8001?

I'm building a project which needs to fit in a wallet. I have an Arduino Micro hooked up to a [nRF8001][1]. I attempted three button cells wired in series, which provided a solid 7.5 volts, but only `20mA`.

A 9V battery successfully powers it, but that's too big to fit in a wallet. I was considering using an `A27` battery, but even that's thicker than I would like.

Is there any battery I can use that's a reasonable thickness, and won't explode on me? Thanks!...

  [1]: http://www.adafruit.com/product/1697

body:
Either of these two are pretty good depending on how long you want it to live and how much current your device draws:

[https://www.sparkfun.com/products/731][1]

[https://www.sparkfun.com/products/10718][2]

  [1]: https://www.sparkfun.com/products/731
  [2]: https://www.sparkfun.com/products/10718

You can still probably power the micro from these even though they're 3.7v. When charged they'll be closer to 4.2v and it will still probably run down to 3.5v anyway.

Or you could just put two in series to increase the voltage


body:
I run my projects directly from a 3v CR2032 lithium cell. Bypassing any voltage regulator. You could use something like a I'd get a 3.3v arduino, something like a Arduino Pro Mini. (You can also use your micro, but you'd have to "underclock" them, as the ATMega32u4 isn't necessarily capable of running 16Mhz at 3V.)

By bypassing the voltage regulator, you don't get any of the losses.


body: You can use rechargeable `Ni-Cd` batteries of 3 AAA size cells with wired connection.There are also small 4V rechargeable `lead-acid` batteries,which are mostly used in led torch.


body: I think you should use a 3.7v mini battery that are around 200-300mAh capacity. These batteries are variable on online stores and are very thin. Now as you require 5v there are mini DC-DC boost converters available what you can use with them.


message:
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.

body: [PowerSwitch Tail](http://www.powerswitchtail.com/Pages/default.aspx) is what you are looking for.


message:
nrf24l01+ does not work with a battery, or very unreliably

For a project in progress, I have an Arduino UNO sending a message when a condition occurs, and a Raspberry Pi that listens to it. Both are fitted with NRF24L01+ modules with antennas.

It works perfectly when the Arduino is powered from a wall socket, for instance using a 9V / 1A power supply. But when I try it with a [9V battery][1] (which is supposed to supply 600 mAh), the Raspberry Pi receives only 1/10 of the messages.

Could you tell me:

 1. Why this happens
 2. How I can solve this problem (software / wiring / capacitor / ...)
 3. What would be the best way to power an Arduino whose only job is to detect that a switch closes, and emit a message over the air

[Here][2] is the code of the emitter (Arduino). And [there][3] is the code of the receiver (Raspberry Pi).

Thank you.

  [1]: http://data.energizer.com/PDFs/6LR61PL_EU.pdf
  [2]: http://pastebin.com/S0BvhiMr
  [3]: http://pastebin.com/PgcCYxNc

body:
According to the [datasheet][1] of another 9V battery, I should not expect more than 30 - 50 mA of constant current. This is probably the reason why.

Long story made short: One can not power a NRFL01+ reliably with a 9V battery.
I'd be better off using 2xAA batteries.

  [1]: http://data.energizer.com/PDFs/522.pdf


body: Another thing to consider is that a nrf24l01+ chip at full power will potentially be pulling more current than your 5v reg can supply, try a lower power setting on the PA.


body:
Add a 100uf capacitor between ground and 3.3v directly on the nrf breakout. They're very susceptible to noise on the power supply. I had issues with the same thing and this solved it. Also, make sure you're powering from 3.3v. Also make sure you solder the negative to the negative!

![see capacitor placement][1]

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


body: I got a similar problem while not exactly the same but it may include the solution. I have a arduino nano with the nrf24l01 with the adapter and antenna (PA LNA). Transmitter work well but the receiver only work/receive data when plug by USB to the computer, not using an external battery (by USB too). I search for hours looking for a solution (the capa, the robin nrf24 tutorial, SPI problem, power supply problem, trying with another nrf24 module...) without finding any reason for this unexpected behaviour. Then i figured out that  the USB cable that i use make a big difference: two were preventing transmission, one allowing transmission (the 3 cables perfectly work to upload sketch): i was thinking to a ground plan problem due to different size of USB cable but then i check the voltage arriving on the adapter of the nrf24l01. It was 4.7V for the cables that doesn't work, 4.6 with the cable that work. Then i just bypass the arduino alimentation of the nrf24l01  by using a regulated power supply directly applied on vcc and gnd of the adapter. By manually adjusting the voltage i could trigger the transmission with 4.5 V and stops it at 4.7V. I don't know why it's work like this (defect of the 5V to 3.3V regulator of the adapter?) but that do the trick for me. I know that it looks like a very unlikely solution for you but if you are desperate after hours of research, take a minute to put a voltmeter just before the adapter to look for difference in  the voltage in the condition where it works versus where it doesn't work.


message:
Is there an Arduino Simulator or Emulator that runs on OS X?

Is there an Arduino Simulator or Emulator or cross-compiler to native Mac executable that runs directly under Mac OS X, and does **NOT** require a Windows or Linux VM or an active internet connection for running in the cloud?

There **are** previous questions here on similar topics, but they do not seem to address exactly this particular use case subset.

body:
[Arduino CodeBlocks][1] plug-in has an Arduino simulator. Be carefull when setting it up and use full paths, it's easy to mess up, but works beautifully once done.

  [1]: https://github.com/provideyourown/CodeBlocks-Arduino/


body:
I am using the [Wokwi Arduino simulator][1] for a long time. It runs on all three platforms. Mobile, Windows OS, and macOS.
I have checked the working of the simulator in both Android and iPhone. Both give a good performance as well.

  [1]: https://wokwi.com


message:
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?

body:
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.


message:
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?

body: 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.


message:
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?

body:
I don't know if it will still work but I will suggest you [this][1].
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]: http://www.instructables.com/id/Arduino-Leonardo-as-Isp/step5/Target-Atmel-Microcontroller-1-Atmega328p-burning-/


message:
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.

body:
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.


body:
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.


message:
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?

body:
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.


message:
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()
     {
     }

body:
(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.


message:
Will the arduino power autoselection logic short the regulated 5V and the USB 5V?

From the reference design of the Arduino UNO r3, I find that USBVCC will be connected to +5V via mosfet T1 if Vin is below 6.6V.
Doesn't this short the two sources if Vin is just below 6.6V?
The datasheet for regulator U1 (NCP1117) mentions input range as low as 6.5V for the 5V version.

This question came to mind when researching if I can simultaneously power the arduino with USB and the 5V-pin. There are many warnings not to do so, and some say its ok anyway. I realise that this will short the USB 5V with my external 5V if Vin/PWRIN is not connected or less than 6.6V/~7.3V, but how bad is that considering that this may happen anyway by design (if the theory above is correct)?

body: If you connect a power supply directly to 5V pin on gpio it bypasses voltage regulator hence your board may be damaged if the power supply generates  spikes. But you can power it using 5V supply directly to 5V pin provided you are using a good quality power supply. If you are supplying the power via Vin or power jack there is additional voltage regulator in path giving extra security. Thus you need more 6.5v so as the output of the regulator is 5v. If you supply 5v to Vin the output is nearly 4v thus the board doesn't get enough power.


message:
Operating Sharp memory LCD with Arduino

I am trying to write to Sharp memory LCD "LS027B7DH01" which isn't going well for me. I didn't find any useful information for beginners. I just want to display any character on the LCD. Here's my code:

<!-- language: c -->

    #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);
       pinMode(SI,OUTPUT);
       digitalWrite(SCS,HIGH);
       tone(EXTCOMIN,40);
       SPI.setClockDivider(SPI_CLOCK_DIV16);
       SPI.setBitOrder(MSBFIRST);
       SPI.setDataMode(SPI_MODE0);
       SPI.begin();
       SPI.transfer(0×20);
       delay(3000);
    }

    void loop()
     {
       SPI.transfer(0×80);
       delay(3000);
       for (byte i=0; i<30;i++)
        {
           SPI.transfer(i+1);
           delay(3000);
          for(int j=0; j<50;j++)
           {
             SPI.transfer(0x0F);
             delay(3000);
           }
           delay(3000);
           SPI.transfer(0×00);
        }
        delay(3000);
        SPI.transfer(0×00);
      }

body:
As the page [Sharp Memory LCD Breakout A2][1] shows, it seems that you need some additional circuitry to drive the display, such as capacitors and resistors. This is why breakout boards are usually employed. Quoting the page:

> This is a simple breakout board for Sharp’s new Memory LCD displays (
> LS013B4DN02 and LS013B4DN04). It brings all pins to a 0.1″ header and
> provides necessary caps and resistors. The new revision A2 also adds
> an optional boost converter for those wanting to run 5V display from
> sub 3.3V supply.The footprints are there, but parts are not populated
> to save cost. I’ve also added silk labels to the header pins on the
> back. This is an open design under CC BY SA license.

Of course, you can always make your own breakout circuit. For example, you could reproduce the breakout board using a breadboard and some resistors and capacitors. The schematics are provided on that page for [A1][2]

![Sharp LCD Breakout A1][3]

 and [A2][4]

![Sharp LCD Breakout A2][5]

So, in short, either purchase a breakout board, or make one. Once you have done that , you can use the [CraftyCoders Arduino Library][6]

Hope that helps.

  [1]: http://kuzyatech.com/sharp-memory-lcd-breakout-a2
  [2]: http://kuzyatech.com/wp-content/uploads/2012/08/SharpLCD_BreakOutA1.pdf
  [3]: https://i.stack.imgur.com/0bKxA.png
  [4]: http://kuzyatech.com/wp-content/uploads/2012/09/DipTrace-Schematic-072012_SharpLCD_BreakOut_A2.pdf
  [5]: https://i.stack.imgur.com/EFj6b.png
  [6]: http://code.google.com/p/arduino-sharp-memory-lcd-gfx-library/


body:
I looked at this question as I too plan to drive a Sharp Memory LCD manually with my own code at some point.  From your question and comments I think you are going about it the wrong way, even if you are already very proficient with the electronics side of the task.

As mentioned, the breakout board is the easiest way to connect the screen and the library is the easiest way to program it.  I suggest you use both *initially* and then replace them one by one.  I did this when driving a 32x32 LED matrix.

Once you have a little bit of code running that displays what you want on the screen, try removing the breakout board and wiring the display yourself without changing the code at all.  If the display is not what you expect, you know the problem is in the wiring so you don't waste time looking into your code.

Once the wiring is sorted, start on the driver code.  Leave the wiring and your code that makes the display show what you want untouched so that you know any problems are in your driver code.  The other advantage of this is that you have the working library as reference for how the screen works and what signals to send with what sort of timing.

As a pointer to why your code is not doing what you expect, I *think* you may be misunderstanding how the screen works.  Your question and code suggest you may be trying to display ASCII characters on the screen which I believe can be done easily with some LCD displays but I'm fairly sure that these LCDs are not character based - you have to manually set or clear each individual dot.  I think the minimum number of dots you can set at a time is a full single line of the display.

In your code you have a delay of 3000ms after every byte send.  At that rate it would take 2mins 30secs just to transfer the data for a single line of the screen so maybe you are sending the correct data, but are not waiting long enough to see the results.  I've also read that you have to do something (sorry, not quite sure what) at least once per second to prevent problems with the screen - this suggests that taking over 2mins to send a line of data could not work as you expect.


message:
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

body:
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](https://github.com/mpflaga/Sparkfun-MP3-Player-Shield-Arduino-Library) and its [documentation](http://mpflaga.github.io/Sparkfun-MP3-Player-Shield-Arduino-Library/) noting that it also uses the more mature SdFat. As the stock SD library may be part of your problem.


message:
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)

body:
 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":

![enter image description here][1]

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

![enter image description here][2]

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

![enter image description here][3]

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:

![enter image description here][4]

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

![enter image description here][5]

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.

  [1]: https://i.stack.imgur.com/gPhH1.jpg
  [2]: https://i.stack.imgur.com/Cuc1E.jpg
  [3]: https://i.stack.imgur.com/MTTEJ.jpg
  [4]: https://i.stack.imgur.com/lQy8i.jpg
  [5]: https://i.stack.imgur.com/HLsHL.jpg


message:
If I have a group of Arduinos connected via I2C, can one Arduino cause the rest to freeze?

I have a group of four Arduino boards connected via I2C.  One is the master, which sends and receives values from all of the others.  I noticed that the Master will stop executing its loop if power is removed from one of the other Arduino boards.

Can one Arduino in a I2C group cause the rest to freeze?
Is there a way to prevent this?

I am using one of the Arduino boards to connect to a server via network shield and I don't want the other Arduino boards to be effected if the networked Arduino freezes.

body: I can say from personal experience, I had a similar event. I had a logic analyzer hooked up and was using it. I got the code working the way I wanted.  A day later when I tried it the code failed.  Turned to be because I had not powered up the logic analyzer and it was still hooked up.  If I unhooked it or powered it on everything worked fine.  This was on an Netduino BTW, but it leads me to believe (not being an electronics person per se) that yes it very possible if some unexpected load is on the I2C bus.


body:
There are a number of places in the standard Wire library where the code goes into a tight loop waiting for an interrupt to occur. If that is missed for some reason, it will loop indefinitely.

By removing power from one of your devices you may be introducing electrical conditions that prevent the I2C messages from being transmitted properly (possibly just noise). Alternatively the device may parasitically power up from the SDA/SCL data and then behave in unpredictable ways. It is probably unwise to do this.

There is an alternative I2C master library at http://dsscircuits.com/articles/arduino-i2c-master-library which does not hang (I believe it times out instead).


message:
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?

body:
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


body:
[Here](http://www.amazon.com/nRF24L01-Wireless-Transceiver-Arduino-Compatible/dp/B00E594ZX0/ref=sr_1_1?s=electronics&ie=UTF8&qid=1427168753&sr=1-1&keywords=2pcs+nRF24L01++2.4GHz+Wireless+Transceiver+Arduino+Compatible) 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.


message:
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.

![enter image description here][1]

I want to convert my 3D printer to CNC Router using my Dremel with Flexible shaft like this.
![enter image description here][2]
![enter image description here][3]

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.

  [1]: https://i.stack.imgur.com/pecNu.jpg
  [2]: https://i.stack.imgur.com/ZoGcp.jpg
  [3]: https://i.stack.imgur.com/KvhPF.jpg

body:
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.

* <http://www.w3schools.com/svg/default.asp>
  This link describes the SVG format, and it does a fairly decent job at it.
* <http://en.wikipedia.org/wiki/G-code>
* <http://en.wikipedia.org/wiki/STL_(file_format)>


message:
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.

body:
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


body:
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)


message:
time error in controlling a clock

I have [designed and 3d printed a clock][1].

I am controlling the clock using a Arduino sketch running on a Attiny2313. The stepper motor I am using is a 12v 1:12 ratio stepper. The total number of steps per revolution are 288.

The problem I am facing is that I am unable to get the time right. I have got the steps per revolution of the minute ring bang on, but some how the motor gains 10/11 minutes every 24 hours.

I have used a lot of the code from the stepper motor library. I am not using the stepper motor library as the code gets larger than what can fit into the 2k attiny memory.

Any help is appreciated.

    int number_of_steps = 288;
    int motor_pin_1 = 9;
    int motor_pin_2 = 10;
    int motor_pin_3 = 11;
    int motor_pin_4 = 12;
    int ledpin = 13;
    int delayTime = 4;
    int buttonPin = 4;
    int buttonState = 0;
    int enablepin = 8;
    int whatspeed = 40;
    int last_step_time =0;
    int step_number = 0;
    [color=red]int blinkDelay = 939; [/color]
    int step_delay = 60L * 1000L / number_of_steps / whatspeed;
    int step_direction = 0;
    void setup() {

     pinMode(motor_pin_1, OUTPUT);
     pinMode(motor_pin_2, OUTPUT);
     pinMode(motor_pin_3, OUTPUT);
     pinMode(motor_pin_4, OUTPUT);
     pinMode(buttonPin,INPUT);
     pinMode(ledpin, OUTPUT);
     pinMode(enablepin,OUTPUT);

    }

    void loop() {
     buttonState = digitalRead(buttonPin);
     if (buttonState ==HIGH){
       enablemotor();
       movestep(20);
       digitalWrite(ledpin,HIGH);
     }
     else{
       digitalWrite(ledpin,LOW);

       for (int xx = 0; xx<59;xx ++){

         enablemotor();
         movestep(42);
         //delay(100);
         motoroff();
         blinkk();
       }
       enablemotor();
       movestep(89);//85;

       motoroff();
       blinkk();
      //delay(3000);
     }
    }

    void enablemotor(){
     digitalWrite(enablepin,HIGH);
    }

    void movestep(int steps_to_move){
     int steps_left = abs(steps_to_move);

     if (steps_to_move > 0) {
       step_direction = 1;
     }
     if (steps_to_move < 0) {
       step_direction = 0;
     }

     while(steps_left > 0) {
       // if (millis() - last_step_time >= step_delay ) {
       //last_step_time = millis();
       if ( step_direction == 1 ){
         step_number++;
         delay(step_delay);
         if (step_number == number_of_steps) {
           step_number = 0;
         }
       }
       else {
         if (step_number ==0){
           step_number = number_of_steps;
         }
         step_number--;
       }
       steps_left--;

       stepmotor(step_number % 4);

       //}
     }
    }

    void stepmotor(int thisStep){

     switch (thisStep) {
     case 0:    // 1010
       digitalWrite(motor_pin_1, HIGH);
       digitalWrite(motor_pin_2, LOW);
       digitalWrite(motor_pin_3, HIGH);
       digitalWrite(motor_pin_4, LOW);
       break;
     case 1:    // 0110
       digitalWrite(motor_pin_1, LOW);
       digitalWrite(motor_pin_2, HIGH);
       digitalWrite(motor_pin_3, HIGH);
       digitalWrite(motor_pin_4, LOW);
       break;
     case 2:    //0101
       digitalWrite(motor_pin_1, LOW);
       digitalWrite(motor_pin_2, HIGH);
       digitalWrite(motor_pin_3, LOW);
       digitalWrite(motor_pin_4, HIGH);
       break;
     case 3:    //1001
       digitalWrite(motor_pin_1, HIGH);
       digitalWrite(motor_pin_2, LOW);
       digitalWrite(motor_pin_3, LOW);
       digitalWrite(motor_pin_4, HIGH);
       break;
     }

    }

    void blinkk(){
     for (int i = 0 ; i<30;i++){
       buttonState = digitalRead(buttonPin);
       if (buttonState ==HIGH){
         break;
       }
       else{
         digitalWrite(ledpin, HIGH);   // set the LED on
         delay(blinkDelay);  // 968           // wait for a second
         digitalWrite(ledpin, LOW);    // set the LED off
         delay(blinkDelay); //968
       }
     }
    }

    void motoroff(){
     digitalWrite(enablepin,LOW);
     digitalWrite(motor_pin_1, LOW);
     digitalWrite(motor_pin_2, LOW);
     digitalWrite(motor_pin_3, LOW);
     digitalWrite(motor_pin_4, LOW);

  [1]: http://www.thingiverse.com/thing:570797

body:
It is very difficult to accurately control timings with `delay()`,
because you have to account for the time needed to execute the rest of
the code, including interrupts. You can easily have better accuracy by
using `millis()` like this:

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

    static unsigned long last_step_time;
    unsigned long now = millis();
    if (now - last_step_time >= step_delay) {
        do_one_step();
        last_step_time += step_delay;
    }

This is almost what you have commented out in your own code, except that
`millis()` should be called only once per iteration, hence the `now`
variable.

This may still have less than perfect accuracy due to your clock source.
If your Arduino is clocked from a quartz you should be able to get
decent timing accuracy. If it is clocked from a ceramic oscillator you
are out of luck. In any case, you can always improve the accuracy by
calibrating your clock: you measure its drift and correct for it in
software. Then you have only to worry about thermal fluctuations of the
clock frequency, which should not be an issue with a quarts.

For best accuracy, you can use either an RTC or a watch crystal
connected directly to your ATmega chip. This last solution is only
possible if you go for a bare microcontroller, without the Arduino
board. See [this answer](https://arduino.stackexchange.com/a/9039)
for more details about this option, as well as the way to correct
for the drift in software.


body:
You should consider using hardware timers (`millis()` uses this, see answer of edgarBonnet.

Or you might want to use a Real Time (Calendar) Clock chip, which often has even better accuracy (some even adjust to temperature).

Also a possibility is using a GPS module, and using the GPS time which should be extremely accurate and will not drift (since it's synchronized).

Post on AVR timer precision (hardware timers):
http://www.seanet.com/~karllunt/interval.html

RTC (Real Time Clock) example:
http://www.instructables.com/id/Real-Time-Clock-DS1302/

GPS example:
http://blog.arduino.cc/2014/01/06/simple-arduino-micro-gps-clock-project-arduinomicromonday/


message:
What is the maximum wire length for serial communication between two Arduinos?

I am building a project in which two Arduinos will be linked by three wires: TX an RX for serial communication and a common GND. What would be the maximum length of the wires here before communication gets affected?

I am using an Arduino Mega R3 on one side and an Arduino Mini on the other one.

I have no particular requirement for the Baud rate, I could use the lowest one if this helps in any way.

body:
You need to specify

 - The order of range you are interested in - is it in the order of metres, tens of metres, kilometers or interstate ?:-) . ALL are possible with suitable compromise.

 - How you intend to connect to the circuit - direct Arduino pins, high/low buffer, differential drivers, ...

If you use 5V/0V "unipolar" then at say 9600 baud you can get many metres with suitable drivers. If you use an Arduino pin directly wire resistance and inductance will start to matter as range increases.

At 300 baud you can achiever hundreds of metres with twisted pair cables. As range increases aspects like cross-talk from the other circuit and external noise increase in importance. At longer ranges having 4 wires with signal + ground twisted together in each case helps BUT it is likely that at ranges of interest 2 wires plus ground will work OK.

If you are prepared to use enough voltage and slow enough signalling you can signal over thousands of miles - as was done with very early telegraph cables. The thousands of volts needed and signalling speeds of perhaps a few bits per second will be a disincentive in most cases.


body: This is not exactly what you are asking for but it would be robust and available at low cost in the form of arduino modules. The way I would do it is use a Can Driver and receiver on each end. They are inexpensive differential line drivers. There is nothing that prevents using Async at whatever baud you want up to about 1 megabaud. Run a wire for ground it helps. You will wind up using 5 conductors or 2.5 pairs of wire. Ethernet cable should work fine. You can send some power over the spare wires if you like. You also have the option of using some of the automatic CAN drivers that automatically switch to transmit mode when data is sent and receive otherwise, this will keep you to three wires.


message:
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?

body:
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][1]. 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][2]. 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]: http://arduino.cc/en/Main/ArduinoUSBHostShield
  [2]: http://arduino.cc/en/Main/ArduinoBoardYun


body:
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.


body:
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.


body:
**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/


message:
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?

body: 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.


message:
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.

body:
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


body:
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][1] 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.

  [1]: https://learn.adafruit.com/adafruits-raspberry-pi-lesson-13-power-control/hardware


message:
Arduino Nano Motor

If I had four of these [motors][1] 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?

  [1]: http://www.ebay.com/itm/10pcs-Nidec-1-5V-DC-20-200mA-Micro-DC-motor-High-speed-Low-noise-Mini-dc-motor-/221718326366

body:
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][1] 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][2].

  [1]: http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/
  [2]: https://www.pololu.com/product/2130


message:
How can I make a garage door laser sensor?

![enter image description here][1]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.

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

body:
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](https://www.sparkfun.com/products/8958) 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.


body:
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.


body:
I would recommend using laser and [LDR][1]. 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

  [1]: http://en.wikipedia.org/wiki/Photoresistor


body:
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.


body:
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/


message:
ESP8266 + Arduino Uno: Can't send AT Commands

I'm trying to get the ESP8266 up and running without a FTDI chip, just my Arduino Uno. But it seems really difficult. What I did:

 - attach the ESPs VCC directly to Arduino Uno 3.3V; RX->TX; TX->RX

Result: surprisingly worked for 2 mins, however the AT commands returned ERROR sometimes. (baud rate: 9600)

 - attach the ESPs VCC to 3.3V 500mA power supply; RX->TX; TX->RX

Result: AT commands don't work anymore, nothing is displayed in the serial monitor, not even my input; red LED constantly on.

 - attach the ESPs VCC to 3.3V 500mA power supply; TX->TX; RX->RX

Result: blue LED constantly on, no response, same as before

 - change back RX/TX connection, experimenting with baud rate (300 - 115200)

Result: blue LED flashes on start, flashes when something is sent (no matter what the baud rate is), however still no output at all.

Suddenly, I was also getting this error while uploading:
> ser_recv(): programmer is not responding

Detaching the TX connection solved the problem. Btw, I am also using a voltage divider between TX of the Arduino and RX of the ESP.

Afterwards, the blue LED was on constantly again, even though I haven't changed the wiring... (really weird)

To me it looks like the Arduino Serial monitor isn't sending anything, because I don't even see my input. However, the Arduino can output stuff, therefore I assume a connection between Arduino and PC is existing. Maybe it has to do with the connection between TX -> RX, but I see no shorts, just an ordinary voltage divider (100 Ohm and 200 Ohm resistors).

As you might see, I spent a lot of time trying to figure this out. I'm kind of stuck now, as I'm not sure what else to try. If you have any ideas, tips or advice please leave an answer.

Sorry for my English, it's not my native language. If you don't understand something, feel free to ask.

Hope you can help me!

body:
Tx and Rx should be crossed; meaning connect Arduino Tx to ESP Rx and vice versa.

Your second (and first) attempts are correct. Use 1uF capacitor between Vcc and Gnd. This will provide a more
robust connection since the ESP can draw too much current which might cause it to reset.

When using external power supply, hook together the Arduino Gnd to the PS Gnd.

If you get "Programmer is not responding" - disconnect and reconnect the Arduino USB. Also, you shouldn't get this at all since you are not trying to program the Arduino, just use its FTDI as proxy to the ESP. Any serial terminal application can do it (you don't have to use the built-in terminal in Arduino IDE).


body:
Put CH_PD HIGH for AT mode COM.

Note if you upgrade firmware you need to take CH_PD LOW to write new firmware.
Also note if you upgrade your firmware for the LUA com speed will probably default to 115200 and then SoftSerial wont work.
I found it best to test on Arduino Mega as has extra serial ports.


body:
When the 8266 is powered from the Arduino there is barely power enough for sending. So there will be power glitches that makes the USB port inactive.
Even a short voltage drop seems to disable the USB port until it is pulled and reconnected.

I struggled with this. One solution is external power for the WiFi chip. One other solution is to put a 1000 uF capacitor on the 3V power line and ground. That has worked for me.


body:
I have powered the ESP module with 3.3V of Arduino itself.

I too used to get the error always until I changed my settings to "no line ending" at the bottom of the serial monitor.

I had kept it to "NL & CR" from other answers that I read here, and that was the reason for errors I suppose. Anyway changing it gave me the AT OK.

You should try that first.


message:
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.

body:
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**](https://www.pololu.com/file/download/dual_mc33926_shield_schematic.pdf?file_id=0J559)

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.


body:
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.


message:
Wiring Lilypad USB + ESP8266 Serial WiFi Module

I am trying to solve the following scenario:
Lilypad USB connected to WIFI through ESP8266 Serial WiFi Module.

http://arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardLilyPadUSB

http://www.seeedstudio.com/wiki/WiFi_Serial_Transceiver_Module

According to the wiki:
I should connect to TX RX pins. None of them are present as "selectable pins", because they are built in.

This post [Using LilyPad Arduino USB with LilyPad Xbee Shield ][1] talks about using SoftwareSerial something that is new to me.

Could anyone explain how should I proceed with the wiring and if possible a sample sketch just to connect the lilypad usb with the WIFI module to my personal WIFI.

**Edit:**

I found the following [tutorial][2] (spanish one but easy to follow...) where they use the Arduino UNO. I tried the example with the software serial and it worked.
I saw in that tutorial sometimes the pin RST is needed. So I tried to do the same with the lilypad USB, but still didn't work.

  [1]: http://forum.arduino.cc/index.php?topic=245169.0
  [2]: http://www.prometec.net/arduino-wifi/

body:
First, upload the sketch below to your Arduino. Then, try to tie RX (pin 3) and TX (pin 2) of SoftwareSerial together. Open the Serial Monitor and send some text and see if you get it back as a response.

    #include <SoftwareSerial.h>
    SoftwareSerial Serial1(3, 2);

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

    void loop()
      {
         if (Serial1.available())
             { char c = Serial1.read() ;
               Serial.print(c);
             }
         if (Serial.available())
             {  char c = Serial.read();
                Serial1.print(c);
             }
       }

Once you get a response, then your SoftwareSerial part is working and you can then try to connect to your ESP8266.


message:
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,"u-u-u u:u:u", 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,"u-u-u u:u:u", 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()** ?

body:
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.


message:
How can I run two Arduinos in sync for video generation?

I was thinking about building a video circuit that uses two Arduinos (maybe more) to generate video using `NTSC` and the `AD725`.  Although, VGA might be nice if possible.

Anyway, the idea is to use one Arduino as the background layer and the other one as the sprite layer (overlay).

Then, instead of masking the sprite data and having more cpu time, I was thinking of running the signals through a mux.  So that when drawing background data and no sprites (per scanline) then pipe the signal to the AD725.  But when there is a sprite mid-line, then the >0v signal of the sprite Arduino would cause the mux to pipe its contents through to the AD725.

Or, something similar.

I believe many arcade boards from the 80's did this.  Many of them had entire "sprite boards" attached and the signals would mix.  Each layer would have it's own RAM and not be aware of the other layer.

But to do this, I would have to keep the Arduinos sync'd perfectly.

So that's my question.  How I can do this?

Oh, my Arduino of choice in the beginning would be the UNO but I have others (DUE, Teensy3.1, etc.) if that would be a better fit.

Thanks.

body:
You would need to use interrupts on the "sprite arduinos" to get the timing very exact - the "background" arduino would need to send signals sync signals (horizontal and vertical) to the sprite arduinos. The sprite arduinos would then need to keep track of which line it is on, and time exactly how far along the line it is. You will need a circuit to either allow the incoming signal through (I believe the arduino will be too slow to pass it read it, then write it);

alternatively, have multiple (still synchronized) sources, each indicating if they want to be on the screen; then one that takes the "I want to be on the screen" signals, make a decision, and connect the appropriate one (via a transistor).

A basic tutorial on TV out is found at:
http://playground.arduino.cc/Main/TVout


body:
I would take a look at MREtv which seems to promise all that you want to do, with just one arduino. This might not be the answer you're looking for, but getting threads to sync is a pain in the rear end, see [this](http://thecodelesscode.com/case/121?topic=threads) for explanation of why threads are a pain.

Now back on topic, it seems like MRETV might off what you want to do, and it can do some pretty impressive things from what I read in the arduino. You might need to modify the library a bit, but it offers already implemented encoding, so that is a plus.

http://www.instructables.com/id/MRETV-Video-Stereo-Sound-and-much-more-from-a-s/


body:
Just a thought, you could try synchronizing micros() / millis() between Arduinos... [ https://aaka.sh/patel/2013/12/23/synchronizing-micros-millis-arduino/ ]

Over time you could set instructions/commands to execute at certain time intervals on target arduinos using something as simple as a 2 wire serial setup  [ http://arduino.cc/en/Tutorial/MasterReader ]


body:
Arduinos are great for many things, and I think the idea of synchronizing two or more Arduinos might have several applications.
However, if I wanted to generated VGA or NTSC video, I would look at the Parallax Propeller as another option.

Many people use the Parallax Propeller to produce VGA video, keeping its 8 processors working in parallel.

* ["Hive retro computer"][1]
"containing a total of 24 RISC processors, VGA graphics, stereo sound, ...
uses all DIP and through hole components."
* ["Signal processing module using Parallax's propeller chip"](https://www.ghielectronics.com/community/forum/topic?id=13725),
apparently can do "video in ... to do video-overlay then send it to video out."
* Dangerous prototypes has a long list of projects using the Parallax Propeller.
["Dangerous Prototypes: Parallax Propeller"](http://dangerousprototypes.com/category/parallax-propeller/)
* ["Pocket Mini Computer on Parallax Propeller"][2] includes VGA output
* ["Propellerpowered Forums"][3] includes many people discussing video output on the Parallax Propeller.
* etc.

  [1]: http://dangerousprototypes.com/2013/01/20/hive-retro-computer/
  [2]: http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/
  [3]: http://www.propellerpowered.com/forum/index.php


message:
Connect the output of an Arduino to the input from another Arduino

I'm making a project and i'm trying to send bits from an Arduino to another Arduino with the digital pins. So my setup are 2 Arduino's connected with a jumper.
I connected the grounds and they have both a different power supply.
Now I tried this set-up and as soon as I connect the output pin to the input pin from the other Arduino the voltage lowers from 5V to 2.6V so we can't detect our bits.
Anybody an idea how to solve this problem?

Thanks in advance!

Kind regards,
Manu

body:
I would suggest sticking a transistor in between - use a layout like http://en.wikipedia.org/wiki/Transistor#/media/File:Transistor_Simple_Circuit_Diagram_with_NPN_Labels.svg (from the wiki page on transistor).

Note that Vout should be connected to the input pin on one arduino, and Vin should connect, via a resistor, to the output pin on the other arduino.

Just to confirm, the labels are reversed from what you will expect them to be.

The 2 resistors can be anything > 1kOhm.

This still depends on the common ground.

Note that common ground may not be a good idea if they are generated from the same power source - I've found ground from two USB ports on the same laptop to be at different levels, so current will flow out from one port, and in the other, probably damaging the laptop, if the two grounds are connected.


body: As you are trying to communicate with two arduinos I will suggest you to use some sort of standard communication protocol such as Two wire interface or I2c. There is the Wire.h library you can use and it has also a reference on the main Arduino site. If you have different necessity and want to carry on with you're methods you need to specify in more depth the connections you have made. As for now I can guess that the output is being connected to ground or some sort of load and that might be the reason you are seeing a drop out of voltage. But it might be also the case that you're output pin is changing so fast that the multimeter is not capable of reading the high state correctly


body:
As Harry mentioned better to use some communication lines like UART or I2C or SPI.
If you dont have them available then use digital i/os but make sure their pull up and pull down resistors are correctly configured. If it is input just set as pull up and for output set as output pin.
Regards,
Pathik


body:
First of all, I cannot say if your protocol will work or not since I don't have the details. However, switching protocols will give you the same result. Also, you do not need a transistor for this usage.

The solution is to connect the grounds of the different power sources. Since voltage is relative, having the grounds disconnected will lead one device to think that the voltage is higher/lower than the other one thinks (they have different reference point).