message:
Timer1 stops firing

I am trying to use interrupts to play notes on a speaker.  Timer2 works fine, but after about 15 seconds, Timer1 stops firing for about 5 seconds, and then it comes back on.  If I keep running the sketch, it will stop and resume every now and then.

Here is my code:

    #define SPEAKER1 8
    #define SPEAKER2 7
    volatile bool swap1;
    volatile bool swap2;

    ISR(TIMER1_COMPA_vect)
    {
        digitalWrite(SPEAKER1, swap1);
        swap1 = !swap1;
    }

    ISR(TIMER2_COMPA_vect)
    {
        digitalWrite(SPEAKER2, swap2);
        swap2 = !swap2;
    }

    void playNote1(unsigned note) { //Play a note on Timer1.
        uint8_t oldSREG = SREG;
        cli();
        bitSet(TCCR1B, CS10);
        bitSet(TCCR1B, CS12);
        unsigned ticks = (16000000 / 1024) / (note);
        ticks /= 2;
        OCR1A = (ticks <= 65535 ? ticks : 65535);
        SREG = oldSREG;
    }

    void playNote2(unsigned note) { //Play a note on Timer2.
        uint8_t oldSREG = SREG;
        cli();
        bitSet(TCCR2B, CS20);
        bitSet(TCCR2B, CS21);
        bitSet(TCCR2B, CS22);
        unsigned ticks = (16000000 / 1024) / (note);
        ticks /= 2;
        OCR2A = (ticks <= 255 ? ticks : 255);
        SREG = oldSREG;
    }

    void stopNote1() {  //Stop playing a note on Timer1.
        uint8_t oldSREG = SREG;
        cli();
        bitClear(TCCR1B, CS10);
        bitClear(TCCR1B, CS12);
        SREG = oldSREG;
    }

    void stopNote2() {  //Stop playing a note on Timer2.
        uint8_t oldSREG = SREG;
        cli();
        bitClear(TCCR2B, CS20);
        bitClear(TCCR2B, CS21);
        bitClear(TCCR2B, CS22);
        SREG = oldSREG;
    }

    void setup() {
        pinMode(SPEAKER1, OUTPUT);
        pinMode(SPEAKER2, OUTPUT);
        pinMode(13, OUTPUT);
        // initialize timers
        cli();          // disable global interrupts
        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B
        // turn on CTC mode:
        bitSet(TCCR1B, WGM12);
        bitSet(TIMSK1, OCIE1A);

        TCCR2A = 0;     // set entire TCCR2A register to 0
        TCCR2B = 0;     // same for TCCR2B
        // turn on CTC mode:
        bitSet(TCCR2A, WGM21);
        bitSet(TIMSK2, OCIE2A);
        sei();          // enable global interrupts
    }

    void loop() {
        playNote1(523);
        delay(1000);
        stopNote1();
        delay(500);
        playNote1(131);
        delay(2000);
        stopNote1();
        delay(500);
    }

body:
The problem you have is that **you never reset Timer1 counter (`TCNT1`) when you stop a note and then play another one**.

Also, changing the clock divider selection to "*no clock*" by clearing bits **CS10** and **CS12** as you do is not the most effective way to stop the timer; in fact, rather than stopping it, you can let it run but just **disable its interrupts**.

I have modified your program and this worked correctly:

    #define SPEAKER1 8
    volatile bool swap1;

    ISR(TIMER1_COMPA_vect)
    {
        digitalWrite(SPEAKER1, swap1);
        swap1 = !swap1;
    }

    void playNote1(unsigned note) { //Play a note on Timer1.
        uint8_t oldSREG = SREG;
        cli();
        unsigned ticks = (16000000 / 1024) / (note);
        ticks /= 2;
        OCR1A = (ticks <= 65535 ? ticks : 65535);
        TCNT1 = 0;
        bitSet(TIMSK1, OCIE1A);
        SREG = oldSREG;
    }

    void stopNote1() {  //Stop playing a note on Timer1.
        uint8_t oldSREG = SREG;
        cli();
        bitClear(TIMSK1, OCIE1A);
        SREG = oldSREG;
    }

    void setup() {
        pinMode(SPEAKER1, OUTPUT);
        pinMode(13, OUTPUT);
        // initialize timers
        cli();          // disable global interrupts
        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B
        TCCR1C = 0;     // same for TCCR1C
        // Set clock divider
        bitSet(TCCR1B, CS10);
        bitSet(TCCR1B, CS12);
        // turn on CTC mode:
        bitSet(TCCR1B, WGM12);
        bitClear(TIMSK1, OCIE1A);
        sei();          // enable global interrupts
    }

    void loop() {
        playNote1(523);
        delay(1000);
        stopNote1();
        delay(500);
        playNote1(131);
        delay(2000);
        stopNote1();
        delay(500);
    }

Note that I have removed all code for Timer2 as it does not play any role in the initial problem.

The important changes are:

1. `setup()` now performs Timer1 setup completely (CTC mode, clock divider); note that I also included **TCCR1C** to ensure full setup (it is preferrable as Arduino libraries may have initialized it differently before `setup()` is called); it also ensures Timer1 interrupts are initially disabled.
2. `playNote1` now clears `TCNT1` **and then** enable Timer1 interrupt for `TIMER1_COMPA_vect`
3. `stopNote1()` just disables Timer1 interrupt for `TIMER1_COMPA_vect`

To be complete, you would also want to limit **useless consumption** on output **pin 8**, thus stopping a note should also force its output level to `LOW` (or `HIGH` depending on your actual circuit behind, but `LOW` is more likely):

    void stopNote1() {  //Stop playing a note on Timer1.
        uint8_t oldSREG = SREG;
        cli();
        bitClear(TIMSK1, OCIE1A);
        swap1 = false;
        SREG = oldSREG;
        digitalWrite(SPEAKER1, LOW);
    }

### Now what about your code for Timer2, the code is the same, so why does it work?
Actually it doesn't :-)

But you can't hear the difference between Timer2 is an 8-bit counter so if you don't reset it, then it won't take long until it reaches 255 and resets to 0, so only the first wave phase will be wrong but your hear won't notice that...

So **you should also modify the code for Timer2** to make it correct.


sender: user

message:
Servo Keeps Trying to Turn

I currently have a servo wired to my Arduino and have imported the Servo.h.  Here is my sketch:

    #include <Servo.h>

    Servo s1;
    Servo s2;

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

      s1.attach(8);
      s2.attach(9);
    }
    int pos = 0;
    void loop()
    {
      pos = 0;
      if(s1.read() != pos)
        s1.write(pos);
      if(s2.read() != pos)
        s2.write(pos);

      delay(1000);
    }

The problem is that even when my servos are at the position 0 it still tries to turn and I hear it trying.  What do I have to do to tell it to stop turning once it is already at the desired position?

So this is my second bit of code:

    s1.write(0);
      delay(5000);
      s1.write(100);
      delay(5000);
      s1.write(180);
      delay(5000);

When I write them to 100/180 (or any number) they are silent after the turn, but when I write them to 0 I hear them keep trying to turn...

sender: assistant

body:
The reason they keep trying to turn is mechanical. The physical stop in the gears is hit before the encoder/potentiometer reaches its end point.

You can make the servo stop fidgeting by completely relaxing it if you want. just use

    s1.detach();
    s2.detach();

and your arduino will stop sending any signal.

Bear in mind that "reading" the value of a servo in arduino gives you the servo's current set point, not its current location. Your code in unfortunately unaware of a servo's actual location. With that in mind, setting your servo to go to 0, waiting for it to get there with a delay, and then detaching it will have the desired effect, but since it will not maintain position and you will need to reattach it to function again, using 1 or 2 as your far left endpoint is likely the better option.


body:
A common reason is could be because your servo cannot operate at a PWM signal of 0ms.
For conservative limits, you should stay between 100ms and 2800ms even for very high quality servos.
With lower quality servos that do not specify maximum and minimum values, conservative limits are 700ms to 2400ms.


message:
Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards?

I have come across some Andruino Sensors like Motion, Light and all recommend to be connected to pin 2 or 3 on Andruino Uno board which are interrupt pins. This is especially true if you are looking for HIGH or LOW values. Why is that to be connected to interrupt pins?

One example would be is I used CC3000 Wifi Breakout and Motion sensor. Both were in fight to occupy the interrupt pin 2. I have seen the Motion sesnor not working correctly after getting it's signal hooked to Pin 4[It has pull up resistor enabled]

What should I do if i need to hook up more sensor which uses the limited interrupt pins and how should i handle the above scenario?

body:
The interrupt pins are used to notify the MCU that a device needs attention. The INTx pins are chosen first because they are easy to program for; each gets a dedicated interrupt vector and hence ISR.

There is another type of external interrupt though, the Pin Change interrupt. This can be invoked via any of the PCINTxx pins on the device; on the '328 *any* pin can act as an interrupt.

The main difference between INT and PCINT is that PCINTs are grouped into banks of 8, which means that once the ISR has been invoked the appropriate pins need to be checked for their level, which furthermore means that it is possible to misread an interrupt if a bank is shared by multiple devices and the interrupt pulse itself is very short.

Further details can be read in the "External Interrupts" and "Interrupts" sections of the MCU datasheet.


body:
Ignacio provides a great answer on the differences between the two types of interrupts.  But to add to that, it isn't a universal requirement to even use an interrupt.

**Polling** is also a possibility, though it has been compared to periodically picking up the phone to see if anyone is trying to talk to you.

* Advantages of using an interrupt can include faster response, background response while a program is primarily doing something else, and often an associated ability wake up the processor from low-power sleep mode used in battery powered gadgets.

* But polling can have a role, for example when the program runs in a tight loop and can only take action in response to input at certain times anyway - an interrupt service routine that merely sets a flag to tell the main program loop that something has happened may or may not be much benefit.

* Often the best solution is a hybrid approach - an interrupt service routine records events - especially ones which might vanish or be repeated before the main program loop can poll for them.  Then when the main program loop reaches a logical decision point, it checks the flags or event queue to see if the interrupt service routine has recorded anything to which it should respond.  Serial receive is typically handled this way in the Arduino framework.


message:
Animated LED Strip & Sensing an Object

Problem: Have an LED strip do some animation (say it takes 15 seconds for that line of code to run) meanwhile, have a sensor (tried methods: PIR sensor and ultrasonic sensor) watching to see if an object passes by.  If it senses an object, stop the light animation and make the lights do something else.

