body:
I had fun making a 3x3x3 led cube. Now I want to build a bigger one. I'd like to find out the best IC for it. I've seen that some projects uses multiplexer like 4051 or 74HC595.

I'd like to make it at least 8x8x8 (so the multiplexer has to easily be spotted in cascade), possibly supporting also the pwm (to fade the leds).

And I'm a little bit scared by the real time with a lot of LED.. do I have to solve the problem in hardware (with a "faster" multiplexer) o via software?

title: Best multiplexer for a led cube

Answers: 2

body:
Those aren't multiplexing chips. Those are just chips to give you more outputs than your arduino has.

The multiplexing is just done on the microcontroller. But it depends on how you are wiring the leds. You can wire the cube to use less digital outputs, but you'll end up with a less bright leds.

You could use no multiplexing. That way the leds are lid with a 100% duty cycle. But for that you'd need 512 outputs.

You can choose to light up only one level at a time. That way you only need 72 outputs (64 for the leds, and 8 for selecting the level). This is a form of multiplexing. Since only one level is lid at a time, the leds have a duty cycle of 12.5%. Please note that because of the way humans perceive light, it will look more like 1/3rd the brightness, instead of 1/8th (so that's great). Also note that since you only need one level to be on at a time, some people prefer to use a decade counter IC for that.

You could also choose to only light one row at a time. That way you only need 24 outputs (8 for the leds, 8 to select which row, 8 to select which level). But you'd need some additional circuitry to combine row- and level-selection.

There are specialized multiplexing IC, but those only support rows and colums (not level). So you need 1 chip for each level, and more problematically you need to run 8-row and 8-culumn wires for each level to the bottom. That's quite a bit of wire, which might ruin the aesthetics of the cube.

In short. There are quite a few ways of making a 8x8x8 cube. I'd suggest finding a well documented build from someone else that you like and follow that.

Quite a bit of information. I hope it's of help. If you have any more question feel free to ask.

body:
You could use a few TLC 5940 PWM Drivers (http://www.ti.com/product/tlc5940).

Each one has 16 channels which would mean to power an 8*8*8 cube would need 32 Drivers.

However, you can use multiplexing to reduce the number of 5940's you would need.

For example, you could use 4 X 5940's which would give you 64 channels and use 8 X time multiplexing to give you 512 channels.

There are 4096 PWM steps giving you lots of control over brightness and can take up to 17v which should be more than enough for any LED.

One of the added features for the 5940 is because it is a current sink, you dont need a resistor on every LED.

I am currently working on a project with TLC5940's that requires control over 512 RGB LED's meaning I have  1536 individual channels to control


body:
Is there any free/open or commercial/paid Arduino IDE Sketch Debugger (not Atmel chip factory standard tool set) with Breakpoint and Variable read/set capability?

I read about VM on web. Is there any similar product?

title: Debugger with Breakpoint and Variable read/set capability

Answers: 2

body:
There is something quite close to what you are asking.
You need either the (more expensive) ICEMKII (iirc) or the (cheaper) AVRDragon.
Then it's possible to [use][1] it with gdb.

In practice the AVR supports only one breakpoint, so what happens is that the binary in flash will be dynamically patched.
This will slightly reduce the life of the AVR, but I think it's fairly acceptable. One can always use Arduino UNO with the original DIP package for AVR, mounted on a socket. Then it's sufficient to replace the burnt microcontroller and keep the rest (but it's hundreds of thousands of programming cycles before the AVR fails).

  [1]: http://awtfy.com/category/microcontrollers/

body:
There is an on-target [debugger][1] in [Cosa][2] and a port of the library for [Arduino/AVR][3]. It allows conditional and unconditional break- and observation points, simple call back-trace, variable read, memory status check, memory dump, etc.

[![Debug Demo Sketch][4]][4]

The debugger is implemented as a small command handler that is executed on the target (Arduino). A set of macros are used to mark break-points, variables to observe, etc.

Please see the debugger [demo sketch][6] for more details.

  [1]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Debug/Debug.hh
  [2]: https://github.com/mikaelpatel/Cosa
  [3]: https://github.com/mikaelpatel/Arduino-Debug
  [4]: https://i.stack.imgur.com/QsIMN.png
  [5]: https://i.stack.imgur.com/igAAB.png
  [6]: https://github.com/mikaelpatel/Arduino-Debug/blob/master/examples/DebugDemo/DebugDemo.ino


body:
I have a raspberryPi and Arduino connected via i2C. On the RPi I have a python script that takes int values and simply sends them to the RPi, which in turn echoes them back. I am trying to debug this, since I am unable to send ints larger than 255.

One thought was that I might be able to connect the arduino slave directly to my Mac, and then use the Arduino serial monitor to help with debugging.

Unfortunately the python script will not run, because I assume i2C can only be run on a Linux kernel.

Am I mistaken?

This is an edited portion of my python code

    import smbus
    import time
    # for RPI version 1, use "bus = smbus.SMBus(0)"
    bus = smbus.SMBus(1)

    # This is the address we setup in the Arduino Program
    address = 0x04

    def writeNumber(value):
        bus.write_byte(address, value)
        return -1

    def readNumber():
        number = bus.read_byte(address)
        return number

title: Debugging i2C from Mac OSX desktop

Answers: 1

body:
No, your Mac doesn't have I2C support. It was pointed out [in the comments](https://arduino.stackexchange.com/questions/3351/debugging-i2c-from-mac-osx-desktop#comment6515_3351) that there might be some legacy port, but it won't be usable due to driver limitations.

You're getting a few things confused. USB is it's own technology, separate from I2C/UART/SPI. I'm not sure how you would even *wire* I2C to your Mac. The serial monitor in Arduino is for USB COM ports, not related to I2C.

As far as debugging, there's a few options. First of all, [there are a few ways to debug I2C using an oscilloscope](https://electronics.stackexchange.com/questions/49752/debugging-i2c-bus-using-aCn-oscilloscope). If that's too expensive, you could also get away with a [logic analyzer](https://www.sparkfun.com/products/8938). The one I just linked was at Sparkfun for $150. If that's still too expensive and you're willing to risk $30, [you can find cheap ones on eBay](http://www.ebay.com/itm/2-in-1-USB-Blaster-amp-Logic-Analyzer-UART-SPI-I2C-EPM240-CPLD-Cyclone-IV-FPGA-MCU-/231036000665?_trksid=p2054897.l4275) (most with little/no documenation).

I don't know your code, so I can't advise you on how to fix it. If you need to debug at such a low level, extra hardware is needed.

It doesn't seem like a maximum of 255 that odd, since that's the maximum number that you can do with one byte. You might have to split data up into multiple bytes with some sort of delimiter character. With some quick mental math, it seems as two bytes can give you numbers up to 65,535 if you combine both bytes (i.e. `10101010` + `01010101` = `1010101001010101`).

Edit: this seems like the Arduino code you want:

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x04
    int number = 0;
    int num1 = 0;
    int num2 = 0;
    int state = 0;
    boolean secondByte = false;

    void setup() {
        pinMode(13, OUTPUT);
        Serial.begin(9600);         // start serial for output
        // initialize i2c as slave
        Wire.begin(SLAVE_ADDRESS);

        // define callbacks for i2c communication
        Wire.onReceive(receiveData);
        Wire.onRequest(sendData);

        Serial.println("Ready!");
    }

    void loop() {
        delay(100);
    }

    // callback for received data
    void receiveData(int byteCount){
        while(Wire.available()) {
            if(secondByte) {
                num2 = Wire.read();
                number = (num1 << 8) + num2;

                Serial.print("data received: ");
                Serial.println(number);

                if (number == 1){
                    if (state == 0){
                        digitalWrite(13, HIGH); // set the LED on
                        state = 1;
                    }
                    else{
                        digitalWrite(13, LOW); // set the LED off
                        state = 0;
                    }
                 }
             } else {
                 num1 = Wire.read();
             }
             secondByte != secondByte;
        }
    }

    // callback for sending data
    void sendData(){
        Wire.write(num1);
        Wire.write(num2);
    }

The Python code will have to do the similar thing. Note: the first part of the number (reading left to right) will be sent first.


body:
I am currently working on a Arduino project that combines an InertiaOne IMU sensor board (from Atmel), with an Arduino UNO and two motors driven by a Makeblock driver board. All sensors communicate using I2C, with different addresses. My issue is that the program runs just fine for a while (everything between 1 second and 2 minutes), but suddenly lock up inside the Wire.requestFrom-function that handles I2C communication. More specifically, I believe that the code hangs at one of these points in the Wire library (the code is a direct copy):

    ...
    // wait until twi is ready, become master receiver
    while(TWI_READY != twi_state){
        continue;
    }
    ...
    // wait for read operation to complete
    while(TWI_MRX == twi_state){
        continue;
    }

As far as I know, there are only two units that utilise I2C in the system, both of which are embedded onto the InertiaOne circuit board. What I find very strange is that reading these two sensors works just fine when no motors are running, but that the problem occurs when the motors are activated. My first reaction was to use separate power supplies for the motors and sensor board since the issue could have been caused by a dip in the voltage and a reset of the sensor board, but without any change of result.

I am running out of things to try, and do simply not have the required understanding of I2C and embedded systems to see what exactly the issue is. Could it simply be that some of my parts are faulty, or am I perhaps overlooking something?

title: Lockup while evaluating Wire.requestFrom function (Arduino)

Answers: 1

body:
The Wire library has an issue in the lines you posted, that if an interrupt is lost, it will stay in that loop forever. There are two things you could do to fix this:

* Stop the interrupt from being lost (ie. fix electrical problems)
* Use a library that has a time-out.

For the electrical issues, I would make sure you have pull-up resistors from SDA and SCL to +5V - typically 4.7k (for each one), but that would depend a bit on whether the device already has them. Also make sure you have decoupling capacitors on the Vcc lines as appropriate.

For the software side, there is an alternative library (master only) at [
Arduino I2C Master Library](http://dsscircuits.com/articles/arduino-i2c-master-library).

I haven't personally needed to use that library, as with pull-up resistors and short cable runs, I haven't had problems with the Wire library. However if things are marginal you may well find that it helps.


body:
I want my real-time clock to set its time as the time on my PC. However, when I run the following sketch, the real-time clock reports the time as being 32-33 seconds earlier than my PC says the time is.

    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 RTC;

    void setup () {
      Serial.begin(57600);
      Wire.begin();
      RTC.begin();

      if (! RTC.isrunning()) {
        Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // uncomment it & upload to set the time, date and start run the RTC!
        RTC.adjust(DateTime(__DATE__, __TIME__));
      }
    }

    void loop () {
      DateTime now = RTC.now();
      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(' ');
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
    }

I have also tried manually setting the time on the RTC, but I end up with the same problem: the RTC is always 32-33 seconds behind what I set it to. The lag happens as soon as I run the sketch. It seems very odd to me that no matter how I try to set the time, I end up with exactly the same error. I can tell the Arduino to report the time as being 33 seconds after what the RTC says it is, but this solution seems kind of sketchy, and I am worried that something is fundamentally wrong with my RTC or the way I am using it.

I am using an Arduino Uno with an Assembled Data Logging Shield from Adafruit. The data logging shield uses a DS1307 RTC. Has anyone had this problem before, or have any ideas about what could be causing it? Any help would be much appreciated.

title: Why is my real time clock getting the wrong time from my PC?

Answers: 5

body:
The `__DATE__` and `__TIME__` are set when the code is compiling so they will naturally be behind since the code still needs to finish compiling and then be flashed to the chip.

See the [Arduino Playground][1] for an example of how to sync it to your computer over serial.

> TimeSerial.pde shows Arduino as a clock without external hardware.
>
>   It is synchronized by time messages sent over the serial port.   A
> companion Processing sketch will automatically provide these messages
> if it is running and connected to the Arduino serial port.

  [1]: http://playground.arduino.cc/code/time

body: The Arduino takes the computer time and sends it to the DS1307. The time it takes to copy is the one you are seeing wrong. I would solve the problem by advancing the computer time the necessary seconds that you say is delayed and when programming you should have the exact time.

body:
You can fix the offset by calling once the following code in the `setup()` function:

    RTC_DS3231 rtc;

    DateTime now = rtc.now();
    rtc.adjust(DateTime(now.unixtime() + 10)); // add 10s to current time for fixing the offset

body:
I am experiencing a similar problem with an Arduino UNO and a Nano. Both from the same PC.
 Indeed it looks like the time it takes from compile time to upload + MCU start is reflected.

Assuming the RTC has a good battery and the compilation + upload times are consistent, then adding a drift compensation to the code seems to do the trick.
Here's how I did it (in my case 7 seconds did the "trick" - sorry for the hardocode, but that's for mere description purposes):

    RTC.adjust(DateTime(__DATE__, __TIME__));
    DateTime t = DateTime(RTC.now().unixtime()+7);
    RTC.adjust(t);

Regards,
Hugo Bertini

body:
With the <DS1307RTC.h> library the DS1307 can be adjusted during time setup, by using a global variable and then adding this to Sec reading in the getTime() function, for example as follows:

    #include <DS1307RTC.h>
    tmElements_t tm;
    byte adjustt = 8;  // adustment for seconds lag allowing for compiler download time

    /*********************

    bool getTime(const char *str) {
      int Hour, Min, Sec;
      if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
      tm.Hour = Hour;
      tm.Minute = Min;
      tm.Second = Sec + adjustt;
      return true;
    }


body:
I've just received my Uno today and already I think I may have broken it :(

I was able to connect to usb and upload a sketch (the blink). However, I then tried to connect a circuit to do the Hello World LCD example. After trying this a few times, I noticed the LCD chip get very hot...and I had mis-wired it. In any case, after a few more tries, the USB connection to my Arduino UNO stopped working.

I tried swapping the cable, connecting it to another mac and to a windows with no luck. I'm worried I may have shorted the USB bus chip when trying Hello World.

I also tried connecting a 12V DC power supply.

I still get the green power light and the amber L light...
Did I break my Uno?
How do I troubleshoot this one?
thanks

title: Arduino UNO USB not recognized

Answers: 2

body:
When the LCD pulled enough current to overheat, the Arduino's power supply (which I gather was the Uno's USB interface, at the time) was probably stressed to the point of failure. One fortunate result is that the Arduino took the hit instead of the computer's USB port that was supplying it. It's not clear which part was involved but here's a discussion on another forum concerning a [similar failure and replacing the ATMegaxU2][1] which does USB-interface duty on the Uno (x = 8, if it's a rev 2 Uno, x = 16, if rev 3). It may be possible to replace the failed chip - regulator or USB interface (though with LEDs working, it's probably not the regulator). Otherwise, you can probably still program it with an ISP (In System Programmer). But the easiest way to do that is probably involves another Uno.

  [1]: http://embdev.net/topic/331929

body:
You can try and buy the Arduino serial board, and connect it directly to the pins on the Arduino , see if this works, basicly override the Arduino's own interface, or if you have another Arduino you can try and "serial" connect them using the first Arduino as ISP.

Else it is like JRobert says, you could move the chip from another arduino burn it on that one and then put it back, using the second Arduino as a run only.

Last but not least, you may find a cheap broken Arduino board on some online auction site, where the chip is broken, then move the defect chip to your defect board, and the working chip to the working board, and throw the defect Arduino in the electronics recycling.


body:
I bought this thing off of eBay:

![USBtoFT232RL][1]

[eBay Link][2]

Will it allow me to program an ATmega[xxx] (Arduino clone) with a bootloader?

 --> If so, how would I go about it? What should I do, and what should I certainly not do?

 --> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

I'm a bit new to Arduino, and since I learned that a fair amount of the clones being sold on eBay don't have a bootloader, I wondered how to fix this. (and the "barebones" seem to be quite a bit cheaper)

__Answer__ - *summarized from different answers below (as I can only mark one answer below as accepted):*

- Can you use an FT232R to burn a bootloader onto an AVR (such as an ATmega328)?
    + => Yes you can, though it's a bit annoying to do, as it's slow and a bit more complicated than just plug and play. See the first part of [Chris Stratton's answer](https://arduino.stackexchange.com/questions/3361/i-bought-usb-ft232rl-can-i-use-it-to-program-a-bootloader-onto-an-arduino#3364) below.
- I already have a working Arduino style board, can I use that?
    + => Yes, you can use for example a UNO-style board to program another. This process is explained here: [http://arduino.cc/en/Tutorial/ArduinoISP](http://arduino.cc/en/Tutorial/ArduinoISP), which was referenced in the second part of [Chris Strattons' answer](https://arduino.stackexchange.com/questions/3361/i-bought-usb-ft232rl-can-i-use-it-to-program-a-bootloader-onto-an-arduino#3364) below.
- The two options above are too much of a hassle for me, or I don't have an Arduino yet/available, is there another option?
    + => Yes, you can buy a USB to ISP (In-System Programmer) board/programmer. They're pretty cheap and are called USBISP or USBASP for example. Here's an example: [http://www.ebay.com/itm/180980285082](http://www.ebay.com/itm/180980285082), referenced at the end of [MatsK's answer](https://arduino.stackexchange.com/questions/3361/i-bought-usb-ft232rl-can-i-use-it-to-program-a-bootloader-onto-an-arduino#3363). (or an even cheaper one: [http://www.ebay.com/itm/390806886235](http://www.ebay.com/itm/390806886235)).

  [1]: https://i.stack.imgur.com/0SNrQ.jpg
  [2]: http://www.ebay.com/itm/161305918505

title: I bought USB > FT232RL, can I use it to program a bootloader onto an Arduino?

Answers: 3

body: You must use a ISP or (HV)PP programmer in order to write the Arduino (or similar) bootloader to the chip first. Only once you have done so will you be able to program it via a serial connection.

body:
> Will it allow me to program an ATmega[xxx] (Arduino clone) with a
> bootloader?

NO. The serial device can only be used when the Atmel ATmega chip has a bootloader burned onto it.

> --> If so, how would I go about it? What should I do, and what should I certainly not do?

To burn a bootloader onto a Atmel AVR chip you need a "AVR ISP (In-System Programmer)".
There is a small 2x3 pin contact on your Arduino board.

In the Arduino IDE under the menu "Tools", "Programmer" you will find the different "AVR ISP (In-System Programmer)" that you can use.

Please note that some programmer have an 2x5 pin ISP contact and if that is the case you will also need to buy a 2x3 to 2x5 adapter.

Ref.: [http://arduino.cc/en/Hacking/Bootloader][1]

> --> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

Most Arduino clones bought on ebay have info witch clone of Arduino they are.

> I'm a bit new to Arduino, and since I learned that a fair amount of
> the clones being sold on eBay don't have a bootloader, I wondered how
> to fix this. (and the "barebones" seem to be quite a bit cheaper)

Im a bit confused, I have bought ~10 Arduino clones from ebay and all had a bootloader. And they are clones of UNO, Nano, Leonardo and Mini Pro and that is what I uses for settings in my Arduino IDE.

I'm interested in witch ebay clones that doesn't have a bootloader, could you post a comment with that info?

I use a USBASP (example: [http://goo.gl/kCiMd][2]) as my external programmer.

  [1]: http://arduino.cc/en/Hacking/Bootloader
  [2]: http://goo.gl/kCiMd

body:
In fact, you can, but you are unlikely to enjoy it as it will be fairly slow.

While this module is intended for serial communications - which the ATmega won't support until it has a bootloader on it - the chip around which it is built can also be operated in "bitbang" mode:

http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf

Using reconfigured pins of this wired to the ISP pins of your target, and an implementation of the ISP algorithm running on the PC, it will indeed be possible to load a bootloader on to a new ATmega chip.  However, USB is not designed for this type of usage - it is meant to move large blocks of data, rather than to efficiently do sequences of tiny operations.  **The result is that the loading process will be drastically slower than with other methods.**  You may also spend a fair amount of time tracking down software to do it, or writing your own.

If you have an already working Arduino-style board available, you can use that to program your new chip:

http://arduino.cc/en/Tutorial/ArduinoISP


body:
I want to use timer 0 to generate a rectangular signal on OC0A (D11) without the use of Arduino specific functions (that use timers for themselves). When I toggle D11 manually using a loop, I hear a sound in the connected piezo, but with my sample code, I don't hear something:

    #define ALARM_PIN 11

    void setup() {
      digitalWrite(ALARM_PIN, LOW);
      pinMode(ALARM_PIN, OUTPUT);
      noInterrupts();

      OCR0A = 60;
      // Toggle OC0A on compare match
      TCCR0A = (0 << COM0A1)
             | (1 << COM0A0)
      // CTC mode
             | (1 << WGM01)
             | (0 << WGM00);
      // prescaler = 256
      TCCR0B = (0 << WGM02)
             | (1 << CS02);
    }

    void loop() {
    }

Any idea, what could be wrong?

**Update**

I've played with it a little bit more:

    #define LED_PIN 9

    void setup() {
      pinMode(LED_PIN, OUTPUT);
      TCCR0B = (1 << CS02);
    }

    void loop() {
      digitalWrite(LED_PIN, TCNT0 > 250);
    }

This causes my LED to light very dim, so the timer is running up to 255. But as soon as I set TCCR0A, nothing is lighting up:

    #define LED_PIN 9

    void setup() {
      pinMode(LED_PIN, OUTPUT);
      OCR0A = 60;
      TCCR0A = (1 << WGM01);
      TCCR0B = (1 << CS02);
    }

    void loop() {
      digitalWrite(LED_PIN, TCNT0 > 0);
    }

title: Leonardo (32u4): Timer0 problems with CTC mode

Answers: 2

body:
You should re-enable interrupts after you finish setting up. Use either

    interrupts();
or

    sei();
If you want to don't want to use the arduino specific commands. Even if the code does not need interrupts, background code does use them.

Timer 0 is used in arduino for some basic "house keeping" function like keeping time. I'm not sure if that could be part of your problem. you could try using a different timer.

body:
Your value of `60` for `OCRA` will give you tone of around 16666hz which isn't audible to us humans. Try setting it to 255. That should give you a 4000hz tone, which is audible. (Or get your neighbors dog, and see if he dislikes hearing it)

You can use [this online calculator](http://eleccelerator.com/avr-timer-calculator/) to help you get the correct value for `OCRA`.

Note that you need 2 cycles to get a full wavelength (1 low and one high), so two toggles.


body:
When the Leonardo was introduced, I think, I've read some articles about being cautious to do some things, that could cause it to not load any new sketches any more, so one has to rewrite the bootloader. Because I plan to use power-saving options, e.g. to disable unused hardware components like USB port, I fear to do something wrong.

One Leonardo-delicacy I've found so far:

 * if interrupts are disabled, uploading new sketches fails unless one presses the Reset button as soon as the Arduino IDE is showing "Uploading..."

What stuff (except of the usual hardware-related thinks like connecting output-configured pins to fixed potentials) could damage the controller or require to reflash the Leonardo with a fresh bootloader?

title: Leonardo (32u4): ways to brick it programmatically

Answers: 4

body: The one I know of is making the Leonard act like a USB mouse that flaps everywhere and types random keys so you can't reprogram it without doing some kind of trick to get around it. But they mention this on the api docs.

body:
If you upload a program that changes the speed of the USB core it would be almost bricked. What would happen is this:

1. Power on, boot loader starts, USB device enumerated on PC.
2. A few second later program start, USB core speed changed, USB device disappears from PC

The issue here is that not only do you have to hit reset to program, after the reset you have to quickly select the right com port and then upload before the program starts.

The Redbearlab Blend Micro requires a USB core speed to be set in the user program. In their setup instructions there is a step to edit the Arduino main.cpp and add a section to do so. If this step is missed, the above problem happens.

body:
I managed to brickwall an ATMega128RFA1. The bootloader, and the software I uploaded in it, were working fine. But it was impossible to erase/write the ROM.

After checking for what have happened, I discovered in the datasheet that some fuses in the AVR core are intended to protect accidental writing on the ROM. Some kind of security fuses.

I never found the bug which wrote in these bytes (as it was a really big program and we were 3 peoples involved in the coding) but yeah, we just blew a fuse and lost an MCU because of a bug.

As for the leonardo, several things could happen, but none of these can brickwall your board unless you blow one of this protection fuse.

body:
It is possible, [with some really clever code][1], to exploit the bootloader to overwrite itself.

Excerpt:

> The solution is actually conceptually fairly simple. A bootloader, by
> its very nature is designed to download new firmware to the device.
> Therefore it will contain at least one spm instruction. Because the
> spm configuration register must be written no more than 4 cycles
> before the spm instruction it means there are very few sequences that
> practically occur: just sts, spm or out, spm sequences. So, all you
> need to is find the sequence in the bootloader section; set up the
> right registers and call it.
>
> However, it turned out there was a major problem with that too. The
> V-USB self-programming bootloader's spm instructions aren't a neat
> little routine, but are inlined into the main code; so calling it
> would just cause the AVR to crash as it tried to execute the rest of
> the V-USB bootloader.
>
> Nasty, but again there's a solution. By using a timer clocked at the
> CPU frequency (which is easy on an AVR), you can create a routine in
> assembler which sets up the registers for the Bootloader's out, spm
> sequence; calls it and just at the moment when it's executed the first
> cycle of the spm itself, the timer interrupt goes off and the AVR
> should jump to your interrupt routine (in Application space). The
> interrupt routine pops the bootloader address and then returns to the
> previous code - which is the routine that sets up the out, spm
> sequence. This should work, because when you apply spm instructions to
> the bootloader section the CPU is halted until it's complete.

So basically, you can do some fancy programming, and get the bootloader to hose itself, rendering the MCU useless without a dedicated programmer.

  [1]: http://oneweekwonder.blogspot.co.uk/2014/07/bootjacker-amazing-avr-bootloader-hack.html


body:
I've got an SD card and speaker hooked up to my nano and I can play mono audio files easily. My question is, is it possible to control the speed of a motor using the pwm output to the speaker? I tried just hooking the motor in where the speaker was, but that produced no noticeable variations in speed.

Alternatively, is it possible to analyse the wav file on the nano and control the motor that way? (i.e. motor speed is dependant on volume at a given time)

Thanks

title: Controlling a motor with a wav file

Answers: 1

body:
Regular sound files will have an even amount of time spend energizing the coil positive and negative, so the motor will not spin around in the normal sense. With a strong enough amplifier it will produce the sounds in the file like a speaker, but it will not noticeably turn.

Actual PWM varies the percentage of the time the signal is HIGH in a fixed frequency square wave, thus all the different values are the same "pitch". Audio varies amplitude and frequency, but the cumulative effect of audio waves is neutral, it spends half of the time below neutral and half above neutral voltage. The simplest analogy I can think of is audio being itself, even vibrations in air, and motor PWM being wind.

I am not sure if it possible to generate a sound file that would turn the motor, it probably depends on the file type. In any case, you would be better off with a far simpler amplifier like a transistor, MOSFET, or H-Bridge on one of your nano's actual PWM pins.

As to whether or not you could analyse the file on arduino, it also depends on file type. The code for the arduino WAV sheild I've seen does not have the arduino actually processing data, but It should be possible with a simple enough file type for arduino to decompress. WAV is not normally compressed, just raw data, so your limits are the RAM and if you can code something to glean volume from the raw data. I don't have much experience in that kind of file processing on AVR so I'm not going to call it either way.


body:
This is an extremely noobie question, but I have a 5V at 2A power source. This power source is going to be powering 6 Sharp IR distance sensors(20-150cm) and a few other low current consumption sensors(ie Xbee).

My question is if it is safe to simply use that power source without some sort of resistor between the power source and sensors?

also the IR sensors have a analog output. Is that same to plug into the arduino's analog pins?

title: Maximum Current?

Answers: 2

body:
> also the IR sensors have a analog output. Is that same to plug into the arduino's analog pins?

If the sensors won't generate more than 5V, it should be safe. (Generally, they're all less than 5V. However, verify this...)

> My question is if it is safe to simply use that power source without some sort of resistor between the power source and sensors?

You probably don't need a resistor*. Current is supplied on demand; if you need 1A but have a 2A supply, only 1A will flow. Voltage, however, is constant.

That being said, some parts will pull more current than they can safely use (like a LED, so *then* you would use a resistor.

This should all be found on the datasheet (especially with a more trusted brand like Sharp). Just look for example circuits and input voltage/forward voltage. A quick note, make sure to connect the grounds if you're not driving the Arduino directly from the power supply.

<sub>*There probably is an internal resistor for the LED. Again, **datasheets, datasheets, datasheets!**</sub>

body:
A few other points, in addition to Penguin's excellent answer:

Make sure your 5V supply is a REGULATED supply. Unregulated power supplies will exceed their target voltage when unloaded, and "droop" to lower than their target voltage when under heavy load.

Quite a few digital components can be destroyed if their input voltage varies too much from 5V, especially over-voltage. TTL is especially sensitive to over-voltage (which destroys the circuit) and to malfunctioning on under-voltage.

Even a regulated power supply will have some ripple if you switch heavy loads on it. You might want to use separate, isolated supplies for your high power and low power logic systems.

A higher current regulated supply will be "stiffer" and therefore more stable if run at lower loads.


body:
i would like to measure some signals from arduino and send it to a pc using USART and display the results in a c# winform application. Does anyone have such a project example ?
Besides, i want to send the data in live time mode, each values should be directly transmitted and then the second measurement ( sample rate 100 kHz )
Thanks a lot

title: Arduino Controlling through C#

Answers: 1

body:
Am I missing the point here or wouldn't the C# just have to open a Serial connection to the board and read and write to that to control the program running on the Arduino?
Yes the board is connected by USB, but that's only so it can open a serial connection.
To be honest I don't think you will be able to sample at that speed, you might be better looking at ICs that directly interface with GPIO and RS232/USB.


body:
**EDIT: after reading up on some stuff and with the help of the comments people left, I'm certain that it's an overflow issue, but I'm not sure how to solve that...**

So I just got an Arduino Yun today and have been figuring out how to use it.  I seem to have run into a problem though and haven't been able to solve it...

I stripped down the YunSerialTerminal sketch that allows accessing the yun linux terminal over a usb com port:

    void setup() {
      Serial.begin(9600);      // open serial connection via USB-Serial
      Serial1.begin(250000);   // open serial connection to Linux
    }

    void loop() {
      if (Serial.available()) {             // got anything from USB-Serial?
        int c = Serial.read();              // read from USB-serial
        Serial1.write(c);                   // write to Linux
      }
      if (Serial1.available()) {            // got anything from Linux?
        int c = Serial1.read();             // read from Linux
        Serial.write(c);                    // write to USB-serial
      }
    }

It works for the most part, but has some odd differences from connecting via ssh over wifi.

It seems to be dropping random characters from the screen (due to buffer overflow):

![enter image description here][1]

As you can see, it's messed up some of the text such as md5um which should be md5sum and the formatting is all off.

It gets even worse when launching elinks terminal web browser (which works beautifully when connecting via ssh over wifi):

![enter image description here][2]

I've also tried different programs (other than putty), including the arduino ide serial monitor, and they all produce the exact same result (and yes I'm setting them to the correct port speed as well).

Does anyone have any idea what I'm doing wrong?  I've tried many different port speed combinations and they all produce the same result.  It seems that the atheros-atmel link is set to 250000 baud (Which is why I have to use that speed on Serial1 in my sketch), but can that be changed?  I've read some things about how 250000 is way too fast when the atmel is involved, but is there a way to change that speed without losing the Bridge library functionality?

Also, could someone else with a yun try this sketch and verify that it works? Load it, and connect with putty via serial (using whatever com port arduino bound to) and double tap tab key to see if the command listing is missing letters.

  [1]: https://i.stack.imgur.com/vQ5XT.png
  [2]: https://i.stack.imgur.com/Nf3vQ.png

title: Arduino Yun Serial Terminal Overflow Issues?

Answers: 0


body:
I am using Python **smbus** `write_word_data` method to send int values from a Raspberry Pi to an Arduino using I²C.

This seems to be the correct method.

When I send values from 0-255, I see the following in my Arduino serial monitor

>0,0,0

0,1,0

0,2,0

…

0,255,0

Sending 256 I see:

>0,0,1

For 257 I see:

>0,1,1

Etc, etc...

My question is, how would I modify the following Arduino code to properly 'reconstitute' the int values, and then send them back to the RPi?

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x04
    int number = 0;
    int state = 0;
    bool newData = false;

    void setup() {
      pinMode(13, OUTPUT);
      Serial.begin(9600);
      // initialize i2c as slave
      Wire.begin(SLAVE_ADDRESS);
      // define callbacks for i2c communication
      Wire.onReceive(receiveData);
      Wire.onRequest(sendData);
      Serial.println("Ready!");
    }

    void loop() {
      Serial.println(receivedValue);
      newData=false;
    }

    // callback for received data
    void receiveData(int byteCount) {
      while(Wire.available()) {
        newData = true;
        Wire.read();
        if(Wire.available() == 2) {
          receivedValue = Wire.read() | Wire.read() << 8;
        }
      }
    }

    // callback for sending data
    void sendData() {
      Wire.write(number);
    }

title: Receiving two-byte int values over serial

Answers: 3

body:
    void receiveData(int byteCount){

      // Looks like your number is sent in a 3 byte packet
      if (bytecount == 3)
      {

        // Discard first number as it is seemingly alway zero
        Wire.read();

        // Read low byte into rxnum
        int rxnum = Wire.read();

        // Read high byte into rxnum
        rxnum += Wire.read() << 8;

        // Send back
        sendInt(rxnum);

      }

    }

    void sendInt(int num){

      // Uncomment below if you want so send back in same format
      // Wire.write(0);

      // Send low byte
      Wire.write((uint8_t)num);

      // Send high byte
      num >>= 8;
      Wire.write((uint8_t)num);
    }

body:
Ir seems to me that there is something wrong with the Python Raspberry Pi code. What you show is 3 bytes of data, not 2. That's wrong.

If you're writing a 2 byte word, I would expect to see 2 bytes, not 3. You might want to post a question on the Raspberry Pi forum to get help resolving **THAT** problem first.

If you're stuck with the sending code you have, then here's what you would do.

Looking at your data, the first byte is always zero. You want to discard it.

The second byte is your low order byte, and your third byte of data is the high order byte. You need to do some juggling to get the data into the correct byte order, like this:

    void readWordWithPadding()
    {
      if (Wire.available()<3)
      {
        newData = false;
        return;
      }
        newData = true;

      Wire.read(); //Throw away the filler byte
      int lowByte = Wire.read();
      int hiByte = Wire.read();

      //Shift the high byte by 8 bits and add in the low byte
      receivedValue = (hiByte << 8) + lowByte ;
      return;
    }

body:
Unless (and until) your application needs high enough data rates that you need to make the most efficient use possible of your data channel (or you're talking to an inflexible hardware device that dictates the data protocol), you'll save yourself a lot of headaches by sending human-readable strings, something like:

    x= 12345, y=   -32
    x=   432, y=-33221

You can reconstitute them at the other end with with `atol()`, log them  to a file, be able to understand them later, and see instantly whether the sender sent what you expected it to. Don't optimize until you have to; you may not have to.


body:
Is it possible to connect the Yun to wifi using 802.1X authentication?  802.1X is WPA2-Enterprise that uses a username and password (per user) instead of one password (for every user).  I don't see a way to do it from the Yun web interface, but is there a way to do it from the linino terminal?

As far as I know, the Atheros AR9331 chip should be capable of this, but I don't see a way to do it with the software included on linino, there must be a way to install something for this?

title: Connecting Arduino Yun to wifi with 802.1X authentication

Answers: 0


body:
i am working on a project which requires changing the direction of the DC motor using arduino. that is I want the DC motor to rotate clockwise when i press key 'A' and anti clockwise when i press key 'D' on my computer.

i have v+ and v- input wires from battery. i have connected one end of the DC motor to gnd of the battery. On the other end of DC motor i want to connect V+ and V- input from the battery to spin the DC motor in clockwise and anticlockwise respectively. I have used BC547 npn transistor.
i do not know how to change inputs (v+ to v- and vice-versa) using arduino when key is pressed.

is there any method other than H-bridge method to do so?

i use arduino uno.

title: Changing direction of DC motor

Answers: 2

body:
L298 IC is very popular way of doing it. IN1 IN2 to control direction, open circuit and breaking (short circuit of motor terminals). EN1 for PWM speed control.

Ready made module PCB widely available.

useful info
https://www.sparkfun.com/products/9670

http://forum.arduino.cc/index.php/topic,84439.0.html

Hope it helps.

body:
Since you have both a V+ and V- you could just use 2 transitors. If you look at an H-bridge, you only need half the circuit.

The only problem is that you need V- to disconnect the NPN transistor, and the arduino can only go as low as GND. So you'd need a second transistor to drive it.

The same might also be needed for the PNP side, if the arduino voltage is regulated to a lower value than V+.

I found this schematic applicable, but only use the left side. The right side of the motor should be connected to ground (or the middle voltage of your battery). , and replace the opto's with normal transistors.
![enter image description here][1]

Come to think of it, I'm not entirely confident about replacing the bottom opto, since battery-negative is below GND in your case. I think it should work, but I'm still quite new to this stuff.

Also make sure you add something like 1k resistors to the base of the transistors (that replace the opto's)

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


body:
The following code works correctly in reading single int values. It also works correctly for 3-4 seconds if I 'stream' the values in constantly (Mouse move coordinates) before I get an IO error and the i2C bus connection is dropped. I assume this is some sort of buffer overrun...or? Can anyone get me on the right track here? What changes do I need to make so that I can constantly stream in serial data?

        #include <Wire.h>

    #define SLAVE_ADDRESS 0x04
    int zeroByte;
    int state = 0;
    int receivedValue = 0;

    int numBytes = 0;

    bool newData = false;

    void setup() {
        pinMode(13, OUTPUT);
        Serial.begin(9600);         // start serial for output
        // initialize i2c as slave
        Wire.begin(SLAVE_ADDRESS);

        // define callbacks for i2c communication
        Wire.onReceive(receiveData);
        Wire.onRequest(sendData);

        Serial.println("Ready!");
    }

    void loop() {
        delay(100);
        if(newData){

          Serial.println(receivedValue);
          newData=false;
        }
    }

    // callback for received data
    void receiveData(int byteCount){

        while(Wire.available()) {
            newData = true;
            zeroByte = Wire.read();

             if(Wire.available() == 2)
      {
        receivedValue = Wire.read() | Wire.read() << 8;

      }

         }
    }

    // callback for sending data
    void sendData(){

        Wire.write(receivedValue);
    }

title: Proxying streaming i2c data(int values) to serial

Answers: 1

body:
Your I2C bus is operating at 100 kHz. Your serial connection is set to 9600 baud. In case you are sending coordinates at a pace faster than the serial interface can keep up, the buffer will fill up. I assume you are using hardware serial (uno, mega, etc). Once the buffer is filled up Serial.write (which is called by Serial.println) will block until the buffer has free space. But the serial transmission depends on interrupts, and you are calling Serial.write inside an interrupt routine. By defult interrupt routines block other interrupts from happening. So your program gets stuck there and locks up both the serial transmission and the I2C interface.

It would be a good idea to put the serial write outside the interrupt routine, in the loop. Make a global variable `bool newData = false;` and set it true in the receiveData function. In your loop check the flag and transmit the data. Then set the flag to false.

You will still experience data loss if the serial interface can't keep up, but your application wont lock up. To solve the data loss simply use a higher baud rate, eg. 115200.


body:
Currently using i2C to connect a RPi with an arduino. It seems i2C is quite finicky and, drops the bus immediately if there are any IO errors. Since what i am building is meant to be semi permanent, I am worried that i2C may not be the best choice.

Has anyone done any real world testing of i2C vs GPIO for RPi to arduino communication?

title: Is i2C more or less robust than GPIO?

Answers: 1

body:
Here are a few things to remember:

 - You should have a ground connection between the RPi and Arduino
 - I2C was meant for really short distances on a printed circuit board
 - Arduino runs at 5 Volt logic levels and RPi at 3.3 Volt logic levels - you need a level translator between them to make that work.

If the RPi and the Arduino are not far apart, I would say less than 1 foot (30 cm) and you have the grounds connected between the boards, then it is a software issue. I2C is meant for short distances any anything longer than a foot puts too much capaitance on the wires and starts causing unreliable communication. I would not even use it for more than a few inches unless it was on a circuit board where you control the capacitance.

I am assuming your using the Wire library on the Arduino side. On the RPi side I would use the the Adafruit I2C library for the RPi as I have had success using the library to communicate with I2C sensors listed on their site. Here is the link:

[Adafruit RPi I2C Tutorial][1]

  [1]: https://learn.adafruit.com/using-the-bmp085-with-raspberry-pi/configuring-the-pi-for-i2c


body:
I'm just beginning to use Processing along side with Arduino and need help linking the two. Just to get started, I just wanted to send a single character (eventually strings) to the Arduino and have the Arduino light up a matrix if the Arduino receives the data.

Here's my code for the Arduino (I'm using an Arduino Uno):

    #include <Adafruit_GFX.h>   // Core graphics library
 #include <RGBmatrixPanel.h> // Hardware-specific library

    // Set up the matrix
 #define CLK 8
 #define LAT A3
 #define OE  9
 #define A   A0
 #define B   A1
 #define C   A2
 RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);

 int incomingByte = 0;   // for incoming serial data

 void setup() {

   Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
   matrix.begin();
 }

 void loop() {
     if(Serial.available() > 0) {
     incomingByte = Serial.read();

        // Print a white "Done!" to the matrix
     matrix.setCursor(1, 0);
     matrix.setTextSize(0);
     matrix.setTextColor(matrix.Color333(7, 7, 7));
     matrix.print("Done!");

   }
 }

And here's the code for Processing:

    // Example by Tom Igoe

 import processing.serial.*;

 // The serial port:
 Serial myPort;

 // List all the available serial ports:
 println(Serial.list());

 // Open the port you are using at the rate you want:
 myPort = new Serial(this, Serial.list()[1], 9600);

 // Send a capital "A" out the serial port
 myPort.write(65);

I run the processing sketch and then upload the code to the Arduino, but get nothing. The Arduino is using COM3 and I believe the Processing sketch is too, but that may be where I'm messing up.

If I open up the serial monitor and send some data to the Arduino that way, then the LED lights up fine, but only when I do it through that.

Any help would be appreciated. Thanks!

title: Unable to send data from Processing to Arduino through ports

Answers: 1

body:
When you open a serial connection to Arduino Uno the atmega328 microcontroller is usually reset(this depends if the OS is configured to toggle the DTR serial control signal on/off when a port is opened). Just after a reset the bootloader (optiboot) runs to see if you are trying to upload a new sketch. If the bootloader doesn't receive any meaningful communication it will start your sketch after ~1 sec. All communication sent to the serial port while the bootloader is running is lost.

When you use the serial monitor you are too slow to notice the 1 second where the board won't respond to your commands. But the processing sketch is another story.

The easiest fix will be to insert a delay after you open the serial port and before you send any data.

    // Wait 1.2 sec
    int start = millis();
    while (millis() - start < 1200);

---
If you would rather use a hardware fix you can connect a 10uF capacitor between RESET and GND pins that will prevent the board from being reset by the usb to serial converter.


body:
I'm attempting to create something similar in nature to the [Ubertooth one][1]. I'd like to sniff Bluetooth packets using the Arduino.

I've found a few nRF24L01+ wireless modules, which appear to operate on a frequency similar to Bluetooth LE. Unfortunately, I don't believe this will work for Bluetooth or BLE.

What would be the best way to sniff radio frequencies in the Bluetooth range from Arduino, am I on the right track?

  [1]: http://ubertooth.sourceforge.net

title: Sniffing Bluetooth Packets

Answers: 0


body:
I am using a grove GPS [http://www.seeedstudio.com/wiki/Grove_-_GPS][1]

  [1]: http://www.seeedstudio.com/wiki/Grove_-_GPS

I attached the GPS to Serial1 of Arduino Mega 2560.

The baudrate of the GPS is set to 9600.

Library wise, I am using TinyGps to parse the GPS data.

The GPS receiver can only get a valid data if it can see a clear sky.

I read uBlox documentation and it states that I can use A-GPS.

So, my question is, how do I actually set the Grove GPS that is attached to my Mega, to use A-GPS?

title: How do I set Grove GPS to use A-GPS?

Answers: 1

body:
A-GPS uses a network connection to download GPS almanac and ephemeris data to enable satellites to be located faster. Otherwise the GPS device has to wait for the data to be sent by a satellite, which may take up to 12.5 minutes. Alternatively, the GPS device can send noise GPS data to an assistance server which will process it and send back a fix.

A-GPS requires a network connection to an A-GPS server. You can't just 'turn it on'. There are some modules out there that combine GPS with a 3G modem which do A-GPS automatically.


body:
The datasheet for the accelerometer states that:

![enter image description here][1]

Here is the data output from the accelerometer:

![enter image description here][2]

I have tried to mask the first two bits using a bitwise AND command with B0011111111111111.

I tried to use this code, but unfortunately the first 2 bits are still "11" so the value has not changed:

    int bresult=0b0011111111111111&result;
    Serial.print(bresult,BIN);

How would I bits mask the first two bits and will arduino automatically know how to convert to twos compliment?

The variable result is of data type "long"

According to an answer, I tried:

    int bresult= result<<2;
    Serial.print(bresult,BIN);

I got this result which is great but is it possible to remove the last two zeros because this is making my value larger?
The image below shows result then bresult.

![enter image description here][3]

  [1]: https://i.stack.imgur.com/ogmVl.png
  [2]: https://i.stack.imgur.com/tvidg.png
  [3]: https://i.stack.imgur.com/V32NY.png

title: Bit mask first 2 bits of 16 bits for accelerometer

Answers: 2

body:
Since it won't convert to two's complement if the sign bit is the 14 bit instead of the 16th, it would be easier to just shift the value left by 2. So

    int bresult= result<<2;

Since `<<2` is the same as `*4` the result will be 4 times as high. So you need to divide the result by 4. Since you already have to multiply by `0.025` (or divide by 40), you end up having to multiply by `0.00625` (or divide by 160).

body:
For the arduino, `long` is 32 bits, `int` is 16 and `char` is 8.

Save the result in an `int` not a `long`. Then Gerben's method `int bresult = (result << 2)/4` should work. This is because `<< 2` moves everything left two bits, but `/ 4` move every thing right two bits *with new bytes the same as the sign bit.* So you get a **16 bit** signed variable with the correct number. If you have it as a long you would have to do
`int bresult = (result << 18)/(2^18)`.

BTW Serial.print(bresult,BIN); is always going to give you up to 16 bits. There is no 14 bit type.


body:
I'm trying to bypass Bridge library and read serial directly from nodejs. I'm on the last sys upgrade (1.3) I have correctly installed nodes and serial module via opkg install. I have also commented out the line in the `/etc/inittab`:

    #ttyATH0::askfirst:/bin/ash --login

This is my arduino code:

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

    void loop() {
      Serial.println("dudee");
      delay(100);
    }

This is my node.js code:

    var SerialPort = require("serialport").SerialPort
    var serialPort = new SerialPort("/dev/ttyATH0", {
        baudrate: 9600,
        dataBits: 8,
        parity: 'none',
        stopBits: 1,
        flowControl: false
    }, false);

    console.log("hello");

    serialPort.on("open", function () {
        console.log('open');
        serialPort.on('data', function(data) {
            console.log('data received: ' + data);
        });
    });

    serialPort.on('error', function(err) {
        console.log('error: '+err);
    });

    serialPort.open();

If I ssh to yun and run the script I don't see any "dudee":

    ~/test# node serial.js
    hello
    open

While if I open the serial monitor I see it.

If I run the node script on my computer (changing the right serial port name) everything works nice and I see the dude..

What can it be?

title: Arduino Yun, node.js and serial

Answers: 1

body:
Autosolved thanks to [this old forum post][1].

It is `Serial1` not `Serial`.
In the Arduino code in the Yun `Serial` is a different object from `Serial1`. Even if it is not super well document (or at least not in the first dumb google search) here are some links that talks about `Serial1`:

[https://www.arduino.cc/en/Tutorial/YunSerialTerminal][2]
[http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/][3]
[http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/][4]

  [1]: http://forum.arduino.cc/index.php?topic=194934.15
  [2]: https://www.arduino.cc/en/Tutorial/YunSerialTerminal
  [3]: http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/
  [4]: http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/


body:
I'm completely new to Arduino, I bought a Rampos 1.4 and an Arduino Mega 2560 to build a Prusa Mendel 3D printer.

But when I connect the Arduino via USB to my computer, open the software and click to upload the blink example, it does anything and says Uploading to i/o board.

This happens when I use Arduino 0022 and then when I use Arduino 1.0.5 r2 that is the problem:

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer

I don't know what is happening, and I don't know what to do.

title: Error uploading on Arduino Mega 2560

Answers: 1

body: Sorry I do not have the reputation to comment. I think your problem can be because you selected the wrong settings for your board. Check in Tools option, and make sure Board, Processor and Port is correct.


body:
I'm pretty new to this whole thing so please excuse my lack of familiarity with terminology.

I'm looking to build two "buzzers" of sorts. One will live on the ground floor and the other will live on the fourth floor. There is wireless internet as well as wired internet available to connect the two.

This is the basic idea. I might put more frills in later. Both buzzers have one button and one LED. I want it so that once a buzzer's button is pressed, the LED lights on both buzzers will light up. Then, only when buzzer two's button is pressed, will the LED lights on both buzzers turn off.

I'm pretty tied up on the two Arduinos communicating with each other. Is it possible to do something like that?

title: How can I get two Arduinos to "talk" to each other?

Answers: 2

body:
Benefits of a networked device:

 - Fairly fast because it has to be able to transfer large amounts of data
 - Can be compatible and used with computers, servers, and mobile devices. You might also only have to have one Arduino (if the second one would only be acting as a bridge between the protocol and the computer)
 - Why *wouldn't* you want to have a networked Arduino :)

So that rules out the protocols I2C, UART, and SPI. I find Bluetooth too hard to work with (it seems to have only a short range) using an Arduino. That leaves us with Wifi, wired network connection, and USB. USB would be best if you could run a short wire, but most USB peripherals aren't really designed to be used 100 feet away from the computer.

With ethernet and Wifi left, I'm going to advise you to go with a wired connection if possible. Benefits of keeping it wired:

 - Even *faster* (with lower latiencies)
 - Lower cost to interface with
 - More reliable than Wifi
 - No pesky Wifi passwords

**tl;dr:** Without a ton of info, **wired internet** (a.k.a. ethernet) seems to be the best choice.  Other wireless options don't provide the distance you need and you (probably) can't run a wire with another protocol.

body:
**Wired**

Communication speed is not a factor - you only have to transmit an on/off signal. The simplest method would be to run a 4-wire cable, like a telephone cable, between the two.

The wires would be

 1. GND
 2. 5V (maybe)
 3. Ground floor output -> fourth floor input
 4. Fourth floor output -> ground floor input

The steps are

- Both wire 3 and 4 start LOW When ground floor button is pressed, ground floor led goes on, wire 3 is set HIGH.

- Fourth floor is monitoring wire 3, when it goes HIGH, fourth floor led goes on, and    wire 4 is set HIGH

- Ground floor is monitoring wire 4, when it goes HIGH, ground floor led goes off, and wire 3 is set LOW

- Fourth floor is monitoring wire 3, when it goes LOW, fourth floor led goes off,    and wire 4 is set LOW

- Ground floor is monitoring wire 4, when it    goes LOW, it begins waiting for a button press again.

Wire 2 can be used for 5V (or 3.3V depending on the Arduino) so that one of the devices can be powered off the other.

**Wireless**

The other option is to attach an RF transceiver to each Arduino, something like [this][1] would be good as it has 100m line-of-site range which you might need to get through 4 floors of concrete.

**Learning**

Start off with the simple wired method shown above. When it is working, connect wire 3 and 4 into the RX and TX pins and try to communicate using the serial port. Finally, move on to the wireless transceivers.

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


body:
I coded a ring buffer for my Arduino to buffer data from either the SPI or TWI ports. In the .h file I used a pointer for the buffer:

    typedef uint8_t *ring_buffer_t;
    typedef uint8_t ring_count_t;
    typedef uint8_t ring_index_t;
    typedef uint8_t ring_size_t;

    typedef struct ring_t
    {
        ring_buffer_t buffer;
        ring_count_t  count;
        ring_index_t  head;
        ring_index_t  tail;
        ring_size_t   size;
    }rint_t;

    int ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size);

    // other function prototypes to add and remove from the ring buffer

There is more code to handle adding and removing from the buffer, but I am simplifying here. Then in my .c file I have:

    #include<string.h>

    void ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size)
    {
  r->buffer = buffer;
        r->size   = size;
        r->head   = 0;
        r->tail   = 0;
  r->count  = 0;

  // clear out the buffer memset cheaper by 12 bytes rather than for loop
  memset((void *)r->buffer, 0, r->size);
 }

Then somewhere in code where the ring buffer is going to be used:

    In SPI.h ...
    #define MAX_BUFFER_SIZE 32
    ring_t  rx_ring;
    uint8_t spi_rx_buffer[MAX_BUFFER_SIZE];

    #define MAX_BUFFER_SIZE 32
    ring_t  tx_ring;
    uint8_t spi_tx_buffer[MAX_BUFFER_SIZE];

    In SPI.c ...
    void spi_init( ... )
    {
        ring_init(&rx_ring, spi_rx_buffer, MAX_BUFFER_SIZE);
        ring_init(&tx_ring, spi_tx_buffer, MAX_BUFFER_SIZE);

        // initialize other spi parameters
    }

Are there any issues with my code that are obvious that I am not seeing? I ask because I ran the code and it works, but I feel I am doing something wrong. I can code in C and remember something about malloc() for dynamic memory allocation, just not sure if what I am doing qualifies. Or should this work creating a buffer of some defined size?

Thanks for any help or ideas.

EDIT: 07/27/2014 Added code to try and make what I am trying to do clear. Let me know, thanks.

title: Is it bad coding practice to design a buffer using pointers?

Answers: 3

body:
Not enough info. You have a struct ring_t that has a pointer to an array of uint8_t's. In your ring_init method, your code assumes that the pointer points to valid memory. If you have not explicitly pointed the pointer to a block of memory, either stack memory or heap memory, then yes, there is a problem.

You COULD malloc the ring buffer, or you could create it as a global variable. If you've only got one ring buffer it's probably just as well to make the buffer a global and set the pointer in your setup method.

body:
Don't bother with `malloc` unless you need to. If you explicitly define your buffer before hand then you can use `avr-size` to [check your SRAM usage][1].

Also the C compiler automatically adds code to initialise global variables to 0, so you don't need ring_init if your define the array explicitly. See https://stackoverflow.com/questions/2218254/variable-initialization-in-c for initialisation comments. Even if buffer was filled with non-zeros it wouldn't matter because it should be written to before being read from.

If you change the ring buffer from chars to ints, etc. you will have to change `memset`, as it assumes chars.

Will MAX_BUFFER_SIZE change? If not, you could put the buffer in `ring_t`.

  [1]: https://stackoverflow.com/questions/960389/how-can-i-visualise-the-memory-sram-usage-of-an-avr-program

body:
Simple answer: No, it isn't bad practice at all. I write with pointers all the time. Pointer referencing usually compiles to more efficient code than does array referencing.

But:
It looks like you've confused a pointer with the thing it is supposed to point to. The member you call 'buffer' is declared as pointer to unsigned byte. It doesn't appear to get initialized anywhere; it should be initialized with the address of an array of unsigned bytes (at least) as large as your ring buffer needs to be. I don't see this in anywhere in your code.

As others have described, the buffer could be allocated at run time with malloc() (but it's best not to save malloc() & free() for things you _have to_ create and destroy on the fly; or direct the compiler to allocate it before your program gets control, with something like:

    #define RINGBUFSIZE 32

    uint8_t ring_buffer_memory[RINGBUFSIZE];

and initialize your pointer to it with:

    r->buffer = ring_buffer_memory;

This will initialize your pointer to the first of (in this case) 32 bytes of zeroed memory reserved for the ring buffer. In your code, it's quite likely the pointer contains `0`, thus pointing to memory location zero and is definitely not what you mean to do.

A word on variable names - adopt a convention for naming your variables that help a future reader (probably you!) understand/remember what that variable is for. In this case I'd probably use `ringBuf` for the array, and `pRingBuf` for its pointer. As a new reader of this code, I'd find it pretty inconvenient to have to have to remember that `buffer` is really a pointer (and what the heck was the buffer called!?).


body:
I have a few Arduino's along with XBee Shields communicating with one another.

The problem I'm having is that, when all the Arduinos+XBee Shields are powered via USB(PC) they seem to work fine and all transmissions get through to one another. But, when I use them with 9Volt batteries(fairly new batteries) the whole thing crashes and I never receive responses back from the battery powered ones.

I'm wondering if this is really a power issue? wouldn't a 9volt be enough to power a single arduino(uno)+xbee shield?

title: Arduino uno + XBee Shield Not transmitting when under battery power?

Answers: 3

body:
Using a multimeter you can confirm your theory by looking for a voltage drop on the power connections to the XBee and into the UNO.

9V batteries don't store much charge, nominally 563mAh according to wikipedia. It is possible that the fairly new batteries are not that new after all.

Depending on the XBee, power consumption varies. 40mA for a normal XBee (ZigBee), 200mA for pro, and 309mA when transmitting for the new XBee WiFi. If the battery is low, the high current draw plus internal battery resistance may drop the 9V output to below the 7V needed for the UNO's voltage regulator to function correctly.

body:
The usb port on your computer can supply about 500mA of current. If geometrikal is correct about the 563mAh and you are using an XBee pro or a higher current draw radio, you could easily be hitting the current limit of the battery. Another aspect of this is the [internal resistance][1] of the battery. I'll let you read about it, but it is another current limiting factor. All of this boils down to once you are drawing more current than the battery can provide the voltage drops. Once it gets down to below what the Arduino board can regulate the microcontroller will reset.

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

body:
Is space an issue? Have you considered using 6 AA batteries? From what I've read basically the current provided by a battery is determined by it's size so C is bigger than AA which is bigger than AAA.

The 9volt battery is from what I understand made up of 6 AAAA cells and therefore has a much lower maximum current. about 563mAh rather than about 1500mAh depending upon the type you choose.


body:
2 days back I bought Arduino Yun. I'm able to flash Led on 13 pin. And I'm able to flash Led on Bread board connected to A0. I'm able to run linux commands.

Now I want control A0 pin using Linux/Python program. Is this possible? I read many documents. But I didn't find thing related to this.

**How I  can flash the LED using Linux programs?**

title: Can I control analog IO pins using Yun Linux

Answers: 5

body:
I haven't used a Yun before, but here is my understanding.

The Yun is really 2 separate computers with a bidirectional serial port between them.

The output pins are on the Arduino side. If you want to control Arduino pins from the LINUX side, you need to come up with a simple command syntax for communicating between the 2 computers and write code on both sides that supports that command syntax.

Say the command is:

    digitalPinx=n;

Where x is the pin number, and n is a value, 0 or 1. (for digital pins). For a PWM output pin you could use a command analogPin and values of n from 0 to 255:

    analogPinx=n;

On the LINUX side you'd just send that command through the serial port to the Arduino.

On the Arduino side, you'd write a loop that would wait for data to come into the serial port from the LINUX chip. If it gets data, it would read it into a buffer until it saw a semicolon.

Then it would break the data into separate lines using the semicolon as a delimiter, search for "digitalPin" or "analogPin", parse the data between the command and the semicolon for the values, and issue the digitalWrite or analogWrite command using those values.

body: I am looking for the same thing. The only thing I have come up with is that you can use the Bridge Library and use curl on the Linux side to read or write the pins

body:
There are several libraries which will do this for you. Basically, you should upload a special sketch onto the Arduino, which listens to the serial port, and performs the I/O that the Linux chip requests. Libraries which can do this are

* [Firmata](http://arduino.cc/en/Reference/Firmata)
* [Autobahn](http://tavendo.com/blog/post/arduino-yun-with-autobahn/)
* [LininoIO](http://www.linino.org/)

body:
Suggest starting with the  the `Mailbox` examples in the Bridge library. Specifically the example
<http://www.arduino.cc/en/Tutorial/MailboxReadMessage>
Which shows how to transfer messages to the Arduino processor. It does discuss how to fire the curl process from the command line.

body:
The simpliest thing I've found, is using the command "lininoio start"

then you can use nodejs with https://github.com/ideino/ideino-linino-lib and you no need to worry with the sketch part anymore, just javascript :-)

 http://smag0.blogspot.fr/2017/07/smagyun.html


body:
I'm currently trying to write to and read from an 25LC256-E EEPROM with my Arduino Uno via SPI. I've made a program which is supposed to do this, but I only get weird answers.

I'm sending in a Serial-string.
This string should start with 'w', 'r' or 'e', depending on what action I want to perform. The second character should be an int between 0 and 3 to determine witch PIN I should use as slave (currently I'm using only 1 slave, so the int should always be 0).
The rest of the string gets written to the EEPROM, one byte/character at the time.

What am I missing?

CODE:

        #include <SPI.h>

        #define WREN  6
        #define WRDI  4
        #define RDSR  5
        #define WRSR  1
        #define READ  3
        #define WRITE 2

        // Multiple slaves for future project
        const int CHANNELS[4] = {10, 8, 7, 4};
        String readResult;

        void setup() {

          Serial.begin(9600);
          channelSetup(); // Set all slave pins in CHANNELS to OUTPUT and HIGH

          SPI.begin();
          SPI.setDataMode(SPI_MODE3);
          SPI.setClockDivider(SPI_CLOCK_DIV2);
          SPI.setBitOrder(MSBFIRST);

        }

        void loop() {

          Serial.println("START");

          while(!Serial.available());
          delay(20);

          // Get all available bytes/characters
          String serialInput = getSerialStream(Serial.available());

          // Second character in serialInput is an int between 0 and 3
          int channel = makeValidChannel(serialInput[1]);

          // "channel" must be between 0 and 3
          // to be able to point to CHANNELS
          if (channel >= 0 && channel <= 3) {

            // First character decides what to do
            switch (serialInput[0]) {

              case 'w':
                writeToChannel(channel, serialInput.substring(2));
                break;

              case 'r':
                readResult = "EMPTY";
                readResult = readFromChannel(channel);
                Serial.print("Result: ");
                Serial.println(readResult);
                break;

              case 'e':
                overWriteEEPROM(channel);
                break;

              default:
                Serial.println("INVALID FIRST OPERATION");

         }

          }

          else
            Serial.print("INVALID CHANNEL: ");
            Serial.println(channel);

        }

        void channelSetup() {

          for (int i = 0; i < sizeof(CHANNELS); i++) {

            pinMode(CHANNELS[i], OUTPUT);
            digitalWrite(CHANNELS[i], HIGH);

          }

        }

        String getSerialStream(int numOfChars) {

          char serialStream[numOfChars + 1];
          int i;

          for (i = 0; i < numOfChars; i++) {

            serialStream[i] = char(Serial.read());
         delay(5);

          }

          serialStream[i] = '\0';
          return String(serialStream);

        }

        int makeValidChannel(char chIn) {

          int channel = chIn - '0';
          //channel -= 48;

          if (channel >= 0 && channel <= 3)
            return channel;
          else
            return -1;

        }

        void writeToChannel(int channel, String message) {

          int slaveselect = CHANNELS[channel];
          int i;

          // Write enabled
          digitalWrite(slaveselect, LOW);
          SPI.transfer(WREN);
          digitalWrite(slaveselect, HIGH);
          delay(5);

          // Disable Write Protection
          digitalWrite(slaveselect, LOW);
          SPI.transfer(WRSR);
          SPI.transfer(0);
          digitalWrite(slaveselect, HIGH);
          delay(5);

          for (i = 0; i < message.length(); i++) {

            digitalWrite(slaveselect, LOW);
            SPI.transfer(WRITE);
            SPI.transfer(0);
            SPI.transfer(i);
            SPI.transfer(message[i]);
            digitalWrite(slaveselect, HIGH);
            delay(5);

          }

          // When writing of "message" is done,
          // add a 0-byte as terminating character
          digitalWrite(slaveselect, LOW);
          SPI.transfer(WRITE);
          SPI.transfer(0);
          SPI.transfer(i);
          SPI.transfer(0x00);
          digitalWrite(slaveselect, HIGH);
          delay(5);

          // Enable Write Protection
          digitalWrite(slaveselect, LOW);
          SPI.transfer(WRSR);
          SPI.transfer(3);
          digitalWrite(slaveselect, HIGH);
          delay(5);

          // Write Disabled
          digitalWrite(slaveselect, LOW);
          SPI.transfer(WRDI);
          digitalWrite(slaveselect, HIGH);
          delay(5);

        }

        String readFromChannel(int channel) {

          Serial.println("Reading started");

          int slaveselect = CHANNELS[channel];
          char outputArr[64];
          int i = 0;

          while (true) {

            digitalWrite(slaveselect, LOW);
            SPI.transfer(READ);
            SPI.transfer(0);
            SPI.transfer(i);
            outputArr[i] = SPI.transfer(0x00);
            digitalWrite(slaveselect, HIGH);
            delay(5);

            if (outputArr[i] == 0x00 || i >= 64) {

              outputArr[i] = '\0';
              return String(outputArr);

                    }

            else
              i++;

          }

        }

        void overWriteEEPROM(int channel) {

          char zeroArr[64];
          for (int i = 0; i < 256; i++) {

            zeroArr[i] = 0;

          }

          writeToChannel(channel, String(zeroArr))

        }

title: Can't read from / write to SPI EEPROM

Answers: 0


body:
I'm using a single sonar, but I want to use two sonar to know another distance.

Here is how I use my single sonar:

        #include <NewPing.h>

        #define TRIGGER_PIN  9
        #define ECHO_PIN  10
        #define MAX_DISTANCE  100 // in CM
        ...
        NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
        ...
        delay(100);
        unsigned int uS = sonar.ping();
        int cm = uS / US_ROUNDTRIP_CM;

But I Want to use a second one to calculate another distance, how to?

    #define TRIGGER_PIN_2  11
    #define ECHO_PIN_2  12
    ...
    new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE);
    ...
    ???

Thanks in advance

**EDIT:**

Maybe this one, I'll try this when I will get my second sonar

    #define SONAR_NUM     2
    #define MAX_DISTANCE 200
    ...
    NewPing sonar[SONAR_NUM] = {
      NewPing(9, 10, MAX_DISTANCE),
      NewPing(11, 12, MAX_DISTANCE)
    };
    ...
    delay(100);
    unsigned int uS1 = sonar[0].ping();
    int cm1 = uS1 / US_ROUNDTRIP_CM;

    unsigned int uS2 = sonar[1].ping();
    int cm2 = uS2 / US_ROUNDTRIP_CM;

title: How to use two Sonar's

Answers: 1

body:
> Maybe this one, I'll try this when I will get my second sonar

*Ding ding ding!* Yeah, this would be one way to do that. That creates an *array* so you can reference the sonar with `sonar[i]`, where `i` is either 0 or 1 for the first or second number.

For only two sensors, it might be easier just to do something like this:

    NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
    NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Then you can run the other code like this:

    delay(100);
    unsigned int uS1 = sonar1.ping();
    int cm1 = uS1 / US_ROUNDTRIP_CM;

    unsigned int uS2 = sonar2.ping();
    int cm2 = uS2 / US_ROUNDTRIP_CM;

A little less code to read, whichever one you want.

The reason you can do this is you can replace the `sonar` with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it `Arduino_Sonar` if you wanted to.

The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do `int numbers[500];` to declare them. An array might be more useful if you're expanding your circuit, but either is correct.


body:
I use the Pin 7 to get the status of a push button. I put 10Kohm R on the - .

The status is unstable because arduino says thet I push it but it is not true...

    int button = 7;
    ...
    // var for reading pushbutton value
    int buttonState = 0;
    ...
    buttonState = digitalRead(button);
      if(buttonState == HIGH)
      {
        myFunction();
      }

**EDIT :**

ARDUINO PIN 7 <---> R 10Kohm <--> [switch] <---> VCC

title: Unstable reading from pushbutton on digital pin

Answers: 2

body:
At the moment, your resistor isn't doing anything useful. When your switch is open, the pin is still 'floating', which means it's ending up with random stray readings from nearby electromagnetic fields.

You basically need two connections coming from your Arduino pin. One goes through a resistor straight to ground. The other goes through your switch straight to +5V.

In that case, the resistor is acting as a pull-down, because it holds your pin at Ground whenever the switch is open. You could swap over the ground and +5V, and it the resistor would function as a pull-up instead.

This question deals with the same kind of issue:

 * https://arduino.stackexchange.com/questions/186/button-state-changing-randomly/187

body:
Note that you can also activate the internal pull-up resistor on the pin by first making it an input, then setting it to HIGH.

    pinMode(pin, INPUT);
    digitalWrite(pin, HIGH);

###EDIT:###
 Based on info from Craig (in the comments below) it's simpler to use the new pinMode INPUT_PULLUP:

    pinMode(pin, INPUT_PULLUP);

Then wire the switch directly to ground.

This is the simplest way to wire a pushbutton to an arduino (no resistor needed) but **do** you need an extra line of code.

Also, the pin will read as HIGH when not pressed, and LOW when pressed (which might seem counter-intuitive)


body: I have the (more or less) Leonardo-compatible board Olimexino-32u4. Both, the TX- and RX-LED are permanently on. To reduce power-consumption, I want to disable them **by software**. What is the reliable way to do it?

title: Leonardo: disable TX- and RX-LED

Answers: 3

body:
Try adding this to your setup routine:

    TXLED0;
    RXLED0;

These macros (and their cousins TXLED1, RXLED1) are used to control the TX an RX LED's on Leonardo. They are defined in [https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/leonardo/pins_arduino.h#L95-L98](https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/leonardo/pins_arduino.h#L95-L98)

---

If that doesn't work you can try the solutions suggested here: http://forum.arduino.cc/index.php?topic=145262.0

body:
The TXled is connected to physical pin 22, or PD5. RXled is connected to pin 8, or PB0. They are connected to the cathode of the led, so they have to be HIGH to turn **off** the leds.

To turn them HIGH use:

    PORTD |= (1<<PORTD5);
    PORTB |= (1<<PORTB0);

Not sure what the firmware does, and if it sets the leds back to low every once and a while. So in addition I would suggest also setting those pins to inputs.

    DDRD &= ~(1<<DDD5);
    DDRB &= ~(1<<DDB0);

body:
Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.

Compare:
http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf

---

The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):

* In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:

        olimexino32u4.name=Olimexino-32U4
        olimexino32u4.upload.protocol=avr109
        olimexino32u4.upload.maximum_size=28672
        olimexino32u4.upload.speed=57600
        olimexino32u4.upload.disable_flushing=true
        olimexino32u4.bootloader.low_fuses=0xff
        olimexino32u4.bootloader.high_fuses=0xd8
        olimexino32u4.bootloader.extended_fuses=0xcb
        olimexino32u4.bootloader.path=caterina
        olimexino32u4.bootloader.file=Caterina-Leonardo.hex
        olimexino32u4.bootloader.unlock_bits=0x3F
        olimexino32u4.bootloader.lock_bits=0x2F
        olimexino32u4.build.mcu=atmega32u4
        olimexino32u4.build.f_cpu=16000000L
        olimexino32u4.build.vid=0x2341
        olimexino32u4.build.pid=0x8036
        olimexino32u4.build.core=arduino:arduino
        olimexino32u4.build.variant=olimexino32u4

* Create another folder 'variants' inside the olimexino folder.
* Inside that, create the folder 'olimexino32u4'.
* Now copy 'arduino/hardware/arduino/variants/leonardo/pins_arduino.h' to that folder
* Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins_arduino.h'.
* Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:

        #define TX_RX_LED_INIT DDRD |= (1<<5), DDRB |= (1<<0)
        #define TXLED1   PORTD |= (1<<5)
        #define TXLED0   PORTD &= ~(1<<5)
        #define RXLED1   PORTB |= (1<<0)
        #define RXLED0   PORTB &= ~(1<<0)

I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools->Board menu.


body:
I have the following sensor stick: https://www.sparkfun.com/products/10724

It has an accelerometer, gyroscope, and magnetometer.

I have connected it to an arduino and am reading the accelerometer values while the sensor is completely flat and the values jump all over the place:

ie
0
2
3
7
-5
12
35
-3
...

This is how I am reading them:

    void Accel_Init()
    {
      Wire.beginTransmission(ACCEL_ADDRESS);
      Wire.write(0x2D);  // Power register
      Wire.write(0x08);  // Measurement mode
      Wire.endTransmission();
      delay(5);
      Wire.beginTransmission(ACCEL_ADDRESS);
      Wire.write(0x31);  // Data format register
      Wire.write(0x08);  // Set to full resolution
      Wire.endTransmission();
      delay(5);

      // Because our main loop runs at 50Hz we adjust the output data rate to 50Hz (25Hz bandwidth)
      Wire.beginTransmission(ACCEL_ADDRESS);
      Wire.write(0x2C);  // Rate
      Wire.write(0x09);  // Set to 50Hz, normal operation
      Wire.endTransmission();
      delay(5);
    }

    // Reads x, y and z accelerometer registers
    void Read_Accel()
    {
      int i = 0;
      byte buff[6];

      Wire.beginTransmission(ACCEL_ADDRESS);
      Wire.write(0x32);  // Send address to read from
      Wire.endTransmission();

      Wire.beginTransmission(ACCEL_ADDRESS);
      Wire.requestFrom(ACCEL_ADDRESS, 6);  // Request 6 bytes
      while(Wire.available())  // ((Wire.available())&&(i<6))
      {
        buff[i] = Wire.read();  // Read one byte
        i++;
      }
      Wire.endTransmission();

      if (i == 6)  // All bytes received?
      {
        // No multiply by -1 for coordinate system transformation here, because of double negation:
        // We want the gravity vector, which is negated acceleration vector.
        accel[0] = (((int) buff[3]) << 8) | buff[2];  // X axis (internal sensor y axis)
        accel[1] = (((int) buff[1]) << 8) | buff[0];  // Y axis (internal sensor x axis)
        accel[2] = (((int) buff[5]) << 8) | buff[4];  // Z axis (internal sensor z axis)
      }
    }

Am I doing something wrong that these values aren't the same?

title: 9 DoF Sensor Accelerometer Readings Inconsistent

Answers: 1

body:
In 'FULL_RES' mode the number you get is amount of 4mg units.

So 1 is 4mg, 2 is 8mg, -4 = -32mg.

Also note that your current code doesn't interpret the first bit (so the 13th from the right) as the sign bit, so you'll never get negative values. ([Question related to this](https://arduino.stackexchange.com/questions/3401/bit-mask-first-2-bits-of-16-bits-for-accelerometer))

PS I think it is actually more like 3.9mg.


body:
I have a Arduino Mega 2560 connected to

1. L293D Motor Driver IC connected to two small size dc motors.
2. MPU-9150 using i2c
3. Xbee v1.1 arduino shield by seeed
4. Li-po battery, 7.4 volts, 2200 mah.

All components are tested separately, they all are working fine, the sensor readings showing data on serial monitor, the l293 drives the motors, xbee sends wireless serial data on pc, and li-po is also working fine.

I have checked the wiring alot of times. It all seems to be correct.

The problem arises when i connect all of them together, since I am using a single power source, I power the l293d with the Li-po and the Arduino also with the Li-po.

1. When the L293D is powered using Li-po and it starts drawing current from the battery, the serial monitor/arduino gets stuck. It doesnt show sensor readings anymore, while the dc motors start spinning. And they continue to spin, until I break connection with the battery.

2. Without the l293d powered, the sensor readings are working fine, everything is going normal, as it should, but as soon as the l293d is connected, arduino is stuck..

I have searched alot of forums for this, found some info, perhaps something to do analog and digital ground? mpu-9150 is digital ground. So that is why it stops the arduino mega as the l293d starts drawing current. All hell breaks loose.

Can anybody please help me with this? it is giving me headaches ever since!

title: Arduino gets stuck: battery powered, wireless, dc motor drive

Answers: 1

body: My guess is that your motors are drawing too much current and the voltage from your battery is dropping too low for the voltage regulator on the Arduino. Looking at the data sheet, the L293D will provide up to 600-mA for up to 2 motors at a time. That's up to 1.2 amps, a whole lot of current. I would suggest trying to power your arduino from a separate 9 volt battery as an experiment.


body:
I am trying to prep my wiring for a 8x8 Led Matrix w/ Bluetooth according to the following instructable:

http://www.instructables.com/id/Arduino-SPI-7-Bi-color-LED-Matrix-Scrolling-Text-D/?ALLSTEPS

Instead of soldering everything together I'd much rather use a breadboard. I'm new to wiring, breadboards, and Arduino's in general. I was wondering if anyone could look over my sketch and see that the connections I've made are valid.

I'm basing my wiring off this image (See original instructable for higher resolution):
![enter image description here][1]

I realize the bluetooth module isn't the same. I'm just using this as a reference. The wires leading off the top of the board will be going to the LED Driver module.

EDIT: Thanks for the feedback guys. I have decided to go with the Innogear HC-05 module. I've adjusted the wiring according to that model.
As per the suggestions, I've switched my power and ground rail and eliminated the resistors and ground for TX communication. (I've still kept a ground for the BT).
Here's my new attempt:
![enter image description here][2]

  [1]: https://i.stack.imgur.com/UkLpO.jpg
  [2]: https://i.stack.imgur.com/RoBTD.png

title: Help with wiring? Fritzing example inside

Answers: 2

body:
Those are, in fact, the same board. When you look at this image (from Amazon)...

> ![][1]

...you can see that there are really six pins, just two of them aren't soldered.
****
**Your circuit:**

 - On the power rails, you have the 5V and ground switched. It'll work okay, but you're asking for trouble later on when trying to work with it and accidentally plugging a wire into the wrong rail.
 - Also, from the reviews on Amazon, it says that it can be powered with 5V since the breakout board provides voltage conversion. However, no one specifically mentions the TX/RX, so I'd not risk it. [This module](http://www.amazon.com/Innogear-Wireless-Bluetooth-Transceiver-Arduino/dp/B00JP05S6C/ref=cm_cr_pr_product_top) (seems to be same chip) costs less and a reviewer specifically says that it converts voltage for both power *and* the TX/RX.
  - I'm not going to verify the resistor values, since you don't seem to need them if you get the other module I listed.
  - If you still did want to do the 5V/3.3V conversion, you should connect the power wire to the 3.3V pin, not the 5V rail on the breadboard

**tl;dr:** it seems as you just need to skip the resistors for the yellow wire and make a direction connection. I'm not 100% sure about *that specific part* but there was another one that a reviewer specified that this was okay.

Note: I cannot comment on the other wires for the shields, but at a quick glance it looks good.

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

body:
I am the author for the Instructable ethanx94's wiring is based on. It seems like the active and helpful members here have already helped iron things out.

If anyone is using the Arduino sketch downloaded from my instructable but is using ethanx94's wiring, do remember to change the SPI SS (Slave Select) pin in the sketch from 10 to 53 to reflect the correct pin used.

Look for the following line in the sketch and change the pin number 10 to 53:

    int SPI_CS = 10;// This SPI Chip Select pin controls the MAX7219
<!---->

    int SPI_CS = 53;// This SPI Chip Select pin controls the MAX7219


body:
I am following [this][1] guide. Now I want to create the Create the "ArduinoCore library". But when I am creating a new project, I can not select ATmega16U2 as MCU type.

But my Arduino Due R3-E and UNO SMD R3 both use ATmega16U2.

What shall I do O_o???

  [1]: http://horrorcoding.altervista.org/arduino-development-with-eclipse-a-step-by-step-tutorial-to-the-basic-setup/

title: MCU Type ATmega16U2 not avaliable in Eclipse AVR Plugin

Answers: 1

body:
The `ATmega16U2` on those boards isn't intended to be programmable by the end-user. It's only there to help convert from USB to TTL serial, which lets your computer communicate with the board's main microcontroller. It replaces the FTDI chip which was used on some older boards.

In the case of the Uno, the main microcontroller is the `ATmega328`. For the Due, it's the `AT91SAM3X8E`. If you want to program them from the Arduino IDE, you can usually just select the board by name from the drop-down menu.


body:
I am new on Arduino, and I am trying to use the Ethernet shield...

but it need:

- IP adress

- MAC adress

IP adress is easy to get... but not MAC..

how can I get my arduino MAC adress?

title: Arduino Mega - get mac adress

Answers: 3

body:
Arduino doesn't have a MAC address, your Ethernet adapter shield however will. The MAC address is likely printed on the interface and is constructed from 12 hexadecimal numbers, usually grouped 2 hex digits at a time.

If it isn't printed on the box or the shield, then the only way to find out is to connect it to your network, configure a valid IP address on the shield and try to connect to it (eg. ping to the address) from your PC) Then you can list MAC addresses from your PC  with `arp -a`.

Or when using dynamic addresses and DHCP, you can find the mac address in you DHCP server (probably your home router).

Either way, you need a sketch on your Arduino to configure an IP address.

body:
> Current Ethernet shields come with a sticker indicating the MAC address you should use with them.

([source](http://arduino.cc/en/Guide/ArduinoEthernetShield))

body:
A MAC address must be unique throughout the environment in which it operates, but apart from that is largely arbitrary.  Typically the problem is solved by selling 3-octet prefixes (called OUI's) to manufacturers, who then uniquely assign the remaining 3 octets to individual device units they manufacturer.

However, if you are unable to discovery a globally unique address assigned to your device by its manufacturer, and know that its traffic will be confined to a local network, you can use a privately assigned (ie, "made up") address with the **Locally Administered** bit set.   An address of the form

    02-xx-xx-xx-xx-xx-xx

or any other with the 2's bit of the first octet set will satisfy this criteria as long as you guarantee that it is unique in your system.

Be especially careful not to set the 1's bit of the first octet - if you do so, traffic will be marked as broadcast and so given wider distribution/attention than needed, wasting network capacity and processor time of connected devices.


body:
I want to drive my model trains (märklin) with my arduino UNO, it requires 32 watt (`0-12/24v, 2A MAX(changes)`)
This is Direct current

How can I amplify the output of the arduino to get my 32 watt?

title: Arduino amplifier

Answers: 2

body:
You certainly can. For relatively small amplifications, you can use transistors. MOSFETs are similar and work well for larger solid state amplification. If all you need is to turn power on or off (no switching faster than ~20Hz) a relay is you best bet, but most standard ones take more power than a raw arduino output can provide so you have to buy one for this purpose. They are all easy to use, for the most part just plug in ground, power, signal, and signal out. You can look up any of these for more details on use, it should not be hard to find.

The easiest pre-built solution is something like this relay board: http://www.sainsmart.com/arduino-compatibles-1/relay/arduino-pro-mini.html

body: This company, among others, has a range of drivers, meeting your volt/current/PWM speed control requirements, with good documentation, manual and use examples. http://www.pololu.com/category/11/brushed-dc-motor-drivers


body:
I'm a computer programmer, but I've never done anything with Arduino. I'd like to build something that holds a polisher (this one, in specific: http://www.homedepot.com/p/BLACK-DECKER-6-in-Random-Orbit-Waxer-Polisher-WP900/202516385) on a metal pole, and moves the polisher up and down (vertically) on the pole at varying speeds (I'd like to use arduino to control the motor/speed)?

Is this the sort of thing Arduino would be able to do? If so, can anyone point me to any motors that would work? If not, any tips on where else I should look?

title: Moving an item on a pole, can an Arduino work for my project?

Answers: 1

body:
I am also a software guy by profession. I've always liked tinkering with electronics, and have recently gotten into Arduino. It is an excellent platform for developing hybrid hardware/software solutions for problems like this. It is very easy to use, both hardware and software.

There is a large ecosystem of add-ons called "Shields" that just plug in. You can probably find a motor control shield that will do exactly what you want.

Your biggest challenge, I think, is going to be mechanical. How will you hold the polisher in position, and make a mechanism that will raise and lower it?

Off the top of my head what I come up with is a U shaped metal bar with a threaded rod in the opening of the U. You'd build a "sled" that would grip the bar and would have teeth that would grip the threaded rod. Then your would have a motor on the end of the assembly that would turn the threaded rod to move the sled up and down on the bar. You'd attach the polisher to the sled. You'd probably need a spring or rubber holder so that the polisher would press gently on the surface being polished but with some freedom of motion.