Issues: The PIR sensor takes too long to reset... I have the timing turned all the way to minimum and I am still able to count 12 seconds before it starts sensing motion again.  (Is there anyway to override this in the code?)  The other issue is the ultrasonic sensor, as far as I know, can't reliably run the first animation and watch for a change in distance then call an interrupt since an interrupt can only happen on FALLING, RISING, LOW, or CHANGE. This is an issue because the ultrasonic sensor is continuously sending LOW to HIGH then back to LOW for its pulses.

OVERALL QUESTION: How can I effectively sense if an object passes by a sensor, run new LED animation then back to where it left off without having to wait 12 seconds every time.  Is there some other hardware I could try? Please help!?

body:
It seems as you are using the `delay();` function for your code. The reason that it doesn't run anything is your Arduino does *nothing* during the function. The easiest option IMHO is using `millis();`. This will "return" a long datatype. Some example code (modified from example sketches in Arduino IDE):

    /*
     created 2005
     by David A. Mellis
     modified 8 Feb 2010
     by Paul Stoffregen
     modified 5/16/14 by Anno. Penguin
     This example code is in the public domain.
    */

    const int ledPin =  13;      // the number of the LED pin
    int ledState = LOW;             // ledState used to set the LED
    long previousMillis = 0;        // will store last time LED was updated
    long interval = 1000;           // interval at which to blink (milliseconds)

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

    void loop()
    {
      //Sensor code
      unsigned long currentMillis = millis();
      if(currentMillis - previousMillis > interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW)
          ledState = HIGH;
        else
          ledState = LOW;

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }

Obviously, your code will be more complex than that. This one only blinks it, but you'll have to do some creative logic here. I don't know what the animation is, but most likely you'll need to add a few more variables (make sure to declare them outside `loop()` so they aren't disposed of each iteration!).


message:
To connect a simple toy circuit and trigger with an arduino?

I have a small circuit from a toy sword that has an LED and a small speaker. It was powered by a couple of small coin cells.

I am trying to figure out how to connect it to my Arduino so I can trigger it.
If I attached the circuit directly to the GND and +3.3V and press the switch in it I get the sound of a sword and flashing LED as desired.

Now I want to somehow get the Arduino to trigger the circuit but am very new to Arduino and quite unsure of how to approach this.

Can anyone advise how best to work with an existing low power circuit that can use the Arduino's power rails but needs the switch integrated?

Sorry for the noob question.

body:
You'll probably want to use a transistor to switch it on/off. You *could* just use the Arduino's digital pin but they can only supply a limited amount of current. Transistors can work with larger currents. The Arduino switches the transistor and it powers the external circuit.

There are a couple of existing questions that may help you.

* [How to switch an external circuit with Arduino?][1]
* [How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?][2]

[jippie's answer][3] in the first link shows an example schematic for hooking up a transistor with a bunch of LEDs but you would replace them with your own circuit:

![enter image description here][4]

  [1]: https://arduino.stackexchange.com/questions/508/how-to-switch-an-external-circuit-with-arduino
  [2]: https://arduino.stackexchange.com/questions/403/how-can-higher-current-devices-motors-solenoids-lights-etc-be-controlled-b
  [3]: https://arduino.stackexchange.com/a/509/11
  [4]: https://i.stack.imgur.com/8zae1.png


message:
What is Serial.begin(9600)?

I know that this is to initialize something:

    Serial.begin(9600);

But I want to know what it really means?

body:
`Serial.begin(9600)` doesn't actually print anything. For that you'd want to use `Serial.print("Hello world!")` to print the text "Hello world!" to the serial console. Rather it initializes the serial connection at 9600 bits per second.

Both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: `Serial.begin(57600)` would set the Arduino to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Arduino IDE's serial monitor) to the same speed in order to see the data being sent.


body:
A picture is worth 1000 words, so they say, (1024 words if you work with computers) so I'll post some pictures ...

I set up my Uno to send "Fab" at 9600 baud and captured the results on a logic analyzer.

[![Serial comms - 3 letters][1]][1]

The parts shaded in red are the "idle" period between bytes.

From the above graphic note that the Tx (transmit) data line is normally high (1) until it drops low to indicate the start of a character (byte). This is the *start bit*. Then the 8 data bits (indicated by white dots) appear at the baud rate (9600 samples per second). After that the line is brought high again. This is the stop bit (the red part). Then we see the start bit for the next character, and so on. The "stop" portion can be indefinitely long, however it has to be at least one bit length.

---

More detail for the first character (the letter "F" or 0x46 or 0b01000110) can be seen here:

[![Serial comms - a single byte][2]][2]

* A - no data (Tx is high)

* B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.

* C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).

* D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.

* E - The start bit for the next character.

---

You can see from the logic analyzer capture that `T1 - T2` is 0.1041667 ms, and as it happens that is 1/9600:

    1 / 9600 = 0.00010416666 seconds

Thus the rate of 9600 gives you the number of **bits per second** and the inverse is the **time interval between bits**.

---

## Other considerations

* Serial comms is not self-clocked (unlike SPI or I2C, and others) hence both sender and receiver have to agree on a clock rate.

* The clock rate is not exact on the Arduino, because the hardware has to divide the system clock down to get a serial clock, and the division is not always exact. There is almost always an error, the amount is given in the datasheet (figures quoted for a 16 MHz system clock, such as on the Uno):

    [![Serial baud rate error][3]][3]

* You can vary the number of data bits, you don't have to send 8 of them, in fact you can send 5 to 9 bits.

* There can optionally be a *parity* bit sent after the data bits.
    * If you specify "odd" parity, the parity bit is set in such a way that the total number of 1-bits is odd.
    * If you specify "even" parity, the parity bit is set in such a way that the total number of 1-bits is even.
    * If you specify no parity, the parity bit is omitted.

    This can help the receiver detect if the data arrived correctly or not.

* The parity bit is sent before the stop bit.

* In the case of 9 data bits (as used in the SeaTalk protocol) the parity bit is re-purposed as a 9th data bit. Therefore you can't have both 9 data bits and a parity bit.

* You can also have two stop bits. This basically just lengthens the time between bytes. In the "olden days" this was so that slow electromechanical equipment could process the previous byte (eg. to print it).

---

### Possible corruption

If you start listening to serial data in the middle of a stream, it is quite possible that a 0-bit in the middle of the stream will be interpreted as a start bit, and then the receiver will interpret everything after that incorrectly.

The only real way to recover from this is to have a large enough gap, from time to time, (eg. 10 bits long) that this cannot happen.

---

### Inverted logic

The bits shown here (logic-level) are not inverted. That is, a 1-bit is HIGH and a 0-bit is LOW. If you have RS232 equipment that will probably be sending something like -12 V for a 1-bit, and +12 V for a 0-bit. This is inverted because a one is less than a zero, voltage-wise.

If you have such devices you need to do voltage conversion and logic inversion. Chips like the [MAX232](http://www.maximintegrated.com/en/products/interface/transceivers/MAX232A.html) will do both for you. They can also provide the -12 V needed to drive such equipment by generating it internally with the help of a few user-supplied capacitors.

---

### Speed rule-of-thumb

Since, with one start bit, 8 data bits, and one stop bit we have a total of 10 bits, as a quick rule of thumb, you can calculate the number of **bytes** you can transmit in a second by dividing the bit rate by 10.

Eg. At 9600 BPS you can send 960 bytes per second.

<!-- language-all: lang-C++ -->

---

Code to reproduce:

    void setup()
      {
      Serial.begin(9600);
      Serial.print("Fab");
      }

    void loop ()
      {
      }

  [1]: https://i.stack.imgur.com/djsrz.png
  [2]: https://i.stack.imgur.com/GYiby.png
  [3]: https://i.stack.imgur.com/3iVaW.png


body:
;TLDR; It initializes the serial communication port and sets the baud rate. The device you're communicating with (or Arduino IDE Serial Monitor) have to be set to a matching baud rate. Once you've initialized the port you can begin sending or receiving characters. [Arduino Serial Reference][1]

  [1]: https://www.arduino.cc/en/Reference/Serial


message:
How to make an electronic suction cup?

The [uArm][1] is a robot arm with a suction cup (or gripper). I'd like to try to make **just the suction part** of it, and I'm wondering what components I'd need?

By the looks of it, I'd need a hobby vacuum pump, but these seem few and far between on UK components sites.

How would I power it? It looks like they're all 12v, and I believe Arduino gives you 5v?

Exact what components would I need? Do I need any shields?

Here's a short video of the suction cup I'd like to copy:

[![][2]](https://www.youtube.com/watch?v=x6pJqdSk29Y)

  [1]: https://www.kickstarter.com/projects/ufactory/uarm-put-a-miniature-industrial-robot-arm-on-your
  [2]: https://i.stack.imgur.com/Yv5KA.png

body:
There are two approaches I can think of that would work decently. Either a.) suck air out of a "cup," turning off the pump when done. OR b.) have a valve where the arm pushes one part of the bag against the table to squeeze all the air out of it, and shutting a valve attached to the "cup." Then, to release, the valve could be opened. For the suction cup, I'd personally try making it out of a suction cup hanger like this:

![][1]

*Source: http://www.amazon.com/Set-Large-Suction-Hanger-Hook/dp/B00439SCZO*

The availability of these might vary by area, so I'm not sure how common these are in the UK. If you find one, make sure that it's pretty thick, with not that large of diameter so it's not too big to work with. I'd then remove the metal hook with pliers and drill a hole in the center. After that, you would need to superglue a tube through the center of the hole and seal it with some caulk.

Like I mentioned earlier, the two options are to a.) suck to grab and turn off pump to release or b.) have arm apply pressure to a flat surface and then shut a valve attached to the tube, creating negative pressure in the suction cup. Then, you could open the valve to balance the pressure and let the item go. I'd personally do the suction approach because, although it is louder and might use a little more electricity, it's a bit easier to build and execute and can grab in the air. I'm going to focus on that.

For the pump approach, build the suction cup (like I said above), attach the tube to one end of the motor with a hose clamp, leave the other hose terminal unconnected, and connect the pump (through a relay) to a 12V 1A+ power supply. You can do this by connecting the + pin of the pump to the "out" (or similar) pin of a relay breakout board, the "in" (or similar) of the relay to the power supply +, and the - of the pump to the power supply's - wire. This will make a circuit similar identical to a switch (the switch being the relay). To connect the relay to the Arduino you will have to connect the relay's logic signal to a pin on the Arduino and then you can just write `HIGH` or `LOW` to turn the pump on and off.

**EDIT:** Forgot to mention, you can use a transistor, too. Also, I illustrated the second method (hopefully it makes this clear).

![][2]

  [1]: https://i.stack.imgur.com/Vxd3Bs.png
  [2]: https://i.stack.imgur.com/glaEV.png


body:
Just a note for those who wonder the same and are in need of a vacuum: In theory, you can use Venturi effect (or Bernoulli's Principle; it's basically the same) to create a vacuum. Or go buy an [Aspirator pump][1]. Since English is not my native language it's difficult for me to explain it in my own terms, but I'll try to give you a rough idea anyway. (Google it or feel free to answer with a better explanation).

First you need some flow of a fluid or gas (air from a compressor or water from a household outlet are fine). You pass that flow through left-to-right in a T-pipe (I'll call that the "flow pipe"). This will result in a weak vacuum in the orthogonal pipe (I'll call this the "vacuum pipe"), which you can connect to your suction cup.

The strength of the vacuum depends on the pressure in the "flow pipe". That means a higher velocity of your matter in the "flow pipe" is good (either a stronger compressor or smaller diameter of your flow pipe).

If I understand my physics book correctly, a higher density of the matter in your flow pipe will also produce a stronger vacuum. If you need a really strong vacuum, you could even use a water compressor, i.e. high pressure cleaner; but I suppose even a small air compressor will outperform a household water outlet (and you could toggle it from an Arduino with a relay board).

Since the air in the vacuum pipe expands more than many other materials, you could try to replace it with i.e. oil (be aware you'll pull out some of the air/replacement material at the intersection in aspirator!). This optimization is dangerous with a normal vacuum pump, since these usually break when sucking up fluids into their internals.

Also using an aspirator has the upside of not needing to buy a vacuum pump if you already own a compressor. On the other hand, that setup might be even louder (and possibly less efficient) than a dedicated vacuum pump.

  [1]: https://en.wikipedia.org/wiki/Aspirator_(pump)


body:
You can't power things like pumps and motors with the power supply from an Arduino. It doesn't provide nearly enough current. It's meant for providing regulated 5V for low powered logic circuits, and nothing else.

What you can do is use a transistor as a switch to turn on and off the power from a suitable external power supply.

If you find a vacuum pump that runs on 12V, get a 12V power supply with enough current to drive the pump, and then use a [**MOSFET transistor**][1] (example link) that will can handle enough current at 12V and can be controlled by a 5V signal to it's gate, and use that to switch the power on and off. Then you'd need a diode to protect the transistor against the reverse current you get from inductors like motors.

  [1]: https://www.adafruit.com/product/355


message:
Initialize a "Matrix" object in my own library?

So, I'm trying to make a custom library to drive a 8x8 Bi-Color LED Matrix from 2 MAX7219's that incorporates two "Matrix" objects from the "Matrix" library and I cannot, for the life of me, figure out how to initialize them in my class. Can someone help me? By the way, I have been programming for 8 years, and consequently have a decent knowledge of the topic! Here is my current code:

header file

    #include "Arduino.h"
    #include "Matrix.h"
    #include "Sprite.h"

    class ZackBiColorMatrix{

     public:

      ZackBiColorMatrix(byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG);

      Matrix r;
      Matrix g;

      void setLED(byte col, byte row, byte val, char color);
      void writeSprite(byte x, byte y, Sprite sp, char color);

     private:

      byte redData;
      byte redLoad;
      byte redClock;

      byte greenData;
      byte greenLoad;
      byte greenClock;

    };

and the .cpp file:

    #include "Arduino.h"
    #include "Sprite.h"
    #include "Matrix.h"
    #include "ZackBiColorMatrix.h"

    ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG) {

     redData = dataR;
     redLoad = loadR;
     redClock = clockR;

     greenData = dataG;
     greenLoad = loadG;
     greenClock = clockG;

     r = Matrix (redData, redClock, redLoad);
     g = Matrix (greenData, greenClock, greenLoad);

    }

    void ZackBiColorMatrix::setLED (byte col, byte row, byte val, char color) {

     if (color == 'g') {

      g.write (col, row, val);

     }
     else if (color == 'r') {

      r.write (col, row, val);

     }

    }
    void ZackBiColorMatrix::writeSprite (byte x, byte y, Sprite sp, char color) {

     if (color == 'g') {

      g.write (x, y, sp);

     }
     else if (color == 'r') {

      r.write (x, y, sp);

     }

    }

Also, I use the Eclipse Arduino IDE if that matters.

body:
This is a C++ question actually.

In C++, you initialize class members in the class constructor definition by using a "[member intialization list][1]" as follows for your example:

    ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG)
    :   r(dataR, clockR, loadR),
        g(dataG, clockG, loadG) {
        ... Additional initialization here
    }

This is a special C++ construct (note the colon `:` after the constructor declaration but before its implementation).

Also note that, in your example, I think you don't need to declare `redData`, `redLoad`, `redClock`, `greenData`, `greenLoad`, `greenClock`, sicne they are not being used once your 2 `Matrix` fields have been initialized.

Hence you could simplify your class further, I think.

  [1]: http://en.cppreference.com/w/cpp/language/initializer_list


message:
Include statement not working

I am creating my own library for the Arduino and I have the following code:

    #include <Arduino.h>
    #include <Servo.h>

    class ServoMotorController {
     public:
      ServoMotorController(int servoPin, int motorPin, int angle);
      void setAngle(int angle);
      void setSpeed(int speed);
     private:
      Servo servo;

      int servoPin;
      int servoAngle;
      int motorPin;
      int motorSpeed;
    };

I am getting the error that `Servo` does not name a type; however if I do

    #include <Servo.h>
    #include <ServoMotorController.h>

in my actual Arduino code then I do not get the error. **Why is the include statement not working in my C++ lib?**

body:
This is a symptom of the arduino IDE. libraries can't add other libraries to the include path, but the can use other libs if they have already been included. you can use an error directive so your compiler output is more informative at least

    #ifndef Servo_h
        #error "ServoMotorController Lib requires Servo.h to be included first to function"
    #else

Arduino 1.5.6 beta's new library format has a section for dependencies in the new library.properties file that should allow one library to add another to the include path, but I'm not entirely sure if the functionality is fully implemented yet (its beta after all).


message:
SoftwareSerial error

I have arduino , upon arduino I have Arduino GSM shield (Tx-2, Rx-3, Modem reset-7) and upon it, I have the Adafruit GPS Logger shield. I am trying to send sms of Latitude  from the GPS Logger shield to my numer through GSM shield. I am getting a error ..

    SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
    /home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_3'

    GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here
    SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
    /home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_4'

    GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here
    SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
    /home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_5'

    GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here

What is the meaning of this error ? what should I do to solve it?

body:
This error means, that there is library overlapping on a vectors. To solve this error, you need to modify your Library file :

STEPS :

1. Remove the Softserial Library
2. Download AltSoftSerial library
3. if you have shield then you need to replace AltSoftSerial in place of SoftwareSerial in both .cpp as well as .h files.
4. Import AltSoftSerial library in place of SoftwareSerial in the sketch.

Execute .


message:
Why does the Arduino Due have a native and USB programming port?

According to the schematics, the Arduino Due has two USB inputs:

 1. Native
 2. Programming

Why is this? And when would I use the different ports?

body:
Either port can be used for programming, but the native USB port lets you do other things:

> It also enables the Due to emulate a USB mouse or keyboard to an attached computer. To
> use these features, see the [Mouse and Keyboard library reference pages][1].
>
> The Native USB port can also act as a USB host for connected
> peripherals such as mice, keyboards, and smartphones. To use these
> features, see the [USBHost reference pages][2]. http://arduino.cc/en/Main/arduinoBoardDue

So you can use the Due to interface with USB devices or connect it to your computer and have it act like a USB device.

  [1]: http://arduino.cc/en/Reference/MouseKeyboard
  [2]: http://arduino.cc/en/Reference/USBHost


message:
Error while connecting Arduino to Macbook: “serial port already in use. try quitting any programs that may be using it”

I'm trying to connect to my Arduino board through a macbook pro with mac os x 10.9.3 installed. I'm following the instructions from the arduino guide and in the connection section:

>" Connect the Arduino board to your computer using the USB cable. The green power LED (labelled PWR) should go on.
If you're using the Arduino Uno or Arduino Mega 2560, a dialog box will appear telling you that a new network interface has been detected. Click "Network Preferences...", and when it opens, simply click "Apply". The Uno or Mega 2560 will show up as "Not Configured", but it's working properly. Quit System Preferences.

I cannot see any ports that hold the USBModem port.

How to setup the connection in the right way?

I read some articles about making a lock folder and I followed them but they didn't work for me, I also tried following [this article](http://forum.arduino.cc/index.php?topic=198539.0) but the solution there didn't work as well.

body: Under what circumstances does this happen? I see this message whenever I try to download to the Arduino but I've left my terminal program connected to that port. The fix in that situation is to disconnect it (after a <face-palm> to remind myself, yet again....  :-)


body:
Sorry about providing this as an answer, rather than comments; however, I do have *some* suggestions to troubleshoot the connection.

First, check the usb connections with `lsusb`

        lsusb |grep -i arduino

Similarly, you can try following the output of `dmesg`; though, I'm not sure about the version of `dmesg` your system's installation is running.  Newer version of `dmesg` have a "follow" option available. On my Fedora system it's:

        dmesg -wH

Check the output as you plug in the arduino for messages related to the device, such as the resulting location of the `tty`. As a desperate measure, you can also look in the `/dev/` folder for the last modified device, and search your logs for those devices:

        ls -alrth /dev/


message:
Is there a way to test whether the UART Tx buffer is empty without waiting?

`serial.flush()` waits, so it won't help me.

I tried looking into `serial.SerialEvent()`, but the link was broken on the Arduino reference page.

Can anyone point me to a description of it?

body:
It doesn't look like that function is implemented. The source for HardwareSerial.{cpp,h} are in `/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino` under OS-X. (Someone better versed in Window than I may have to chime in here to point you to that source location.)

Taking HardwareSerial::available() as a model, create a new function, say, HardwareSerial::txremaining(), that does the same thing, but for the transmit buffer.

Left as an exercise for the student:<br>Make a common function that returns the contents of an arbitrary ring-buffer and use it in both ::available() and ::txremaining().


message:
avrdude: stk500_getsync(): not in sync: resp=0x00

I have arduino pro mini 5V, 16M ATMega328 and CP2102 USB to TTL. I've wired them like this:

![enter image description here][1]

When I try to upload a sketch to the arduino board I'm getting the following error:

    avrdude: stk500_getsync(): not in sync: resp=0x00

The board type and the serial port are correct. The sketch also compiles successfully and I've installed the CP2102 drivers. I've noticed that even if I unplug all wires from the arduino board(and just leave the cp2102 connected to the PC), I'm getting the same error again. I'm using Windows 7.

Anyone else encountered the same issue?

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

body:
This error means that the program responsible for uploading (avrdude) can not communicate with your arduino.

Did you reset the board just before programming? The reset pin of the arduino seems unconnected in your picture; so the board wouldn't be executing the bootloader when the serial cables expects it to.

Try either to reset the board manually just before programming, or connect the rst pin.


body: It's hard to tell from your pictures, but are all the header pins soldered to the boards? If not, they need to be: there's no chance that the proper electrical connections will be made reliably if they're just inserted loosely into the holes.


body: This problem is caused by using the wrong USB cable. I have three cables, two of which work find, and one of which has this issue. The cables with the ferrite bead around them will work. The one cable that I have which works has a braided shield surrounding the conductors, and it is about 2 feet long. I have a 3 foot cable with no bead and no shield that exhibits this issue.


body:
I solved this problem by connecting **DTR** signal from USB-converter to the pin which says **GRN** on the board (the one aside TXD). It was not obvious to find, but seen on ebay some arduino-dedicated-usb-programmer which seemed to be connected this way - so I took the chance. I do not get this error anymore and uploading works every time!!!

Cheers!


body:
I had the exact same problem. I tried installing the IDE on another laptop and uploaded the program from that laptop. Problem solved. Then I came back to my laptop, uninstalled the IDE and re-installed it. It works.

However, I wasn't satisfied because I can't find the source of the problem... so I tried running everything again the same exact way.. I found the problem but am not sure if that can be the actual cause of it.

In my project, I needed to carry out serial communication between Arduino and MATLAB (GUI). In order to see/verify the output(type) of MATLAB (GUI) serial data, I used HYPERTERMINAL and also VIRTUAL SERIAL PORT EMULATOR. I noticed that every time hyperterminal is running or VSPE is running while my serial monitor is on, it screws up the uploading feature of the program. I'm not sure if it's because of the VSPE or HYPERTERMINAL, but reinstalling the IDE worked for me. :-)


body: This has happpened to me as well. I had a bluetooth/TTL unit wired to RX/TX, which are the same ports used by the usb connection to the computer (where transfer of the program happens), and all I had to do was disconnect RX to the BT unit when transferring the program.


body:
{linux}

The solution for me was to set the correct USB port.

I had been previously working with my Uno on USB0.

I could not upload to my nano as I had it connected on USB1

In menu: Serial Port -> /dev/ttyUSB1


body:
As some of the other answers have said, you may not have soldered on the header pins. You can't just push them into place and hope for the best. See my Pro Mini:

![Arduino Pro Mini][1]

My soldering is reasonably neat, however you can see the solder come through to the other side.

Also see:

* [Some dude named avr won't let me upload my program, aka “avrdude: stk500_getsync(): not in sync: resp=0x00”](https://arduino.stackexchange.com/questions/17/some-dude-named-avr-wont-let-me-upload-my-program-aka-avrdude-stk500-getsync)
* [Have I bricked my Arduino Uno?](https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno) .

A lot of the issues in those threads apply to any Arduino.

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


body:
To solve my sync issue I added a connection from USB serial adapter RST to ProMini DTR pin. I'm using Linux Mint 18 OS with Arduino IDE 1.8.5 -
My other Arduino clones (UNO_r3 and Nano) uses the CH340G chip so I knew I had working drivers. Sorry for the picture quality, my old camera and I don't know how to balance LED light bulbs. The pins from USB to ProMini are: (U)GND-(P)GND; (U)3V3-(P)no connection; (U)5V-(P)VCC; (U)TX-(P)TX; (U)RX-(P)RX; (U)RST-(P)DTR.  Hope this helps. 73 AB1OP_Ralph

[![CH340G USB serial adapter to Arduino ProMini][1]][1]

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


body:
I spent hours looking for a solution to  the same error message. Everything was correct - Board chosen, COM port, everything.

I switched my TX and RX pins, and connected the tx and rx to each other, instead of them being switched (which I saw from a tutorial).
Then I pressed the manual reset, held it down, and uploaded, then released while it read Uploading. It worked.

Hope this helps.


message:
arduino EM408 GPS problem

I have written this little snippet of code to interface with EM408 GPS.

    #include <SoftwareSerial.h>
    SoftwareSerial GPS = SoftwareSerial(2,3);  //rx,tx
    void setup()
    {
      GPS.begin(4800);
      Serial.begin(9600);
    }

    void loop()
    {
      //Serial.print(GPS.read(), BYTE);
      Serial.write(byte(GPS.read()));  //as of Arduino 1.0
    }

Hardware side i have these connections:

ENABLE: 3.3V

Vcc   : 3.3V

Ground: Ground

Rx, Tx correctly connected to arduino and correctly initialized with SoftwareSerial

However, the values i get are just junk data

    ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

I get these without ending...
I experimenting with changing the baud rate, still the same thing goes on.
Any ideas?

EDIT:

I used to get random junk data before with the EM406 gps module, but i solved it by casting everything to BYTE. I have tried both approaches here, but the results are the same...

body:
The problem you get is that `read()` does not wait for a byte to be available, it just returns `-1` if there is no byte available; converted as an unsigned byte that becomes `255`.

In **ISO-8859-1**, which I guess is the encoding that your serial monitor is using, `255` translates to `ÿ`, so this is exactly what you observe.

Fixing this problem is straightforward, just check that a byte is available on `SoftwareSerial` before reading it:

    void loop()
    {
        if (GPS.available()) {
            Serial.write(byte(GPS.read()));  //as of Arduino 1.0
        }
    }


message:
Using Arduino Micro with MPU6050

I have an Arduino Micro and an MPU6050 gyro/accelerometer board; I want to read DMP data from the MPU6050, but the sketch requires the use of the interrupt pin, of which I have none of the interrupt pins available and they cannot be switched around.

I'm wondering how to go about reading the DMP data when needed. I've tried but always just receive the value 180 for any reading.

Thank you!

body:
I searched quite some time for everything regarding the MPU6050, but there is just rumors and jokes about the dmp funcionality. One project encorporates the hard reverse-engeneering some wise people did, which is: http://www.i2cdevlib.com/docs/html/class_m_p_u6050.html

This also uses the interrupt, which I suppose you can't really avoid. Why exaclty this would be necessary though, is not a thing I could tell you.. I assume, that the dmp works somehow with the fifo buffer and can only interact through it. The cited library has examples with and without dmp, which I can really recommend.

Using this thing for a quadcopter however I can just say, that the dmp is too slow to control such a fast system, so maybe first consider what you really need. From my experience it does some magic things, but acts strange is due to it's not documentary it is a pain to work with.

Hope this helps.


body:
You can, in fact, avoid the use of an interrupt with the MPU6050/DMP combination.  See the ongoing thread at https://github.com/jrowberg/i2cdevlib/issues/479 and [this post][1] for example.  I've been running an MPU-6050 based system using polled (vs interrupt) driven configuration for months without any issues (other than a pesky motor noise issue I'm currently trying to resolve).

Regards,

Frank

  [1]: https://www.fpaynter.com/2019/10/mpu6050-fifo-buffer-management-study/


message:
Send text according to an ultrasonic measurement, on battery

I have this big bucket where I would like to install an arduino on the top of the bucket where it would calculate the % of the bucket being filled up with water. Then, every day at night the arduino will send a text message (via SIM card) to the server where it would collect data for that bucket.

As far as a beginner point of view, I can understand that I will need:

an Arduino Board
PING))) Ultrasonic Distance Sensor
Battery pack that would allow to run the board for a year?
and the Arduino GSM Shield (integrated antenna) OR the GSM/GPRS Module M10?

My question is:
What arduino board do I need for my setup?
How long will 2 large or 4 AA batteries lasts for receiving a value from the ultrasonic sensor once a day and sending that value to a server? The point of the instrument is to be as small as possible.

body:
First of all: what is the intention of your setup? What are you trying to measure, what do you want to do with the data? Where is the bucket located, in your backyard or miles away in a forest?

I foresee some problems with your current setup.

First of all, you need a enclosure that keeps your 'duino and other components dry and at a comfortable temperature. I don't know how severe the weather conditions are, but stuff can get unreliable when used close to the min/max operating temperatures. Can you find an enclosure that can protect your electronics against the elements?

My advice: think of a good enclosure.

Second, do you really think PING))) is the best sensor? Have you already tested how it behaves around water? Are the measurements correct?
Another option would be an array of metal strips, one connected to +V or GND, the others to separate ports on your Arduino. Space them evenly from the bottom of your bucket to your maximum water level (drill a hole in the bucket to prevent overflowing or drowning your duino). Poll the pins at a predefined interval (not too short, keeping battery life in mind) to see which ones make contact with the water (allowing current to flow from/to the pins from/to +V/GND)

My advice: do some research on sensors, or try to make your own

The best way to communicate with your 'server' (what are you going to use?) totally depends on how far it is from the bucket. GSM shields are quite pricey, other alternatives may be preferable (and do not have additional phone costs).
Is your server on the other site of the window? Bluetooth? Somewhere in your backyard? Zigbee. Across the street? High-power Zigbee (if allowed by local authorities). Far away but with WIFI access? Zigbee, posting data to an online place. In the middle of nowhere but with great cell phone reception? GSM.

My advice: check out wireless communication possibilities. There's a ton of them, each with pros and cons.

Last hurdle, energy. Your battery setup will most definitely NOT be able to provide enough energy for a whole year. There's just too little juice in them.

Arduino and standalone AVRs often have a sleep mode, in which power consumption can be very *very* low. Google is your friend on this one. Still, that won't let your setup last a year.

Unless there was a gigantic glowing ball of plasma hanging around some 8 lightminutes from here and we could harness its incredible power with the use of photovoltaic elements... Wait, we totally can! Using (a) solar panel(s) and some simple circuitry you can recharge your batteries, and depending on the weather conditions this could keep your project up and running for a year.

My advice: get down and dirty with small solar panels.

I really appreciate your ambition. If done right, this could be quite the project for a beginner! Just make sure you thoroughly research every part of the system, on itself and as a whole. This could prevent a lot of disappointment and unnecessary costs, while only expanding your knowledge.

Good luck!


message:
Power small hobby motor using Vin pin on Arduino and 9V battery, safe?

I want to power a small motor with a 9V battery and control it with PWM using an Arduino Leonardo. I know I can power the motor separately, but this introduces the problem of needing a battery to power the motor (9V battery) and another power source to power the Arduino (another 9V battery?)

**Would it be safe** to simply power the Arduino with a 9V battery and use the Vin pin on the board (which is unregulated and outputs directly the power source powering the Arduino) to drive the motor? That way, I power everything from the 9V battery, and use a transistor to drive the motor.

Thanks a lot!

Steve.

body:
If you use a transistor circuit as shown below, back EMF would not cause any trouble.
![enter image description here][1]

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


body:
Yes it is  OK to do that. But the thing you should consider in mind is "What is the current requirement of the motor?"

You say

> I want to motor a small motor with a 9V battery and control it with PWM

This means you have a servo motor, which might require a lot of current depending on the torque. So if you have a battery with low 'mAh', your battery will dry out very quickly. This might or might not be a problem for you depending on your requirements.


body: The arduino has its on voltage regulator, so feeing 9v to the arduino is not a problem. But the arduino will not drive the motor directly. You need to use a transistor big enough  to  hundle the amperage of your motor (e.g.tip120). The diagram above is a good indication of how to connect it. Yet the diagram is missing a diode (1n4001 or 1n4004) from the GnD to Vcc, as to avoid back voltage from the motor, which may damage your arduino.


message:
Setting time frame in Arduino Uno

I have built the circuit below using mux ICs. In a particular interval the respective selector pins get selected and analog signal from hall sensors are read and give a particular analog value out. There is a total of 30 hall sensors which are represented by `HS0` to `HS31`.

![Multiplexer][1]

Now I wanted to set time as in the table below. After 8000ms I would like it to reset the time automatically and start reading. **Can someone tell me which timer example would let me achieve this?**

    TIME IS ms  OUT1    OUT2    OUT3    OUT4
      0-1000 HS0     HS8     HS16 HS24
    1000-2000 HS1     HS9     HS17 HS25
    2000-3000 HS2     HS10 HS18 HS26
    3000-4000 HS3     HS11 HS19 HS27
    4000-5000 HS4     HS12 HS20 HS28
    5000-6000 HS5     HS13 HS21 HS29
    6000-7000 HS6     HS14 HS22 HS30
    7000-8000 HS7     HS15 HS23 HS31

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

body:
Could you tell us which multiplexer IC you are using? This way, we can help you better. Also, why do you need the 8 second cycle? Does it matter if it's a little shorter or longer? If timing does not have to be very precise it would make things a lot easier.

By the way: you say there are 30 sensors, but your table has 32...

The following pseudocode will not work on your Arduino, but you can use the same structure.

    int sensorArray[32] // we will store our 32 sensor values here

    // these pins control the multiplexer chips
    int selectPinZero = 8;
    int selectPinOne = 9;
    int selectPinTwo = 10;

    // these pins will receive the sensor values from the multiplexer chips
    int inputPinOne = 0;
    int inputPinTwo = 1;
    int inputPinThree = 2;
    int inputPintFour = 3;

    void setup(){
        // make sure the correct pins are inputs and outputs
        pinMode(selectPinZero, OUTPUT);
        pinMode(selectPinOne, OUTPUT);
        pinMode(selectPinTwo, OUTPUT);

        pinMode(inputPinOne, INPUT);
        pinMode(inputPinTwo, INPUT);
        pinMode(inputPinThree, INPUT);
        pinMode(inputPinFour, INPUT);
    }

    // all done, now keep reading the sensors
    void loop(){

        // set selectPins so that each Multiplexer will output its first channel
        digitalWrite(selectPinZero, HIGH); // or low, depending on your Multiplexer IC
        digitalWrite(selectPinOne, HIGH); // or low, depending on your Multiplexer IC
        digitalWrite(selectPinTwo, HIGH); // or low, depending on your Multiplexer IC

        // start reading sensors

        int i = 0;
        while(i<32){
            sensorArray[i] = analogRead(inputPinOne);
            i++; // variable i was 0, now 1

            sensorArray[i] = analogRead(inputPinTwo);
            i++; // variable i was 1, now 2

            sensorArray[i] = analogRead(inputPinThree);
            i++; // variable i was 2, now 3

            sensorArray[i] = analogRead(inputPinFour);
            i++; // variable i was 3, now 4

            /*
            use digitalWrite() on all the selectPins to make the Multiplexer IC output the next channel
            */

            delay(1000); // wait 1000 milliseconds
        }

        /*
        this will repeat until all 32 sensors are read and stored in the array
        */

    }

This code is by no means optimized, but written to make it easy for you to understand. Good luck!


message:
Data packet format when USB initialized as COM port

Does anyone know how the data in data packet looks like when the USB is initialized as COM port?

I have a Arduino Mega 2560. I have initialized COM port with a baud rate of 9600. I know that there are four types of USB packets as

 1. Token Packet (Commonly used for device identification and transaction initiation.)
 2. Data Packet (Contains the data that needs to be transferred from host to client or vice-versa.)
 3. Acknowledgement Packet (Acknowledgement for error-free data reception.)
 4. Special Packets (Hub to hub communication and speed differential.)

The payload in data packet is formatted as

**DATA1 >> PAYLOAD >> CRC16 ; DATA2 >> >> PAYLOAD >> CRC16 ;** etc.

Till this point I am clear about whats happening.

Now all I want to know is

 - How the data is structured in the PAYLOAD section, when USB is initialized as COM port?
 - How the baud rate comes into picture i.e how a particular baudrate is achieved in this type of communication?
 - How is communication in terms of packet sequence? Does the sequence of packets change? (Like token>>data>>ack>>data>>ack>>...)

I really need to know this urgently as I am working on program that has to connect with 3 MEga2560 boards through a USB hub. I want to fix my design constraints depending on what is the maximum baud rate that I can achieve for all boards.

body:
Once the USB connection is initialized as a COM port, it no longer utilizes traditional USB packets (only internally). It acts as a regular COM port. This layer of abstraction is created by 8u2 chip on Arduino side and by the driver on the PC side.

If you need to use the USB without the COM port abstraction, you have to probably configure the 8u2 chip to behave this way. I think it should be possible to configure to act as some HID device for example. You would also need to take care about the PC side and you might have to write your own driver.

For a guide on hacking and configuring the 8u2 chip on Mega, see following link:

[http://arduino.cc/en/Hacking/DFUProgramming8U2][1]

  [1]: http://arduino.cc/en/Hacking/DFUProgramming8U2


message:
How to program an empty Mega2560 with an Arduino sketch?

I am writing code on Arduino mega. My current code is working fine. However, I'm not using all the pins.

My question is:

 1. I have the hex file for my code and I can purchase a Mega2560 MCU. Is there any way to upload the hex file to it and how?
 2. What are the circuits I would need to to build?
 3. [Eagle files][1] of the Arduino mega are available here. Is this circuit more than enough?

  [1]: http://arduino.cc/en/Main/arduinoBoardMega2560

body:
If you buy an empty mega2560 IC. It won't contains any bootloader.
That means that you need an extra circuit, a programmer, to upload your HEX file into your MCU. ["When to use the bootloader" questions link][1]

But, if you buy your mega2560 from an Arduino provider, you should be able to order the MCU with the arduino booloader already programmed. Then a simple serial link from your PC to your MCU will suffice to program the MCU with your Arduino sketch using the Arduino environment. You could clone the serial part that you have on the Eagle files of the original Arduino to do this.

In summary:

 - Programming an empty chip requires a programmer
 - Programming a chip that has a booloader requires either a programmer, or a simple serial link.

You may also use another Arduino with the suited sketch as a programmer and use it for programming another empty MCU. There are examples of this on the web.

  [1]: https://electronics.stackexchange.com/questions/57651/when-to-use-an-arduino-bootloader?rq=1


message:
Stacking shields without headers

In the project I am working on, I have a limited space with which I can work. I am using an Arduino Uno with 2 Adafruit motor shields, and when I stack them using normal, female stacking headers it is too tall to fit. I thought that one way to solve this would be to lay them out side to side rather than one on top of the other. So, instead of this

    +--------Motor shield 2 ----------+
    |||||||||||||||||||||||||||||||||||
    +--------Motor shield 1 ----------+
    |||||||||||||||||||||||||||||||||||
    +---------Arduino Uno ------------+
it would look like this

                   -----------------------------------------Wires -------------------------------
    +---------Arduino Uno ------------+    +--------Motor shield 1 ----------+    +--------Motor shield 2 ----------+
Would this be possible if I were to connect all of the pins with wires, and has anyone successfully done this before?

body: It is possible to have some success with this, but keep in mind that the longer the wire, the higher the inductance and voltage drop across the wire. Prefer to use a star topology rather than a chain topology, with the Arduino in the middle of all the shields in use.


body:
Yes, no problem running individual wires, and also like Craig says, only run the wires you need. For some inspiration, here's a project I did with a [bit of hand wiring][1]. And then there's [this project][2] with kinda epic wiring.

  [1]: http://forums.adafruit.com/viewtopic.php?f=22&t=44710
  [2]: http://www.ducatimonsterforum.org/index.php?topic=64324.0


message:
Is it possible to transmit using an NRF24L01+ without an Arduino?

I have two [NRF24L01+ modules](http://www.elecfreaks.com/wiki/index.php?title=2.4G_Wireless_nRF24L01p) which are transceivers, but for my project I would like to send a very simple signal from one of these modules to the be read by the other.

That would've been very simple if I had an Arduino on each side but due to power consumption constraints as well as size, cost and practicality, the transmitting side won't have one. Would it still be possible to do this?

To clarify, the message itself is not important and can be set in stone, it will never change. I really just want to detect on the receiving side (which will have an Arduino) that the transmitter is in fact transmitting. Transmission will be triggered by a push-button.

Ideally I would have a way of identifying my particular transmitter from others on similar frequencies but I am not too precious about that.

body:
The [nRF24L01+](http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01P) needs an external microcontroller to be used.

I believe an XBee could be used if you want a "single module" solution, however using even the Atmega328p (standard for Arduino Uno) would probably be cheaper than this.


body:
The nRF24L01+ has a somewhat complex SPI based interface, where many registers have to be configured and tested and timeouts honored.  Therefore it requires some kind of microcontroller to send or receive even the simplest message.

This can be as simple as a 3.3v Arduino Pro Mini (less than $3 with shipping), and there are libraries which simplify the task of interfacing to it - in particular see the RF24 library (there are many variations, see https://github.com/TMRh20/RF24 for a good one).

But many other microcontrollers could work as well.

Once you bite the bullet and accept the need for a microcontroller, yes the code can identify the source of the signal (which pushbutton) and much, much more.

Or you could use a dedicated device like an xBee which can be configured using a Windows utility to send the state of an input pin to another xBee; basically there is already a programmed microcontroller on the module along with the radio (not nRF24L01+ compatible).


body:
An ATTiny85 can drive the NRF24L01+: "[nrf24l01+ control with 3 ATtiny85 pins](http://nerdralph.blogspot.ca/2014/01/nrf24l01-control-with-3-attiny85-pins.html)"

At least this is not a "full" Arduino...

Edit 2015-06-06:

Hackaday News: "[EMBED WITH ELLIOT: MULTIPLEXING SPI USES FEW PINS](http://hackaday.com/2015/06/05/embed-with-elliot-multiplexing-spi-uses-few-pins/)"

The referred blog entry is: "[nRF24l01 control with 2 MCU pins using time-division duplexed SPI](http://nerdralph.blogspot.ca/2015/05/nrf24l01-control-with-2-mcu-pins-using.html)".

(-: Nice countdown... 3 pins, 2 pins, ... ;-)


body:
1) Easy way

This transmitter uses _only_ SPI interface so you need to drive it some logic unit, i.e. microcontroller that supports this interface (i.e. AVR atmega8) and is able to use driver for this module as a ready to use set of high level functions to express your intentions in your code.

2) Badly bad way

You can use the SPI to I2C converter as well. Connect it to your computer via serial port - but note that it's a big effort. You will need to port nRF24L01 driver, etc.

http://www.elecrow.com/nrf24l01-wireless-shield-spi-to-i2c-interface-for-arduino-p-737.html


body: Note, there is also the NRF24LE1 SoC which has its own ULP MCU - good for transmitting simple data such as sensor readings. If used to Arduino, ARduino Pro Mini 3.3v and the NRF24L01+ is easier and better way to go. (Mod the Arduino to be ULP)


message:
How to loop over analog pins?

I want to do something along the lines of

    for (int i = 0; i < 4; i++) {
      analogRead(i);
    }

Which appears to work, but the following does not:

    for (int i = 0; i < 4; i++) {
      pinMode(i, INPUT);
      pinMode(i + 4, OUTPUT); // should make Analog Pin (i + 4) into an output
      digitalWrite(i + 4, LOW);
      analogRead(i);
    }

Instead, it appears to treat the pin addressed by `digitalWrite(i + 4, LOW);` as one of the digital pins.

Do I really have to explicitly specify A0, A1, A2, ... anytime I want to loop over the analog pins?

body:
Your first loop will work just fine indeed, however, you might want to add `delay(1);` after you `analogRead(i);`, to give the ADC some time to settle.

Could you elaborate on what you are trying to do with your second piece of code? As it looks right now, it doesn't really make sense to use *analog inputs* as *digital outputs*.

Besides, you're trying to read a pin's input just a couple of lines after you specified the pin to be an output.

Please explain what you are trying achieve, so the nice folks around here can you help you better.


body:
Yes, the analog pins must be addressed using A0, A1,... when using them for digital I/O.

Depending on the board you are using A0,A1,etc. are mapped to different values (for instance it looks like A0 is 18 on some boards but 14 on others.

One solution for looping over the analog pins would be this:

    static const uint8_t analog_pins[] = {A0,A1,A2,A3,A4};
    // Setup pins for input
    for (int i = 0; i < 5; i++) { //or i <= 4
      digitalRead(analog_pins[i]);
    }

If you are using the analog pins only with the `analogRead()` call you can use 0,1,... instead of A0,A1,...


body:
At least an Uno/Megas/leonardos, all the values mapped to analog pin numbers are consecutive, so

    for (int i = A0; i < A4; i++) {
      pinMode(i, OUTPUT);
      digitalWrite(i, LOW);
    }

will set A0, A1, A2, and A3 to OUTPUT, and then LOW.


body:
Pins 14 through 19 are the analog pins A0 to A5. `A0` is just an alias for `14` and so on.

So another way of writing BrettM's answer:

    for (int i = 14; i < 18 i++) {
      pinMode(i, OUTPUT);
      digitalWrite(i, LOW);
    }


body:
I know this is old, but if you hover your mouse over A0 to A7 in visual micro it will show you the true value, they are just a variable (it actually shows as 14U but while addressing you do not need to include the U). What Craig said is wrong, they do NOT have to be addressed by A0, A1 ect..

A0 = 14
A1 = 15
.
.
A7 = 21

    //Will set all pins, digital and analog to LOW (0)
 for (int i = 1; i < 22; i++) {
  digitalWrite(i, LOW);
 }

 //Will set all analog pins to LOW (0)
 for (int i = 14; i < 22; i++) {
  digitalWrite(i, LOW);
 }

 //Will set all analog pins to LOW (0)
 for (int i = A0; i < A7 + 1; i++) {
  digitalWrite(i, LOW);
 }

The last for loop is basically saying i = 1 (A0), and stop on 21 (A7).


body:
Assuming pin numbers are consecutives you can iterate them:

```cpp
int acc = 0;
for (int Ai = A0; Ai < A0 + NUM_ANALOG_INPUTS; Ai++) {
    acc += analogRead(Ai);
}
Serial.println(acc);
```


message:
Programming arduino via bluetooth module issue

I followed a [tutorial][1] on how to setup arduino and bluetooth so it can be programmed without usb cables. I didn't use capacitors or resistors asthere doesn't seem to be a need for them. I have the serial output appearing on arduino serial console via bluetooth (no usb cable connected). Since the is a working connection that means it is working to a point. However when trying to upload I get "avrdude: stk500_getsync(): not in sync: resp=0x4c" error.

I didn't connect pin 32 of hc-05 to arduino reset pin yet, could that be the issue? I don't actually need arduino to be reset since I can just kill the power to it manually at least for now. I also used 9600 as baud rate instead of 115200 as in the tutorial, because my arduino code used 9600 but maybe I misunderstood this and it actually needs to be 115200 regardless or my baud rate in arduino code?

What else could be the cause?

  [1]: http://makezine.com/projects/diy-arduino-bluetooth-programming-shield/

Edit 1:

From the answer by @sachleen I changed the baud rate as per the tutorial and soldered pin 32 of the hc-05 module to rst pin of arduino.

After baud rate change opening arduino serial console no longer outputs anything. Why did this happen? I was getting serial output before when baud rate of hc-05 was 9600.

After soldering the rst pin arduino also seems to reset after serial console is opened. I did not add the capacitor, is it required and if so why? I also excluded resistors since it seems they are only for voltage reduction from 5v to 3V (my arduino is 3.3V version).

body:
Both of those things will cause issues.

It needs to reset when its downloading a new sketch. You can manually reset it at just the right moment, but if you don't get the timing right, you'll get that issue.

The baud rate you set in your code for serial communication becomes irrelevant when you're loading a new sketch as that's set in the bootloader. Keep it at 115200 like the tutorial suggests.


body:
Have you got the TX from the Bluetooth module linked to the RX pin of the Arduino?

If you have you need to unhook it whilst uploading. A better solution is not to use the TX RX pins of the Arduino and use serial software instead.

Here's a simple tut but it spreads over a few pages:

http://ianlangelectronic.webeden.co.uk/#/arduino-bluetooth/4583456314

A Bluetooth baud rate bigger than 9600 is not recommended. The Arduino struggles to keep up if it's much faster than this.


body:
I wrote the tutorial you were following so maybe I can help. When I was building the circuit initially I used some of the other tutorials out there on Arduino Bluetooth programming which don't have a lot of the extra resistors and capacitor.  However, I couldn't get any of those to work reliably.  Using a circuit simulator and some trial and error, I ended up with the circuit shown in the tutorial which worked for me.

While there "doesn't seem to be a need for" some of the extra passives, if your circuit doesn't work without them, perhaps there is a need for them after all? ;-) Now, I have heard from other people that they were able to leave out certain bits so it seems that there is some variability in the hardware. But we're talking four passives to ensure reliable operation, so why leave them out?

Anyway, a couple of points:

1. Pin 32 on the HC-05 becomes active upon Bluetooth connection.  We configure the pin to be active low so we can use it to auto-reset the Arduino upon serial connection to emulate what happens with the normal USB connection.  You can leave out the connection to pin 32 only if you want to have to manually reset the Arduino to program it.

1. The 115200 baud rate is the rate for programming the Arduino and is set by the Arduino bootloader.  It is possible to re-flash the bootloader with a different configuration if you needed to for some reason.

So, the programming baud rate is fixed in the bootloader, but the communication baud rate is configurable in software using `Serial.begin()`. However, the HC-05's baud rate has to be the same as the Arduino's, so you need to stick with the same baud rate for both programming and communication (115200 by default).

1. There are two resistors involved with the reset, R3 and R2.  I believe R2 is only necessary for 5V Arduinos to act as a voltage divider with R3.  However, R3 should be included for any voltage Arduino. See this [Atmel design note](http://www.atmel.com/images/atmel-2521-avr-hardware-design-considerations_application-note_avr042.pdf) - "The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically ... This pull-up resistor makes sure that reset does not go low unintended." R3 should be 4.7k or greater; most designs stick with 10k.

1.  The capacitor C1 is necessary because Pin 32 stays low the entire time Bluetooth is connected.  If you connect RST to Pin 32 directly, the Arduino will just stay reset until the Bluetooth connection drops and nothing will work just as if you held down the reset button and never let go.

With C1 in place, when Pin 32 goes low it will momentarily discharge C1, pulling RST low and resetting the Arduino. C1 will immediately begin charging through R3 back up to VCC which will restore RST to high, bringing the Arduino out of reset.  The values of R3 and C1 affect the timing of the reset and must be chosen appropriately.

5. Don't forget R1.  I can't remember the reason it is helpful, but it has something to do with the Arduino/Atmel UART.  I found the recommendation for adding it one day on an Atmel discussion board and it has solved a non-working circuit for me many times.

Hope that helps!


body:
The baud rate depends on model of arduino you are using. For Pro-Micro; Pro-Mini and Nano that I use I had to change to 57600 baud as that is what the dll (downlineloader) avrdude forces this baud rate:

    avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM40
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600

For Mega the overriding Baud Rate is 115200.


body:
The easiest way to program your arduino via bluetooth (HC-05) is the following steps

 1: change the baud rate of the bluetooth module to 57600 using software seriel, and that is all you need to do with your bluetooth, and when you use the software seriel sketch you do not need a ftdi converter, this is how you do it (  https://www.youtube.com/watch?v=zoJUAjW3vQ0 )

2: next step is to make a very simple and small circuit for the reset pin of your bluetooth module like the one in this youtube link ( the circuit I am talking about is a circuit made of a NPN transistor, a 0,01 capacitor and a 10 k resistor. the circuit is like a signal inverter or something. (https://www.youtube.com/watch?v=xXUKfTNHkKE). you will find the circuit in the middle of the video.

I have done it and it works,

thanks for reading
Arman


message:
Arduino reading serial data non-blocking

<!-- language-all: lang-C++ -->

I have an Arduino reading serial data and responding to other inputs as well, I'm trying to read incoming serial data without using the while, if at all possible. the incoming serial data will be formatted in a specific manner each time and will be CSV; It will look like such:

    19,1400700083, 1-0,1-10,and other values delimited with a new line character "/n".

The first value will tell how many bytes are coming in so the serial receive function wont parse data until it gets all the bytes,second value is a Unix time-stamp, the third value (1-0) is the "get" or set" value; which will tell the Arduino to return a value or to set a value. The fourth (1-10) value will correspond to what variable to get or set. and the other values will be integers as well but are dependent on the other values.

My code is as follows:

    void CheckSerialData() { // begin function

      if(Serial.available() >= 2) { // begin one, first line will be how many bytes incoming.
      int NumberOfIncomingBytes = Serial.parseInt();
        if(Serial.available() >= NumberOfIncomingBytes) { //begin two
        int IncomingTime = Serial.parseInt();
        setTime(IncomingTime); //time is always incoming with serial values
        int GetOrSetValue = Serial.parseInt(); //this value should be 1 or 0 for "getting values(1)" or "setting values(0)"
          if(GetOrSetValue == 1) { //BEGIN THREE
            int ValueToGet = Serial.parseInt();
              switch(ValueToGet) {// BEGIN SWITCH
                case 0:
                  Serial.print(GetTemp());
                  Serial.print("/n");
                  break;
                case 1:
                  //serialwrite yaw pitch roll
                  break;
                case 2:
                  Serial.print(GetVoltage());
                  Serial.print("/n");
                  break;
                case 3:
                  //append all RGB final values together and serial print it
                  break;
                case 4:
                  //print out accel values
                  break;
                case 5:
                  //print alarm alarmed status
                  break;
                case 6:
                  //print out last time alarm set off
                  break;
                case 7:
                  //print out time allowed lights to turn on
                  break;
                case 8:
                  //print out arduino time
                  break;
                case 9:
                  //print out system summary, (time,voltage,temp,yaw,pitch,roll,accel
                  break;

              }//END SWITCH
             }//END THREE
          else { //BEGIN TWO B //SET VALUES
          int ValueToGet = Serial.parseInt();
              switch(ValueToGet) {// BEGIN SWITCH
                case 0:
                  //set global rgb value set LEFT
                  break;
                case 1:
                  //set global rgb value set RIGHT
                  break;
                case 2:
                  //set global alarm value
                  break;
                case 3:
                  //set global angle to start flashing emergency led's
                  break;
                case 4:
                  //set turn signal RGB value
                  break;
                case 5:
                  //set time that lights are ok to turn on
                  break;
                case 6:
                  //set light override value
                  break;
                case 7:
                  //set pattern enable
                  break;

              } //END SWITCH

          }//END TWO B

              }
            }//end two
          }//end one
        }//end function
        //**********************END SERIAL FUNCTION**************************

I would like to know if this looks like it can work, or am I going about this all wrong?

(I don't have access to my Arduino currently to test the code)

body:
Unfortunately your code could end up dropping data quite easily, or parsing it incorrectly.

Let's say your code has successfully read the first couple of bytes into `NumberOfIncomingBytes`. However, when it reaches `begin two`, let's imagine the sender hasn't finished sending all the data yet.

Your code will drop through to `end two`, discarding the `NumberOfIncomingBytes` value it just read. Next time round, it will start all over again from scratch, and attempt to read `NumberOfIncomingBytes` again. However, that data isn't there anymore. The next data waiting on serial will actually be the timestamp from the previous message.

From there, it could end up parsing arbitrary data with unpredictable results, getting completely out-of-sync with the sender.

A way to fix it would be to store the `NumberOfIncomingBytes` value outside the function (e.g. as a global variable), along with a flag indicating if you're still waiting for the rest of the data to arrive. At the start of `CheckSerialData()`, the code should check that flag. If it's true, then it should skip trying to read `NumberOfIncomingBytes`. Instead, go straight on to `begin two`.

An alternative approach would be to avoid using `NumberOfIncomingBytes` at all. Each call to `CheckSerialData()` would read whatever serial data is available, and accumulate it in a buffer. As soon as it hits a newline character, it will stop reading, and parse the data it's accumulated. If it runs out of serial data before it hits a newline, it should stop and carry on from there next time it's called.


message:
bootloader uploading into Atmega328

![enter image description here][1]

Here is mine circuit. Intially i used arduino UNO directly for programming. Now i am Using atmega 328 IC for programming. I am trying to connect 32 hall sensor via Mux circut. I wanted to How to upload boot loader or HExfile Here. Will avr pocket programmer satisfy above circuit or i need to add addtional circuit here
[AVr pocket programmer][2]

  [1]: https://i.stack.imgur.com/EhaCw.jpg
  [2]: http://www.rhydolabz.com/index.php?main_page=product_info&products_id=597

body:
The AVR pocket programmer should work fine. Sparkfun has a [good guide for doing this](https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader/connecting-the-programmer).

Here's the pinout of the Atmega328:
![Atmega328 Pinout](https://i.stack.imgur.com/t7SJV.jpg)

You'll want to connect your programmer as follows (note, these are the pins for the bare Atmega328 chip *only*. The pin numbers on an Arduino board are different.):
<pre>
Programmer Pin		Atmega328 Pin
5V			Vcc (7)
GND			GND (8)
MOSI			Digital 11 / Physical 17
MISO			Digital 12 / Physical 18
SCK			Digital 13 / Physical 19
Reset			Reset (1)
</pre>

Note that the physical pins on the chip are numbered differently than the logical pins. In the table above the "Digital" pin numbers are those colored yellow in the figure, while the "Physical" pins correspond to the black-on-white numbers around the edge.

If you already have the ICSP header connected to those pins (it's not completely clear in the schematic if that is the case), you can connect the programmer to those pins instead. This can be easy if you have a 6-pin ICSP cable with your programmer.

Also, if you are already powering your Atmega328 from some other 5V power supply you can omit the `5V-Vcc` pin. However, the programmer and the Atmega328 *must* share a common ground, so be sure the GND pins are connected.

Connect your programmer to the computer using USB, open the Arduino IDE, select the correct serial port of the programmer, and pick "Arduino Uno" in the "Board" menu. You can program the bootloader by selecting "Burn bootloader" in the Tools menu, or you can simply write your program by selecting "Uploading using programmer" in the File menu.


body:
Uploading Hexfile to your arduino can be done using this application:

http://kmtronic.com/upload-hex-files-to-arduino.html

------------------------------

This is how you upload an Arduino Bootloader on an empty ATmega328 / ATmega328P-PU. Using an Arduino. (No need for a separate ISP Programmer).

From Arduino Uno to other Arduino Uno.

1. Open the ArduinoISP firmware (in Examples) to your Arduino board.
2. Select the items in the Tools > Board and Serial Port > Arduino Uno.
3. Upload the ArduinoISP sketch.
4. Wire your Arduino board to the target as shown in the diagram below. (Note: you'll need to add a 10 uF capacitor between reset and ground.)
5. Also connect TX from Arduino A to the RX of Arduino B and RX from Arduino A to TX Arduino B.
6. Select Target Board in Tools > Board > Arduino Duemilanove w/ ATmega328
7. Select programmer in Tools > Programmer > Arduino as ISP
8. Use the Burn Bootloader > Arduino as ISP command.
9. Go to Tools and Select Burn Bootloader. Done.

![Upload to other Arduino Board][1]

To upload on a breadboard without External clock.

1. Download: [Breadboard.zip][2]
2. Put boards.txt in your Arduino directory under Hardware > ATmega328. (For windows usually (C:/Program files/Arduino/Hardware/ATmega/boards.txt))
3. Close Arduino IDE and reopen it.
4. Open the ArduinoISP firmware (in Examples) to your Arduino board.
5. Select the items in the Tools > Board and Serial Port > Arduino Uno.
6. Upload the ArduinoISP sketch.
7. Hook pin13 from Arduino to pin19 on Chip
8. Pin12 from Arduino to pin18 on chip
9. Pin11 from Arduino to pin17 on chip
10. Pin10 from Arduino to pin1 on chip
11. pin0 from Arduino to pin3 on chip
12. pin1 from Arduino to pin2 on Chip
13. connect 5V from Arduino to pins 7 and 20 on chip
14, connect GND from Arduino to pins 8 and 22 on chip
15. Select Target Board in Tools > Board > ATmega328 on breadboard (8 MHz internal clock)
16. Select programmer in Tools > Programmer > Arduino as ISP.
17. Select Tools > Burn Bootloader. Done.

It's also possible with an Arduino Leonardo but you'll have to change some settings for that.

Note: You will need to put target board to Arduino Duemilanove w/ ATmega328 for programming the new chip (Uploading a code to it) instead of targeting Arduino Uno.

  [1]: https://i.stack.imgur.com/cVfzF.png
  [2]: http://arduino.cc/en/uploads/Tutorial/Breadboard.zip


message:
What is the smallest microcontroller capable of running Arduino?

I'd like to know which is the most powerful, lightest, and perhaps least expensive micro controller capable of running Arduino.

body:
Well, your questions is quite vague and perhaps overly broad.  I'll answer your main question "what is the smallest," assuming you meant dimensionally, while keeping in mind that you also want the most powerful one in that size. The pricing of different chips like this will be fairly similar so I'll ignore that.

Next, I'm not sure what you meant by saying "capable of running Arduino" which may mean capable of having the Arduino bootloader installed or could mean being capable of running code written with Arduino libraries.  I'll assume the latter since it's the most practical requirement. I'll also assume you want an Atmel chip since it will be the most directly compatible with the Arduino libraries.

So what is the most powerful of the smallest Atmel microcontrollers capable of running Arduino code?

<strike>The answer is probably the [Attiny 10][1] which comes in a 2 x 2mm 8-UFDFN Exposed Pad package, or a 2.9 x 1.6mm SOT-23-6 package for about one dollar in small quantities.

Also see this [Hackaday article][2] on how to use the Attiny10 with Arduino.</strike>

Edit: After more research, I was unable to find an Arduino core for the Tiny10. So while you can program it with an Arduino using assembly or something, writing Arduino code for it won't work.  The smallest Attiny with an [Arduino core][3] I could easily find is the [Attiny13][4] in a 3 x 3mm 10-VFDFN package.  The upside is that while not being that much bigger or more expensive, it's a way more capable chip for your project.

  [1]: http://www.digikey.com/product-detail/en/ATTINY10-MAHR/ATTINY10-MAHRCT-ND/2774321
  [2]: http://hackaday.com/2012/08/23/programming-the-attiny10-with-an-arduino/
  [3]: https://www.google.com/search?num=20&q=attiny13 arduino core
  [4]: http://www.digikey.com/product-detail/en/ATTINY13A-MMU/ATTINY13A-MMU-ND/1914669


message:
Arduino to Raspberry Pi wired communication

I am new to Raspberry Pi (just brought mine before writing this post), and I am looking to see what is the most ideal way for two way communication between an Arduino and a Raspberry Pi (USB, SPI or I2C).

The reason I am asking is because I need to build a small, semi-autonomous robot and plan on using both the Arduino and Pi to control it, using the pins of the Arduino for the motor control and sensors and the Pi for video processing and autonomous part. Both will be on the robot itself. I am pretty good with the Arduino but never used a Raspberry Pi before.

So my biggest question is what would be the best form of communication for the two boards taking into account speed and safety (there is a voltage difference between the Pi and the Arduino).

body:
Hands down, I can rule out the I2C. [This post sums it all up:](https://electronics.stackexchange.com/a/29041/18442)

>  - SPI is faster.
>  - I2C is more complex and not as easy to use if your microcontroller doesn't have an I2C   controller.
>  - I2C only requires 2 lines.

Since speed is your first priority, either do USB or SPI. I'd personally go with USB, just for the reason that it's simple. Nearly any programming language can inference with COM ports, but that's not the case with SPI. Also, for SPI, you would have to either use a level shifter, or do a voltage divider for the Arduino to RPi wires (for RPi to Arduino wires, Arduino can still sense 3.3V as HIGH.)

Also, [serial can be pretty fast](https://arduino.stackexchange.com/a/299/220). Technically, the Arduino can go up to 2 Mbps (not very fast compared to a lot of things, but fast enough for what the Arduino can even handle). One thing to note, the writer of the post stated that this is the highest you can practically achieve with the poorly optimized libraries:

    Serial.begin(500000);


body:
Firsr of all, When you say "there is a voltage difference", I assume you are referring to the raspberry pi being a 3.3v device vs the arduino's 5v, and not to some kind of ground potential difference. If theres a ground potential difference(which there shouldn't be in a robot), neither i2c or spi or usb will work without extra circuitry.

My short answer would be USB all the way because its easy and built into the arduino and pi. The only issue is that if anything mechanically bumps the usb enough to lose connection, sometimes linux is a little unpredictable with regards to naming serial ports, and when it reconnects it might give the arduino a different serial port name. But this isnt an issue if your cable isnt a cheap worn out one with a flaky connection like the one that bothered me for a hour today.

USB does have about a millisecond of latency because devices are usually polled at 1khz iirc. Using the raspberry pi hardware serial might be a good idea if milliseconds count which I doubt they do.

But on the software side, raspi hardware serial and USB serial are the same. So there should be no problem switching between them if you need to.

I wouldnt bother with i2c or spi. Why fuss around when serial works so well?


message:
Arduino Master-Slave Pins

Can I change the pins on the communication for a Master-Slave arduino Wire transmission? I want to communicate between 2 arduinos, but on one of them A4&A5 are taken

body: You cannot. Wire uses hardware I2C, and on the Uno only A4 and A5 are connected to the TWI peripheral on the MCU. You will need to either switch to a bit-bang I2C implementation or change the protocol you're using.


body:
To complete Ignacio's answer, there's indeed no other hardware I2C on AVR Arduinos.

The only options you have to use other pins is:

 * to use bitbang i2c, which is way slower ;
 * or you can switch to the Arduino Due which features two TWI ports ;
 * or you can use an SPI to I2C serial bridge such has [that one][1].

[1]:http://www.silabs.com/products/interface/spitoi2c/Pages/default.aspx


message:
controlling LEDs, few pin outputs lots of LEDs

We need to control many leds, about 40 with arduino (UNO) and we need some remain turned on and other off at the same time. Muted or pinned vary constantly.
What should I use to do this, I have several Multiplexers CD4051 but with these I can just light a LED at a time.

I do some calculation and then need to turn LEDs 1,2,5,7 and need to be pinned to the following calculation. In the following calculation I need to turn leds 4, 5, 10, 12 pinned and need to follow. What I need is something like that

With the multiplexer I can turn the LEDs I need and with minimal delay and it seems they are apprehended while, but I want to know if there is another alternative to do so

body:
The most common technique for doing this is called "multiplexing". You arrange the 40 LEDs into 8 "columns" and 5 "rows" with common anodes and cathodes, and then you switch the columns or rows on or off individually, activating only the LEDs you want lit for that column or row. If done quickly enough it appears to the human eye that the LEDs are always lit due to persistence of vision. Note that the *physical* display does not need to be a rectangle; this is simply the *logical* arrangement used in order to simplify the circuit.

![LED multiplexing demonstration][1]

*(note that the cathode side of the above image is wrong; the cathode needs to be **low** when you want the LED to light)*

(source)

A naive implementation with 8 columns and 5 rows would use 13 pins to connect them all. However, since you don't need more than one column at a time what you can do is use a 74HC138/238 to use 3 inputs to control which of the 8 columns you want to activate. This drops the number of required pins to 8, which is low enough for anything larger than a ATtinyX5. Use of a 74HC595 for the 8 pins further drops the required MCU pins to 3, which is low enough for even a ATtiny4/5/9/10, but the timing is harder to get right due to the shift register.

  [1]: https://i.stack.imgur.com/UCqdw.gif


body: Check out [NeoPixels](https://www.adafruit.com/category/168). Make sure to check out the datasheet, as a single Arduino Uno might not be able to provide the required current.


message:
help with input in a Simon arduino uno game

I' making a Simon game with the arduino uno.

I know something is wrong with the inputs but i don't know why or how to fix it.

The problem is the program takes an input and says it is correct no matter what it is or the length

    #define NOTES

    int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6};
    String sequence;

    void setup() {
        pinMode(13, OUTPUT); //green
        pinMode(12, OUTPUT); //yellow
        pinMode(11, OUTPUT); //blue
        pinMode(10, OUTPUT); //red
        pinMode(7, INPUT); //green
        pinMode(6, INPUT); //yellow
        pinMode(5, INPUT); //blue
        pinMode(4, INPUT); //red
        Serial.begin(9600);
    }

    void loop() {
        while(true) {
            delay(1000);
            randomSeed(random(random(1000000000)));
            sequence = String(random(4));
            boolean run = true;
            while(run) {
                for(int i = 0; i < sequence.length(); i++) {
                    simonOut(sequence.charAt(i) - '0');
                    delay(500);
                    simonClear();
                    delay(100);
                }
                for(int i = 0; i < sequence.length(); i++) {
                    int input = simonIn();
                    while(input < 0 || input > 3) {
                        delay(50);
                        input = simonIn();
                    }
                    if(sequence.charAt(i) - '0' == input) {
                        flash(0);
                        run = false;
                        goto reset;
                    }
                    else if(i = sequence.length() - 1)
                        flash(3);
                }
                sequence += random(4);
            }
            reset:;
        }
    }

    void boolOut(long pin, boolean val) {
        digitalWrite(pin,val ? HIGH : LOW);
    }

    void simonOut(long num) {
        boolOut(num + 10, true);
        tone(2, tones[num]);
    }

     void flash(int led) {
         delay(300);
         for(int i = 0; i < 5; i++) {
             simonOut(led);
             delay(100);
             simonClear();
             delay(100);
         }
     }

     void simonClear() {
         for(int i = 0; i < 4; i++){
             boolOut(i + 10, false);
         }
         noTone(2);
     }

     int simonIn() {
         int ret = -1;
         for(int i = 0; i < 4; i++) {
             if(simonIn(i)){
                 ret = i;
             }
         }
         if(ret != -1) {
             simonOut(ret);
             delay(500);
             simonClear();
             delay(100);
         }
     }

     boolean simonIn(long num) {
         return digitalRead(num + 4) == HIGH;
     }

body:
Is it possible that your problem might be just a typo?

>  #define NOTES
>
> int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6};

In your array you talk about NOTE and you defined NOTES (See the S?)


body:
The problem in your code is there:

    int simonIn() {
        int ret = -1;
        for(int i = 0; i < 4; i++) {
            if(simonIn(i)){
                ret = i;
            }
        }
        if(ret != -1) {
            simonOut(ret);
            delay(500);
            simonClear();
            delay(100);
        }
    }

This method never returns any value, so that means the caller will just tke whatever is in the stack at that time:

                int input = simonIn();
                while(input < 0 || input > 3) {
                    delay(50);
                    input = simonIn();
                }

`input` could be anything there.

So the fix should be easy:

    int simonIn() {
        int ret = -1;
        for(int i = 0; i < 4; i++) {
            if(simonIn(i)){
                ret = i;
            }
        }
        if(ret != -1) {
            simonOut(ret);
            delay(500);
            simonClear();
            delay(100);
        }
        return ret;
    }

It's surprising you did not get a **warning from the compiler** on that one, which IDE do you use?

Finally, regarding your code, I would also advise you the following improvements:

- break down the `loop()` code further into functions that do **ONE** thing, e.g. `showSequence(sequence)`, `checkInput(seuquence)`, `readSimonInput()` (this last function would only return a value between 0 and 3 included. That would make your code much clearer.
- use the right types for your variables: I see you abuse usage of `long` where `int` or `byte`, or you mix different types for the same data, thus forcing the compiler to cast data on some function calls.
- avoid hardcoding constants in your code, e.g. you could define the number of buttons, the first pin of buttons, the first pin of LEDs, the various delays.