body:
Processor pins have strictly limited current drive capability.

- The rated values may vary depending on whether you want a high or low drive.
- Some processors will supply only a few mA and the most you will usually officially get is in the 20 to 30 mA range.

- There is usually a total current limit for the processor and only a few pins can provide peak current simultaneously.

- Processor pins have significant effective resistance and a high voltage will "drop" as increasing current is drawn and a low voltage will rise as load increases. Pins MAY be specific with a maximum short circuit current but at that point a high pin will be pulled low and a low pin will be pulled high so short circuit current has limited applicability.

Even if you have a say 25 mA per pin rated processor the power available is small. 25 mA · 4V say (1V drop on 5V Vcc) = 100 mW. Most motors will take more than that and only very small motors will run well when powered only by a pin.

Electric motors and inductors will generate significantly high voltages when current is interrupted - voltages of tens of volts can easily result and 100+ volts can happen. Connecting a motor of inductor to a processor pin directly is an invitation to destruction. Murphy will often oblige.

---

A transistor (bipolar or MOSFET) that will drive typical hobby motors costs 10's of cents (or free from scrapped equipment) and allows the port pin current drive to be buffered and "amplified". Use of a transistor or other buffer is an extremely good idea if you have one or a few processors and do not wish them to die semi-randomly.

**MOSFET motor driver** - [**from here**](https://www.picotech.com/library/application-note/some-power-pwm-drivers-for-electric-dc-motors) - section 8.

Voltages and part numbers are for their example - select to suit.
A NPN biploar could be used with the addition of an input resistor to the transistor base.

[![enter image description here][1]][1]

Bidirectional driver - if you want the driver to be able to drive a load high and low this circuit will work. [from here](http://www.electronics-tutorials.ws/transistor/tran_7.html)
The input gate is in this case the internal processor driver. The two MOSFET gates connect directly to the processor pin. Vdd should usually be no higher than processor Vmax_drive_out. Slightly higher can be made to work with suitable design. Much higher voltage loads can be driven with this circuit (or similar) plus one extra transistor.

[![enter image description here][2]][2]

---

A buffer such as a ULN2803 (and other family members) will drive 8 channels x 500 mA/channel and several can be paralleled.

---

A ULN2803 is essentially 8 x "Darlington" transistors with emitters connected to a common ground, 8 x "open collector" (unconnected) collectors, and 8 flyback diodes to deal with over voltage spikes (use optional). (There is a ULN280x family with slightly different input characteristics).

This device provides a reasonably priced means of providing 8 x 500 mA pull down drivers. A load connected from an output to V+ is turned on when the input pin is driven high. Once you've used one a few times you'll find them trivially easy to use and very useful. (There is also a ULN200x family with 7 channels per package).

[YouTube "how to" video](https://www.youtube.com/watch?v=HE4CqVR7H3s)

---

[Driving a stepper motor](https://graigroup.wordpress.com/2008/04/27/stepper-motor-driver-using-uln2803/)

[![enter image description here][3]][3]

[Also here](https://graigroup.wordpress.com/2008/04/27/stepper-motor-driver-using-uln2803/)

---

[Driving small DC motors](http://profmason.com/?s=gearhead) - and quite a lot else.

[![enter image description here][4]][4]
[A zillion examples](https://www.google.co.nz/search?q=uln2803+motor+driver&biw=1164&bih=817&tbm=isch&tbo=u&source=univ&sa=X&ved=0CCAQsARqFQoTCJ_f69jo0MgCFUQrpgodKL4CZA)

[Digikey - available in 1's if desired](http://www.digikey.com/product-detail/en/ULN2803APG,CN/ULN2803APGCN-ND/856431) $0.72/1, $0.29 in 1000's.

[**ULN2803 datasheet**](http://www.toshiba.com/taec/components2/Datasheet_Sync/201212/DST_ULN2803APG-TDE_EN_22738.pdf)

---

[For sale at Sparkfun](https://www.sparkfun.com/products/312)  - can be had rather cheaper but these are available

  [1]: https://i.stack.imgur.com/s4cSN.gif
  [2]: https://i.stack.imgur.com/bRw7X.gif
  [3]: https://i.stack.imgur.com/JncuL.jpg
  [4]: https://i.stack.imgur.com/Mmgi9.jpg


sender: user

message:
Reasons why it is not OK to connect a relay directly from an Arduino digital pin

After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?

If not (most likely):

1. Can someone give a detailed explanation and might as well important cautions on current limits and stuff?

2. How can one control such components without risking the Arduino? What are some common means to accomplish this?

3. What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

I'm just a beginner who wants to be extremely cautious. Thanks.

sender: assistant

body:
Have a look at the simple circuit on this [PDF][1] from the Arduino Playground.  It shows a single transistor to drive a small relay.

As Russell says in his answer, a ULN2803 or similar is a chip which will allow you to drive several small relays, which is neater than using several transistors, if that's what you want.

(Also note the diode "D1" in the circuit I linked - you need this, it's to protect the transistor from eventually being damaged by inductive spikes generated when the relay turns off.  Some of the ULN-style chips have this diode built in, which is why you don't always see it in schematics.)

  [1]: http://playground.arduino.cc/uploads/Main/relays.pdf


body:
To really protect your arduino it's worth putting a photo-coupler on the pin and driving your circuit that way.  Then no stray inductive charge or short can affect the arduino.

They are also called OptoIsolators or Optocouplers.

http://forum.arduino.cc/index.php?topic=143954.0


body:
Let us look as some basic's, these seem to be the basis of a lot of questions:

A capacitor when power is switched on draws a huge amount of current that tapers off as it gets charged. This curve is also called the RC time constant (this is close but not exact "[http://www.electronics-tutorials.ws/rc/rc_1.html][1]" will give a better explanation).

When switching off a capacitor discharges at an exponential rate (RC time constant) depending on the value, charge voltage and the load.  This makes them good for holding power for a short time when the power fails.

An Inductor draws nothing when first switched on but the current increases exponentially until its voltage reaches the supply voltage.

When switched off the inductive field in the inductor collapse causing the polarity to reverse.  The voltage will rise unlimited until typically something externally limits it. The faster it is turned off the quicker the rise time and voltage.  Energy will cease to flow when the inductive charge is dissipated.  Guess where this current goes when the inductive load such as a relay is connected to a port pin?

For this reason you need to put a diode (commonly called a fly wheel diode) across the inductive load.  Google for: "inductor/capacitor charge curve" you will find a lot of nice graphs explaining this. This diode is not necessary if you use an appropriately rated MOSFET (UIS). The UIS (Unclamped Inductive Spike) information is in the MOSFET data sheet.  If you look at the circuit it has the cathode + connected to the most positive side of the power supply.  In this configuration it will not conduct unless the voltage is reversed (when the inductive load is switched off).

Another common misconception is you can load a microprocessor I/O to the maximum. This is bad design. They give you a maximum per pin, per port and for the chip.  At room temperature you will probably get away with it for a while.

Let us assume we have a port with a 40mA load.  The output is 0.005 from the power rail.  Using Ohm’s law we are dissipating 20 milliwatts of power on one pin. At this rate of loading it does not take long to over heat the device because of internal power dissipation.

When the output pin is changing state it draws more current because it has to charge or discharge its internal and the external capacitance, ‘more heat’, more speed ‘more heat’.

If you look some of the specs will give you a maximum temperature, it is for the junction on the die, not the case temperature.  Plastic is a poor conductor so heat sinking the package does not do a lot.  Now consider this along with the ambient temperature.  The ratings are given typically with the device at 25C, guess what happens when it gets warmer.

Have fun,

Gil

  [1]: http://www.electronics-tutorials.ws/rc/rc_1.html


message:
Code for password-activated LED via Bluetooth serial

I have this pretty simple task to light up an LED for 3 seconds when I send the right password from my Android phone to the Arduino via Bluetooth. I am using an HC-05 Bluetooth Module. My LED is connected to Pin 9 of the Arduino I/O. TX and RX of HC-05 is connected to Pins 1 and 0 of Arduino respectively. Here's the code I am using:

    int output = 9;         //I will be using to control a DC motor(LED is just for testing).
    int output2 = 10;
    char final[4];
    char correct[4] = {'Q','W','E','R'};
    int pass_true;

    void setup() {
      pinMode(output, OUTPUT);
      pinMode(output2, OUTPUT);
      Serial.begin(9600);

    }

    void loop() {
      while(Serial.available()){
        for(int i=0; i<4; i++){
          final[i] = Serial.read();
        }
        for(int i=0; i<4; i++){
          if(final[i]==correct[i]){
            pass_true = 1;
          }
          else{
        pass_true = 0;
        break;
          }
        }
      }

      if(pass_true==1){
        digitalWrite(output, HIGH);
        Serial.println("ON");
        delay(3000);
        pass_true = 0;
      }
      else{
        digitalWrite(output, LOW);
      }

    }
I am using Bluetooth SPP Pro Android App to send the 4-byte pass code ("QWER")

The problem is the LED wont light up. I tried replacing the LED thinking that it may be a dead one but it's not. The "TX" LED on the board blinks everytime I press "SEND" in the Bluetooth App, but still Pin 9 doesn't seem to produce the HIGH output at all. Is there a problem with the code?

body:
Instead of

    while(Serial.available()){

please try

    while(Serial.available() >= 4){

Depending on how your transmitting application is buffering the writes, the loop()'s password check may be triggering on a single byte of input each time.

You may also want to make the code a bit more fault-tolerant.  For example what if there's a bit of noise in the line, or the operator pushes [Enter] first before entering the code.  The input buffer will fill up a few characters, then the password will not match because it spans, say input bytes 3,4,5,6.  Maybe throw away any old input based on elapsed time, etc.


body:
Try using the following code you need to use String and concatenate that

        String rcev_data="";
    bool chk=false;
    \#define output 9

    \#define output2 10

    void setup()
    {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(output, OUTPUT);
      pinMode(output2, OUTPUT);
    }

    void loop()
    {
      // put your main code here, to run repeatedly:
      while(Serial.available())
      {
        char rxx = Serial.read();
        recv.concat(rxx);
        delay(10);
        if (recv == "QWER")
        {
           chk=1;
           break;
         }
        else
         chk=0;
     }

      if (chk)
      {
        digitalWrite(output,HIGH);
        Serial.println("ON");
        delay(3000);
        chk=0;
      }

      else
      {
        digitalWrite(output,LOW);
      }
      recv="";
    }


message:
Passing a static array to a function

I have a functon that creates a instance of `KeyReport` and I want to fill statically the `KeyReport.keys` array. I'm new in the Arduino world so I'll put a example to explain it better:

    void sendKey(byte keys[6], byte modifiers)
    {
      KeyReport report = {0};

      report.keys = keys; // This is my main trouble
      report.modifiers = modifiers;
      report.reserved = 1;
      Keyboard.sendReport(&report);
    }

    void setup(){
    delay(3000);
    sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this
    }

    void loop(){}

body:
    report.keys = keys; // This is my main trouble

You can't assign the contents of one array to the contents of another array.  You can only copy the contents manually from one to the other.

The simplest way is with a loop:

    for (int i = 0; i < 6; i++) {
        report.keys[i] = keys[i];
    }

There is a helper function - `memcpy()` - which can do it for you if you prefer:

    memcpy(report.keys, keys, 6);

It effectively does exactly the same thing - copy 6 bytes starting from the address of `keys` into the addresses starting at `report.keys`.

As for the "hard coded" reports I suggest you create some `const` arrays in the global context - and even use `PROGMEM` to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data.  It may be simpler to split the report into 6 individual variables and pass each byte separately:

    void sendKey(byte k0, byte k1, byte k2, byte k3,
                 byte k4, byte k5, byte modifiers)
    {
      KeyReport report = {0};

      report.keys[0] = k0;
      report.keys[1] = k1;
      report.keys[2] = k2;
      report.keys[3] = k3;
      report.keys[4] = k4;
      report.keys[5] = k5;
      report.modifiers = modifiers;
      report.reserved = 1;
      Keyboard.sendReport(&report);
    }

    sendKey(0x17, 0, 0, 0, 0, 0, 0x05);

Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.


message:
LED cube and 200 mA limitation

I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?

body:
The current limit you quote is the maximum current that the main chip on the Arduino can tolerate through its 5V or GND pins.

As the chip itself consumes (round numbers demonstrate the theory) say 50mA that leaves 150mA in total that can be sourced or sunk through IO pins.

If you want to supply 20mA per LED (that is actually overkill - you can use considerably less and have very little difference in brightness) that means you can have, illuminated at any one time, (150 / 20 = ) 7.5 LEDs.

To increase the number of LEDs you can drive at once you can:

* Reduce the current by increasing the resistor values.
* Use multiplexing so that, although it looks like all LEDs are on at once, only a few are actually on at once.
* Use external LED driving circuitry (transistors, LED driver shift registers, etc).

All this pertains purely to the current that passes through the main chip itself.  It does not pertain to any current you draw from the 5V or 3.3V pins.  The maximum current through those pins is limited by the voltage regulator they are attached to, and also by the voltage that you are supplying the board with (the higher the voltage, the more voltage has to be dropped, and so the more heat is generated per mA drawn).

The 5V regulator has around 800mA limit when supplied with 6.5V.  If supplied with 12V the limit is considerably less (since it will get too hot and go into *thermal shutdown*).  You subtract what you are drawing through the chip (maximum 200mA) and that is how much current you have available.

The 3.3V regulator is driven from the 5V regulator, so any current drawn from the 3.3V pin must also be subtracted from what is available on the 5V pin.


body:
I'm assuming you're talking about an 8x8x8 cube.

The 200mA is for all IO. The regular 5v line can supply 500mA. Since you don't have 64 pins available, you are not supplying the leds via the Arduino directly. Probably using some shift register, or led driver chips for the 64 (cathode) columns. For the 8 levels you'd use some PNP transistors or P-channel mosfets.

So the Arduino won't drive any led directly, so it will only use a few tens of milli-amps. Since you'll draw around 1.3A when all leds are lid, you should power the external components directly from the power supply, instead of via the Arduino. Or you'll hit the 500mA limit.

So the Arduino is just pushing the levers, and not doing any of the hard work (crane analogy).


message:
Powering Arduino with 110v and controlling relay

I've found a lot of tutorials about how to use an Arduino to control power supplies to lamps and things like that using a relay. However, I also need to power the Arduino with the same power that is going through the relay.

In other words, I'd like to be able to plug my device into the wall. The device would use the 110VAC to power the Arduino. My device would also have some outlets that I could plug something into. The Arduino would be connected to a relay and would decide when to enable electricity to the outlet. The important part being that I would like everything to be on one power source.

Do I need to have a step down converter to transform the power, in addition to the relay? Is there some sort of break out board that has both of these functionalities in one board? What is the best way to do this?

body:
In these cases where power must come from mains, my preferred solution is to buy a cheap phone charger+usb cable from ebay. They are sealed and safer than do-it-yourself solutions. The power adapter is barely larger than a normal plug for mains.

If you absolutely need to reach the arduino with only one cable, you can still use the solution i gave, only use a power cord to reach the contraption, then use a socket expander for mains and very short usb cable.


message:
Arduino WIFI compiler error

Just bought an ESP8266 module to try it using my arduino uno R3. I have connected my WIFI module correctly, anyways evenb if i disconnect it, the error occur.

While trying to upload the WIFI (connect with wpa) sketch i get several errors.

First i tried uploading the hole sketch, i got those errors:

 /usr/share/arduino/libraries/WiFi/WiFi.cpp: In member function ‘uint8_t* WiFiClass::macAddress(uint8_t*)’:
 /usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: unable to find a register to spill in class ‘POINTER_REGS’
 /usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: this is the insn:
 (insn 35 25 26 2 (set (reg:QI 23 r23)
  (mem/c:QI (plus:HI (reg/f:HI 28 r28)
          (const_int 2 [0x2])) [3 S1 A8])) /usr/share/arduino/libraries/WiFi/WiFi.cpp:110 28 {movqi_insn}
      (nil))
 /usr/share/arduino/libraries/WiFi/WiFi.cpp:112: confused by earlier errors, bailing out

After that i tried to only import just the libraries and try to compile it. Even with this method i get errors

Code

    #include <WiFiServer.h>
    #include <WiFiClient.h>
    #include <WiFi.h>

error:

    In file included from /usr/share/arduino/libraries/WiFi/WiFiServer.h:8:0,
                     from sketch_oct20b.ino:1:
    /usr/share/arduino/hardware/arduino/cores/arduino/Server.h:4:29: error: expected class-name before ‘{’ token
    In file included from sketch_oct20b.ino:1:0:
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:14:3: error: ‘uint16_t’ does not name a type
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:17:22: error: field ‘uint16_t’ has incomplete type
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:18:24: error: ‘uint8_t’ has not been declared
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:20:11: error: ‘size_t’ does not name a type
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:21:11: error: ‘size_t’ does not name a type
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:22:3: error: ‘uint8_t’ does not name a type
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:24:9: error: ‘Print’ has not been declared
    /usr/share/arduino/libraries/WiFi/WiFiServer.h:18:42: error: ‘NULL’ was not declared in this scope

I can just figure out some syntax errors, but my c is not good enough to understand much of it.

Can anyone tell me what am i doing wrong and show me how it will be done?

body: The WiFi libraries (such as `Wifi.h`, `WifiClient.h`, and `WiFiServer.h`) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. `Serial.write()`, etc.)


message:
Can I place bootloader directly onto Atmega2560 and have USB?

I am working on a prototype device which I am now on my 2nd board iteration and moving away from it being a shield and wired to an arduino mega2560 board.

I have used the freely available Arduino mega 2560 schematic and incorporated this into my project.

I notice that there are 2 µcontrollers on this schematic, (Atmega2560 & Atmega16U2)

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

On the searching I have done I'm getting myself terribly confused.
Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

However, I was intending to flash a boot loader that would make the device appear to a computer (over usb) as a midi controller device.

I am unclear if I can indeed interface a usb port directly to the ATmega2560,  and upload my sketch code AND a midi-over-usb boot loader..
I doubt the advice because the ATmega16U2 (i think) has a built in UART to communicate via usb and that the 2560 does not...

Sorry If this all sounds vague, I'm searched out and confused...

thanks.

body:
> if I can indeed interface a usb port directly to the ATmega2560

You cannot interface USB directly to the ATMega2560, because that µC has no USB support build into (and VUSB is probably no solution either).

If your program is simple enough, then it could fit onto the ATMega16U2 on its own, eliminating the 2560.


body:
> I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

That is a misunderstanding.

The bootloader is on the 2560.  The 16U2 contains its own custom firmware which acts as a USB CDC/ACM interface to connect the USB to the 2560 as a TTL UART connection.

The same can be done using any number of other similar devices, such as the FT232R etc.

You cannot directly connect the USB to the 2560 since the 2560 has no concept of what USB is.  The 16U2 has that knowledge, but doesn't have as many IO pins as the 2560, so combining the two gives you a total system that both understands USB and has lots of IO.


body:
> Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

I recommend that you keep the '16U2 and ditch the '2560. Since the '16U2 is both native USB capable *and* has sufficient I/O for a MIDI controller then you should use *that* one for your project.

Of course, since there's no Arduino core for the '16U2 you may want to consider either learning AVR programming without Arduino (when will there be a better time to do so?), or switching to the (overpowered) 'U4, which uses the Leonardo core.


message:
Arduino Pro Mini lower BOD problem

I am planing to build a project where an arduino pro mini 3.3V runs on 2 aa batteries. The standard brown out detection shuts it down at about 2.7/2.8V where it could run on lower voltages too.
So I changed the efuse to get the BOD down to 1.8V. I connected a serial to usb converter and used avrdude:

    avrdude -c avrisp -p m328p -P COM5 -b 19200 -U lfuse:w:0xff:m -U hfuse:w:0xda:m -U efuse:w:0x06:m

Then I tried to upload a program using the arduino 1.0.3 IDE but I got this error:

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

With 1.6.4 I got another error:

        avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x75
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

After some googling I tried some lower baud rate (the standard seems to be 57600). With 19200 everything worked with avrdude, so I created a new entry in the boards.txt

        ##############################################################

    pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328 BOD 1.8V

    pro328.upload.protocol=arduino
    pro328.upload.maximum_size=30720
    pro328.upload.speed=19200

    pro328.bootloader.low_fuses=0xFF
    pro328.bootloader.high_fuses=0xDA
    pro328.bootloader.extended_fuses=0x06
    pro328.bootloader.path=atmega
    pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
    pro328.bootloader.unlock_bits=0x3F
    pro328.bootloader.lock_bits=0x0F

    pro328.build.mcu=atmega328p
    pro328.build.f_cpu=8000000L
    pro328.build.core=arduino
    pro328.build.variant=standard

And burned a bootloader using the 1.0.3 IDE again. After that I could upload a blink program. My goal is to upload a mysensors sketch though and that doesn't work. I am getting an error

    avrdude: verification error, first mismatch at byte 0x0002
             0x69 != 0x61
    avrdude: verification error; content mismatch

Mysensors seems to have general problems with old arduino IDEs so I tried to use the newer 1.6.4 but I can't define my own board there and if I try it without I get hte out of sync error (because it's still using the wrong baudrate I guess).

I also tried using another arduino uno as ISP => same results

How can I fix this? Is there a way to define my own board for 1.6.x?
Whats the standard way of doing this and why does the change of the efuse results in me not beeing able to program the mini any longer?

Thanks for every answer/help!

body:
When you go below (or above) the manufacturer's voltage/clock specifications, expect some problems. One chip may work another will not.  Remember the lower the voltage normally the slower the clock needs to be.  The CPUs are cut from a wafer (size and geometry specific) which may contain many thousand CPU die, they are at different locations on the wafer they will be a little different and they make more then one wafer.

Check the data sheet, it will show what clock speed will work at what voltage.  As the CPU clock changes so will your baud rate so plan on recalculating that if you change the clock. Example:  If you are operating with a 16MHz clock and change it to 8MHz the baud will be exactly 1/2.  If at 9600 it will be 4800 unless you modify the clock dividers.

Your error indicates a potential baud rate problem. One of the funny things that happens when the voltage is above/below the manufacturer's speck not all instructions operate properly over temperature. Clock problems should be expected.


message:
Shift register 1's and 0's array to 4 int's function not working

I'm not sure if i should post this here or on StackOverflow but I am coding for an LED cube controlled with 4 shift registers. I have a function in a .h file that is supposed to take an array of 1s and 0s (to represent each LED) and then use the shiftOut function to shift the data into the shift registers. This is complicated that the shiftOut function has to take a int which it shifts out in binary and only goes 8 bits at a time. This means I have to separate my array into 4 groups of 8 and then convert each group into an int. I have tried to make my function do that but it is compiling fine and then not lighting up any LEDs. I believe the problem has to do with the way I'm separating the array into 4 smaller arrays althoughI can not figure out exactly what is going wrong, here is my code.

Main program:

    #include <LEDcube.h>

    int data = 2;
    int clock = 3;
    int latch = 4;

    void setup()
    {
      pinMode(data, OUTPUT);
      pinMode(clock, OUTPUT);
      pinMode(latch, OUTPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      int layer[32] = {0,

                      1,1,1,1,1,
                      0,0,0,0,0,
                      1,1,1,1,1,
                      0,0,0,0,0,
                      1,1,1,1,1,

                      0,0,0,0,0,0};
      write(data, clock, latch, layer);
    }
LEDcube.h:

    #include "Arduino.h"

    int binToNum(int bin[])
    {
      int j = 1;
      int num = 0;
      for(int i = 0; i < 8; i++, j = j * 2)
      {
        if(bin[i] == 1)
        {
          num = num + j;
        }
      }
      return num;
    }
    void write(int data, int clock, int latch, int layer[])
    {
      int reg1[8];
      int reg2[8];
      int reg3[8];
      int reg4[8];
      for(int i = 0; 1 < 8; i++)
      {
       reg1[i] = layer[i];
      }
        for(int i = 0; 1 < 8; i++)
      {
       int q = i + 8;
       reg2[i] = layer[q];
      }
      for(int i = 0; 1 < 8; i++)
      {
       int q = i + 16;
       reg3[i] = layer[q];
      }
      for(int i = 0; 1 < 8; i++)
      {
       int q = i + 24;
       reg4[i] = layer[q];
      }
      int regnum1 = binToNum(reg1);
      int regnum2 = binToNum(reg2);
      int regnum3 = binToNum(reg3);
      int regnum4 = binToNum(reg4);
      digitalWrite(latch, LOW);
      shiftOut(data, clock, MSBFIRST, regnum4);
      shiftOut(data, clock, MSBFIRST, regnum3);
      shiftOut(data, clock, MSBFIRST, regnum2);
      shiftOut(data, clock, MSBFIRST, regnum1);
      digitalWrite(latch, HIGH);
    }

body:
The problem is you need to write your data with all of your bits consolidated into a single integer instead of as an array of integers. For example, if you were to `shiftOut(data, clock, MSBFIRST, 1)` that would send `00000001`, not `1`. So for example, if you want to send out 1,0,1,0,1,0,1,0 you need to send `shiftOut(data, clock, MSBFIRST, 170)`, because 170 in binary is 10101010. So you will need to figure out how to represent your data as an integer rather than array of integers of which you are only using the first bit.

**EDIT**:

I see that you are attempting to do a binary conversion, but your for loop is a little off. Try this instead:

    for(int i = 0; i < 8; i++)
    {
      if(bin[i] == 1)
      {
        num = num + j;
      }
      j = j * 2;
    }

Even if that fixes it, you will probably still need to some major refactoring to get decent speed, currently you are using 128 bytes of memory to represent 4 bytes worth of data. and there are plenty of other little inefficiencies here and there.

**EDIT 2**:

The simplest version of the above functionality is this:

    int data = 2;
    int clock = 3;
    int latch = 4;

    void setup()
    {
      pinMode(data, OUTPUT);
      pinMode(clock, OUTPUT);
      pinMode(latch, OUTPUT);
    }

    void loop()
    {
      int data1 = 0b1111100000111110; //Set a variable using a binary constant
      int data2 = 0b0000111110000000;
      digitalWrite(latch, LOW);
      shiftOut(data, clock, MSBFIRST, data1);
      shiftOut(data, clock, MSBFIRST, data2);
      digitalWrite(latch, HIGH);
    }

If you are going to be doing more bit level manipulation, you should probably learn various bit wise operators such as <<, >> &, ^, |, ~, &=, and |=. The [Arduino documentation][1] goes over them and what they do (scroll down, on the left under Bitwise Operators).

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


body:
As noted in Stu's answer, the question's code does not pack bits properly into the bytes that `shiftOut()` will unpack them from.

If you merely want to make things work, as opposed to packing stuff up one place so it can be unpacked another, just write the bits to your SR yourself.  For example:

    for (int i=0; i<32; ++i) {
      digitalWrite(data, layer[i]); // Put a bit on the data pin
      digitalWrite(clock, HIGH); // Pulse the clock
      digitalWrite(clock, LOW);
    }
    digitalWrite(latch, HIGH); // Pulse the latch
    digitalWrite(latch, LOW);

If the clock or latch need low-going instead of high-going pulses, reverse the order of writing `HIGH` and `LOW`.


message:
Arduino Uno "MEM CHECK FAIL" error

Just followed [a tutorial][1] on how to set up ESP8266 with my Arduino Uno R3. I have a serial connection and get a response of the Arduino but I'm stuck now at chapter "first commands".

I have successfully issued the `AT` command and also the `AT+RST` command and got a response. BUT, the response return was "invalid" at its end instead of "ready". Also theres an output "MEM CHECK FAIL!!!"

    AT

    OK
    AT+RST

    OK

     ets Jan  8 2013,rst cause:2, boot mode:(3,4)

    load 0x40100000, len 1396, room 16
    tail 4
    chksum 0x89
    load 0x3ffe8000, len 776, room 4
    tail 4
    chksum 0xe8
    load 0x3ffe8308, len 540, room 4
    tail 8
    chksum 0xc0
    csum 0xc0

    2nd boot version : 1.4(b1)
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size & Map: 8Mbit(512KB+512KB)
    jump to run user1 @ 1000

    ÃÕMEM CHECK FAIL!!! <<----------------------------- ???
    äslrô
    Ai-Thinker Technology Co. Ltd.

    invalid <<----------------------------------------- should be "ready"

Can anyone explain me what that means? Do I have to (re)flash the firmware? And also - are the instructions all the same? I have bought mine from China but it was sold at the same ESP8266 module on Amazon.

  [1]: http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf

body:
http://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-1-up-and-running/

According to the tutorial it's an undocumented bug with no fix.

If you change the name, baud, and set up the wifi and password you should be good to go


message:
Keyboard.print() skips keys

I'm playing with the Arduino Leonardo `Keyboard.print()` command, but I'm facing a annoying problem:

When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):

    Keyboard.print("echo \"This is a demo\"");
Output:

    echo his is a demo

And when I use this line:

    Keyboard.print("echo -This is \"a demo-");

Output (note the umlaut over the `a` instead of getting `"a`):

    echo 'This is ä demo'

I suspect that the problem is that my computer is configured to use Spanish layout.

What source code file can I change to fix this? I can't find the defines used by `Keyboard.print()`

body:
The Arduino assumes a US keyboard layout.  The thing with keyboards is they don't actually send the letters or symbols that are printed on the keys.  Instead the send a *scan code* that defines *where* on the keyboard the key is.  It is then up to the computer to convert those scan codes into actual letters and symbols, and that is performed by the keyboard mapping selected in the operating system.

Some special keys are known as *dead keys*.  These don't actually print a character on their own - instead they are used to modify the next key pressed - for instance the key which occupies the space a " would be on a US keyboard, on a Spanish keyboard, is a dead key which modifies the next key by adding an umlaut to it.

Since the Arduino doesn't know that you have a Spanish mapping, when you send a " it just sends what it believes is the location of that character on a keyboard, and of course it gets that wrong since it assumes the wrong keyboard layout.

So there are two things you can do to "fix" it:

1. Change your keyboard layout to US, but that will mean your normal keyboard will stop working properly.
2. Change how the Arduino thinks the keyboard is laid out, but that means lots of work to find the right scan codes.

The Arduino's keyboard layout is stored in the file `HID.cpp` in the Arduino core (`hardware\avr\cores\arduino` or somewhere like that - I forget off hand) and is the `_asciimap` array.  It is a list of the first 128 ASCII characters and the keyboard scancode mappings for them, including *modifier keys* like Shift.  You will have to find the scan codes for the keys you want to map on your keyboard layout and change the codes in that list.  For instance, the character " is listed as:

    0x34|SHIFT,    // "

Which is scan code 0x34 (52 decimal) coupled with the SHIFT modifier.  You will have to discover (maybe Google can help) what the 0x34 should be changed to so that it moves the " to wherever it is on a Spanish keyboard.


body:
In your particular case, the double quote ***is to be entered*** (using the [Spanish keyboard layout][1]) by Shift + the physical key labelled 2. On a [US keyboard][2], Shift + the physical key labelled 2 is "@".

Thus, this simply will get the desired result (the Arduino library assumes a US keyboard layout):

    Keyboard.print("echo @This is a demo@");

###More general solution

More generally, strings can be encoded as in the following table (the exact mappings depend on the particular keyboard layout - this will work for many European keyboard layouts).

If the *physical key* (and modifier key, if any) *exists* on [the US keyboard][2] to get the character typed out using the non-US keyboard layout, then this method works fine.

    To get   Use   Notes
    --------------------------------------------
    ;        <     Will result in Shift action
    :        >     Will result in Shift action
    (        *     Will result in Shift action
    )        (     Will result in Shift action
    /        &     Will result in Shift action
    ?        _     Will result in Shift action
    =        )     Will result in Shift action
    &        ^     Will result in Shift action

    -        /
    +        -
    _        ?

    "        @     Will result in Shift action

    ,        ,     The same
    .        .     The same
    #        #     The same

###Even more general solution

Even more generally, some keys are not on the US keyboard (e.g. the 102th key on European keyboards for the original PC keyboards, often with <, >, \, and |), and it is ***not*** possible to use [Keyboard.print()][3].

Instead, use the low-level [HID().SendReport()][4] function - with [code 100][5] (decimal) for the first parameter for the 102th key. See the library source code, Keyboard.cpp (/libraries/Keyboard/src/Keyboard.cpp), for how to use HID().SendReport().

###Alternative solution

Some operating systems enable entering characters using the keyboard and a numeric code.

This is at the expense of making it operating-system dependent (but making it independent of the active keyboard layout).

For example, Ctrl + Shift + U [on Linux][6] (GUI only, dependent on the window manager(?)). For the particular problem (the Unicode code point for `"` is *0022*), without any functional abstraction to reduce the redundancy:

    Keyboard.print("echo ");

    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press(KEY_LEFT_SHIFT);
    Keyboard.press('u');
    Keyboard.releaseAll();
    Keyboard.print("0022");
    Keyboard.press(KEY_RETURN);
    Keyboard.releaseAll();

    Keyboard.print("This is a demo");

    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press(KEY_LEFT_SHIFT);
    Keyboard.press('u');
    Keyboard.releaseAll();
    Keyboard.print("0022");
    Keyboard.press(KEY_RETURN);
    Keyboard.releaseAll();

Unicode code points [can be found at unicode-table.com][7].

###Media keys

Even though the media keys are listed in [the table][5] (e.g. code 128 for "Volume Up" on page 53), they do not work using the method described in the previous section. But there is [a solution][8].

###Platform

This was tested with:

 * [Arduino Leonardo][8]
 * The Spanish keyboard layout was added to the Linux settings and activated. There were 14 different ones to choose from, but I used the one labelled "Spanish". It was verified that "@" actually resulted in an output of "`"`". It was also verified that the Ctrl + Shift + U method worked.
 * Linux, [Ubuntu 19.10][9] (Eoan Ermine), but with [the buggy GNOME][10] replaced by [Cinnamon][11].
 * The Arduino Leonardo connected to an *extra current* port of a [D-Link][9] USB hub (necessary, for unknown reasons - probably a local problem)
 * Arduino IDE v. 1.18.10

  [1]: https://docs.microsoft.com/en-us/globalization/keyboards/kbdsp.html
  [2]: https://en.wikipedia.org/wiki/File:KB_United_States-NoAltGr.svg
  [3]: https://www.arduino.cc/reference/en/language/functions/usb/keyboard/keyboardprint/
  [4]: https://www.arduino.cc/en/Reference/HID
  [5]: https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf#page=56
  [6]: https://askubuntu.com/questions/88347/how-can-i-type-ascii-characters-like-alt-numpad-in-windows
  [7]: https://unicode-table.com/en/
  [8]: https://arduino.stackexchange.com/questions/8934/send-keyboard-media-keys-with-keyboard-library/75466#75466
  [9]: https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_19.10_(Eoan_Ermine)
  [10]: https://en.wikipedia.org/wiki/GNOME
  [11]: https://en.wikipedia.org/wiki/Cinnamon_(desktop_environment)


message:
I2C_Anything String / Char Array issues

I've been working with the lovely I2C_Anything.h (thanks to the great work and support from Nick over at http://www.gammon.com.au/forum/?id=10896&reply=9#reply9).. All working great, I was using Serial communication between Teensy 3.1 & mini pro but looking to replace with I2C - I was sending a file name across that was fine, but not managing to figure it out with the I2C_Anything technique.. here's some snippets:

**MASTER**

    const uint8_t MaxMP3Name = 13;
    //====================================
    // DATA STRUCTURE FOR MP3 SLAVE
    //====================================
    struct SEND_MP3_STRUCTURE{
      char Filename[MaxMP3Name];
      uint8_t VolLeft;
      uint8_t VolRight;
      uint8_t Command;
    };
    SEND_MP3_STRUCTURE txMP3;

    #define MP3_SLAVE_ADDRESS 77

    const uint8_t PlayFile = 1;
    const uint8_t PauseFile = 2;
    const uint8_t StopFile = 3;

    ... etc

    //#################################//
    //##  SEND MP3 COMMAND           ##//
    //#################################//
    void sendMP3Command(String MP3File, uint8_t Command) {
      char *TextArray[MaxMP3Name];
      MP3File.toCharArray(TextArray, MaxMP3Name);
      txMP3.Filename = TextArray;
      txMP3.VolLeft = VolLeft;
      txMP3.VolRight = VolRight;
      txMP3.Command = Command;
      Wire.beginTransmission(MP3_SLAVE_ADDRESS);
      I2C_writeAnything(txMP3);
      Wire.endTransmission(true);
    }

    ...etc

... not entirely sure what i'm doing, I've tried most variations (using String in the struct vs char *Filename[] and various other attempts).

**SLAVE**

    const uint8_t MaxMP3Name = 13;
    //====================================
    // RECEIVE DATA FORMAT
    //====================================
    struct RECEIVE_DATA_STRUCTURE{
      char Filename[MaxMP3Name];
      uint8_t VolLeft;
      uint8_t VolRight;
      uint8_t Command;
    };
    volatile RECEIVE_DATA_STRUCTURE RXdata;
    #define SLAVE_ADDRESS 77
    volatile uint8_t newData; // flag to detect I2C activity

    // MAKE GLOBAL VERSIONS
    String RX_Filename;
    uint8_t RX_VolLeft = 30;
    uint8_t RX_VolRight = 30;
    uint8_t RX_Command = 0;

    ... etc

    //#################################//
    //##  MASTER SENDING US DATA     ##//
    //#################################//
    void onReceiveEvent(int numbytes){
      if(numbytes == 16){
        I2C_readAnything(RXdata);
        newData = 2;
      }
    }

    ... etc

    void loop(){
      if (newData==2){// I2C received Data
        RX_Filename = RXdata.Filename;
        RX_VolLeft = RXdata.VolLeft;
        RX_VolRight = RXdata.VolRight;
        RX_Command = RXdata.Command;
        newData = 0; // Clear data sent marker
      }
    }

    ... etc

Hopefully you'll be able to see pretty quickly what i'm trying to do and the method I should be using to do it..

Thanks for any insights

Cheers

Andy

---

Sorry, still getting used to this comment vs editing questions business, didn't realise it would add my comment when I hit enter so it cut me off... here's full comment:

---

Hiya Nick, thanks for your suggestion, How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error:

 `"invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]"`

(on the Slave) - obviously the RXdata is updated during the interrupt so can't leave it out (despite the fact it compiles - but doesnt work)..

I got it working soon after I posted by breaking down the filename in the struct to separate chars, then assembling back into char array in a function I made.

That seemed to work fine, but only if I added null char at as the last char (0x00) - I can get the char `Filename[MaxMP3Name];` working, but only if I lose the volatile declaration, and it skips the last char.

Thanks for any further help Nick, I really appreciate all you do for the community and I know you're the best guy to help me (not to take anything away from anyone else that wants to jump in ;)

## Current solution i'm using that avoids the volatile erros ##

Obviously could be a for loop etc but I wrote it out this way just to debug and see where the issue was. Not perfect, but breaking it down this way seems to be overcoming the issue of trying to do anything with the volatile variable. (and i've got so much to figure out for so many other parts of the project that I was thinking i'd come back to it later once i'm done with other bits).. Cheers

    //#################################//
    //##  SEND MP3 COMMAND        ##//
    //#################################//
    void sendMP3Command(String MP3File, uint8_t Command) {
      char FileName[8];
      MP3File.toCharArray(FileName, MaxMP3Name+1);
      txMP3.File1 = FileName[0];
      txMP3.File2 = FileName[1];
      txMP3.File3 = FileName[2];
      txMP3.File4 = FileName[3];
      txMP3.File5 = FileName[4];
      txMP3.File6 = FileName[5];
      txMP3.File7 = FileName[6];
      txMP3.File8 = FileName[7];
      txMP3.VolLeft = VolLeft;
      txMP3.VolRight = VolRight;
      txMP3.Command = Command;
      StartMicros = micros();
      Wire.beginTransmission(MP3_SLAVE_ADDRESS);
      I2C_writeAnything(txMP3);
      Wire.endTransmission(true);
      EndMicros = micros();
      //Serial.print("MP3 Packet Size: "); Serial.println(sizeof(txMP3));
      //Serial.print("Sending Command To MP3: "); Serial.print(MP3File);Serial.print("   Command; "); Serial.print(txMP3.Command);Serial.print("   Time; "); Serial.print(EndMicros-StartMicros);Serial.println("uS ");
    }

... Oh, and on the slave end, I changed the numbytes to be sizeof, but as you say Nick, not even any need for that, i'm not using it on any of my other I2C slaves all running in the project (5 X MCU core system). the filename is then pulled from the I2C array in a siimilar (debugging) way as the master packs them in

    //##############################//
    // RECONSTRUCT FILENAME
    //##############################//
    String getFilename(){
      char FileName[] = {
        RXdata.File1,
        RXdata.File2,
        RXdata.File3,
        RXdata.File4,
        RXdata.File5,
        RXdata.File6,
        RXdata.File7,
        RXdata.File8,
        0x00
      };
      return FileName;

    }

    //#################################//
    //##  MASTER REQUESTING DATA     ##//
    //#################################//
    void onRequestEvent(void){
        I2C_singleWriteAnything(TXdata);
        newData = 1;
    }

    //#################################//
    //##  MASTER SENDING US DATA ##//
    //#################################//
    void onReceiveEvent(int numbytes){
      if(numbytes == sizeof RXdata){
        I2C_readAnything(RXdata);
        newData = 2;
      }
    }

body:
This part looks weird:

    void sendMP3Command(String MP3File, uint8_t Command) {
      char *TextArray[MaxMP3Name];
      MP3File.toCharArray(TextArray, MaxMP3Name);
      txMP3.Filename = TextArray;

You have made an array of 13 pointers to strings. This is not what you want. You want the file name to end up into `txMP3.Filename`.

This would be closer:

    void sendMP3Command(String MP3File, uint8_t Command) {
     MP3File.toCharArray(txMP3.Filename, MaxMP3Name);

Personally I wouldn't be using the `String` class at all, but that should be better.

---

Now:

    void onReceiveEvent(int numbytes){
      if(numbytes == 16){
        I2C_readAnything(RXdata);
        newData = 2;
      }
    }

Are you **sure** it's 16 bytes? What if you change the struct? Let the compiler do the thinking for you:

    void onReceiveEvent(int numbytes){
      if(numbytes == sizeof (RXdata)){
        I2C_readAnything(RXdata);
        newData = 2;
      }
    }

---

> How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error "invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]" (on the Slave)

This minimal example compiles OK:

    #include <Wire.h>
    #include <I2C_Anything.h>
    const uint8_t MaxMP3Name = 13;
    struct RECEIVE_DATA_STRUCTURE{
      char Filename[MaxMP3Name];
      uint8_t VolLeft;
      uint8_t VolRight;
      uint8_t Command;
    };

    volatile RECEIVE_DATA_STRUCTURE RXdata;
    volatile uint8_t newData; // flag to detect I2C activity

    void onReceiveEvent(int numbytes){
      if(numbytes == sizeof RXdata){
        I2C_readAnything(RXdata);
        newData = 2;
      }
    }

    void setup()
    {
    }

    void loop()
    {
    }


message:
SD card fails to initialize

I know this question has be asked before on this site. However it was never really answered. I have an Arduino Uno. I am trying to get it to read a 2 GB SDHC Micro SD card. The problem is, the SD card never intializes. I am not sure if there is something wrong with the wiring (which I think is NOT the issue) or the SD card/shield. I have formatted the SD card, but perhaps I did use the wrong settings to do so. Additionally, this SD card is quite old, probably several years. It can still be managed on my PC however.

I bought the following [Micro SD shield off Amazon.][1] It has the pins VCC, GND, MISO, CS, MOSI, and SCK, for which I figured the following:

    MISO = D0
    CS = D1
    MOSI = CLK
    SCK = D3

I have the circuit wired in the following way:

    SCK to Pin 10 on Arduino
    CS to Pin 11 on Arduino
    MISO to Pin 12 on Arduino
    MOSI to Pin 13 on Arduino
    VCC to 3.3V source on Arduino
    GND to Arduino Ground

The image below is a compilation of the closeup of the shield and my wiring. Not that I am also using Pin 9 in the picture. However this is used for a different portion of the circuit.

[![enter image description here][2]][2]

The code that I am trying to run comes from the SdFat library. Though the Amazon page says the device can be used without this library, I prefer to have it. I am running the `SdInfo.ino` example located in SdFat/SdFat/examples/SdInfo/. I have changed the coding so that:

    const uint8_t SD_CHIP_SELECT = 10;

I have also tried running the `Basic.ino` example in the TMRpcm library, located at: TMRpcm/examples/basic, but this doesn't work either. Below is the code:

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

    TMRpcm tmrpcm;   // create an object for use in this sketch

    void setup(){
      tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
      Serial.begin(9600);
      if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
        Serial.println("SD fail");
        return;   // don't do anything more if not
      }
      tmrpcm.play("music"); //the sound file "music" will play each time the arduino powers up, or is reset
    }

    void loop(){
      if(Serial.available()){
        if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback
          tmrpcm.play("music");
        }
      }
    }

In short. My SD card does not initialize, and I cannot seem to figure out why.

  [1]: http://www.amazon.com/dp/B015VH43WM/
  [2]: https://i.stack.imgur.com/IfhE9.jpg

body:
The first thing to try is to use the 'proper' pins for the SPI:

    SCK to Pin 10 on Arduino ---> Pin 13
    CS to Pin 11 on Arduino ---> Pin 10
    MISO to Pin 12 on Arduino ---> Pin 12
    MOSI to Pin 13 on Arduino ---> Pin 11
    VCC to 3.3V source on Arduino
    GND to Arduino Ground

Try that first and see how you get on.

----------

By the way, just thought I'd mention, probably worth just following the Adafruit example word for word as I'm guessing your board is pretty much a good fit for this tutorial:

https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial

good luck getting it rockin' ;)


body:
That breakout board includes a 3.3V regulator and level shifter.  It should be powered from 5V for proper operation.

Also, as @Andology mentions: *use the correct [SPI](http://arduino.cc/en/Reference/SPI) pins*.


body: If you have checked everything (wiring, coding your correct pin etc), AND you have already formatted the new card with the correct sd formatter and/or fat32 formatter, and it still does not work; I have found the following worked on some cards:  Simply create an empty (0 bytes) file on the new card.  Cards that were returning all kinds of funny errors (like they are too small - or simply won't initialize)  magically start working !


body:
The solution to this problem, is that you have to let digital Pin 10 as output (for the SD library to work) and put out a logic HIGH by adding “digitalWrite(10,HIGH);”. For Arduino Mega you have to do exactly the same ignore pin 53 completely though the comment asks you to change it to 53.

pinMode(10, OUTPUT); // change this to 53 if you are using arduino mega
digitalWrite(10, HIGH); // Add this line


message:
Using digital weighing scales with INA125p

Complete electronics beginner here. I'm attempting to build a weighing scale with an Arduino.

I'm attempting to follow [this tutorial][1], with the shield that they use.

[![enter image description here][2]][2]

I've arranged my load cells on the scale into a Wheatstone Bridge, and I can get some readings just by taking a voltage reading from the two cells marked V+ and V-. The board has terminals that are linked to a INA125p, and the pins should give an amplified reading.

    Pin A1:0.96
    Pin A2:1.42
    Pin A3:5.00
    Pin A4:5.00
    Pin A5:5.00

Regardless of whether I have the scale wired in or not, I get these readings from the individual pins. The scales seem to be able to take power from the Arduino shield.

The scales that I have are different from the ones in the example. From what I can figure out, the yellow cables that they reference turn their particular scale on when weight is put on it.

I've put the wires where I take the reading into the 2 and 4 terminals on the circuit board that they have (where the tutorial references a differential signal), but again, it makes no change.

> unsolder or cut the white wire that is referred to as G3 (Wheatstone bridge mass) on the original printed circuit, extend take it to terminal 1 on the new printed circuit;
>
> unsolder or cut the white wire that is referred to as G2 (Wheatstone
> bridge positive) on the original printed circuit, extend take it to
> terminal 3 on the new printed circuit;
>
> unsolder or cut the white wire that is referred to as G1 and G4 on the
> original printed circuit, extend take it to terminal 4 and 2 on the
> new printed circuit (differential signal on the Wheatstone bridge)

I've attempted lots of different combinations of cables and terminals on the new circuit, but it appears to make no difference to the readings.

My question is:
Based on the tutorial and the drawing above, am I taking the readings from the correct place? Are there any things I'm obviously doing wrong with the circuit itself?
If the circuit is correct, how would I go about trying to get correct readings from the scale when I add weight to it?

I apologise for the vague nature of this question, but I am a complete beginner trying to figure this out, and I am struggling to follow the tutorial. I'll try and provide any additional information that you need.

  [1]: http://www.open-electronics.org/wi-fi-body-scale-with-arduino/
  [2]: https://i.stack.imgur.com/TMFhq.jpg

EDIT - I have a Salter SAL-3003 SSSVDR08 scale.

Each load cell has 3 cables, Red, Black and White. The red ones are the ones marked with the V+, V- etc. On the original board, they were wired in threes.

body: Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.


message:
Multiple sensor connection help

How would you connect multiple HC-SRO4 ultrasonic sensors to one arduino uno? As of now, I have a bunch of jumper cables, 3 u.s sensors, and one arduino uno board. How would one hook up 3 sensors? A schematic would be excellent!

body:
It depends on what you want to do overall.

Using the [HC-SR04][1] works roughly like this:

 1. you generate a strobe on a pin for a minimum amount of time, and this strobe is understood by the sensor as "emit the ultrasound signal"
 2. then you somehow (more on this later) measure how much time passed between your strobe and a change of level on another pin from the sensor - this is how the sensor notifies you that there was an echo and it has returned.
 3. finally, you convert the time measured into distance, using a conversion algo (typically multiplying by a certain factor) that is specific to the sensor.

Mostly the problem revolves around point #2: how to measure the time elapsed between command (strobe) and answer (change of level).

You have various options, each with pros and cons:

 - busy looping: it's easy to implement, very straightforward and works right away. The problem is that your arduino will do just that.
 - polling: it's a less aggressive version of polling, where you check the values every now and then. It lets you do more, but the drawback is that in the worst case the line changes level right after you have checked it, so it will be noticed only at the following iteration. The period used for checking is the maximum error you will get.
 - GPIO interrupt driven: this is harder but lets your arduino do many other things, while not loosing precision (I'll detail it separately)
 - HW backed: the AVR on UNO has the ability to capture events: basically there is a timer running that will stop when it gets triggered by a certain event (ex: the change of pin level cause by the echo). It is very precise, but you are limited by the number of HW blocks available on the AVR (3 iirc).

Now about the sub-cases of the GPIO interrupt-driven solution:

 - EXT based: the ATMega328p present on the UNO has what are called external interrupt sources, which is a fancy way to say that if you configure correctly a pin, the processor will notice when the pin voltage level changes and do something about it (in your case, take a time measurement) - this is quite generic solution, but unfortunately it works only on 2 pins, so you are out of lack with your 3 sensors, unless you implement some scheme where you multiplex 2 or more sensors on only one pin.
 - Pin-change-interrupt based: on AVR most of the PINS are grouped in ports. Each port contains maximum 8 pins and is labelled with a letter (A, B, C, ..). The way this interrupt works is roughly like the EXT type, but with a catch: you will get an interrupt whenever _any_ of the pins that you have enabled on a certain port will change. In your case you could allocate only one sensor on a certain port, so that it would be obvious that if you get an interrupt for that port, it will be because of that sensor.

So now you can see why I said "it depends". If all you want to do is to get the information about proximity, you can go with busy-looping/polling.

But if you decide later on to do more on the same arduino, be aware that you might have to come back to the implementation of the ultrasonic sensor.

Finally, there is a [library][2] for this, but its implementation will fall into one of the cases i mentioned before, so be aware that the same catch applies: at some point you might want to do something that conflicts with the library.

Other points worth mentioning, that you should consider in your design (at least experiment with them):

 - orientation of the sensors: will they interfere with each other?
 - timing: do you need/want to activate them all simultaneously or do you prefer to have them activated in sequence?

  [1]: https://docs.google.com/document/d/1Y-yZnNhMYy7rwhAgyL_pfa39RsB-x2qR4vP8saG73rE/edit
  [2]: http://playground.arduino.cc/Code/NewPing


message:
Why can't I use an optocoupler to drive an AC circuit using the arduino digital pins?

So, when I searched for ways to drive AC circuits from Arduino, everyone suggested relays with a transistor switching circuit to channel an external 5V. I was wondering what would happen if I used an optocoupler like 4n35 to drive an AC circuit. Will the phototransistor inside the chip burn out?

body: No. A 4N35 will switch 150mA at 30V DC. See http://elinux.org/RPi_GPIO_Interface_Circuits for more detail. If you are proposing to switch 110/240V AC there are safety issues. You should look at available commercial modules.


body:
Normally Opto couplers like a 4N35 were not designed to drive an application load.  Typically they are used to trigger another device such as a SCR or Triac.  There is a vidio I would recommend you watch, it gives some information and the comments are good.  Give this a try:

https://www.youtube.com/watch?v=FVef6f2_Si8

Gil


body:
Use it with Triac.  I use MOC3020 + BT138 + 330 and 510 Ohm resistors.
It works good as relay and in dimmer scheme.
Scheme is here
http://cyber-place.ru/attachment.php?attachmentid=1030&d=1370462030


body: SSR's typically have a arduino friendly 3v + dc input, and can switch 10+ amps of up to 330vac.


message:
Trouble with sleep mode and interrupts

**Context**

I am building a small battery powered counting device. As with many other projects like this, saving power is critical. I am therefore trying to utilise the sleep mode wherever possible. This is using a 328P as a standalone MCU running on the 1MHz internal clock

The Hall Effect sensor I am using outputs Vcc when nothing is detected, and Ground when something is detected. It therefore seems well suited to being used as a trigger for an interrupt to wake up the 328P from sleep (so that I don't even need to use a watchdog timer.)

Below is an excerpt from my code. This code does put the processor into sleep as desired. However, from testing I have discovered that the device will not sleep when the magnet is left near the sensor, as its output stays LOW. As I only want to detect pulses of a moving piece of metal, this is wasting power. I only want to wake up when it is initially detected on each cycle.

    void sleepLoop()
    {
      Serial.print("S");

      delay(5);   //scales to 40ms

      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      noInterrupts();

      attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

      interrupts();
      sleep_cpu();

      //The program will continue from here.

      //First thing to do is disable sleep.
      sleep_disable();
    }

I therefore changed

`attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);`

to

    attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, FALLING);

**PROBLEM**

Now my processor never goes to sleep. For debugging I have put in a serial print at the start of the loop so that I know it has entered this loop of code. Whether `LOW` or `FALLING` is used the 'S' is printed. I only know it is not sleeping because I am measuring the current flow.

I thought the sensor may be going LOW long enough to keep the device awake, but not long enough to register as a count (as I have a debounce in there) so I have checked the output from the sensor with an oscilloscope in case it was momentarily going `LOW`, but I couldn't see any sign of this.

The findings from the oscilloscope make me feel like there is something about the interrupt function that I am overlooking. Any help would be greatly appreciated!

body:
There is a more radical alternative, that could yield even higher power savings: use the HAL sensor to trigger a monostable circuit that normally would keep the uC (and the clock source) powered off.

When it starts, get it to update the counter and time the monostable so that it shortly puts the rest of the system back to off.

You can use the eeprom for the counter.

For improved efficiency, get rid of the bootloader and start executing your application right away. If you program from the ISP interface, you do not need the bootloader.


body:
Only low level detect is possible with external interrupt pins (INT0/D2 and INT1/D3) in [power down sleep mode][1]. The signal must be low for a number of clock cycles to be detected and the interrupt will detected while the signal is low (and the interrupt is enabled). It is not a transition.

A pin change interrupt could be used instead.

For more details please see chap. 9.5 Power-down Mode and chap. 12. External Interrupts.

Cheers!

  [1]: http://www.atmel.com/images/doc8161.pdf


message:
Multiple shift registers, 16 bit numbers

Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's.  Below you can see schematics I am using.

[![Used topology][1]][1]
  [1]: https://i.stack.imgur.com/5X4Y1.png

The code I am using is

    int latchPin = 8;
    int clockPin = 12;
    int dataPin = 11;
    int numberToDisplay=65535;

    void setup() {
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
    }

    void loop() {

        digitalWrite(latchPin, LOW);

        shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

        digitalWrite(latchPin, HIGH);
        delay(500);
      }

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
    {
        uint8_t i;

        for (i = 0; i < 16; i++)  {
            if (bitOrder == LSBFIRST)
                digitalWrite(dataPin, !!(val & (1 << i)));
            else
                digitalWrite(dataPin, !!(val & (1 << (15 - i))));

            digitalWrite(clockPin, HIGH);
            digitalWrite(clockPin, LOW);
        }
    }

Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.

Thank you in advance

body:
notice the `uint8_t val`. You are truncating the 16-bit number back to 8 bit.

One way of fixing this is to split the 16-bit number before calling shiftOut.

    shiftOut(dataPin, clockPin, MSBFIRST, highByte(numberToDisplay));
    shiftOut(dataPin, clockPin, MSBFIRST, lowByte(numberToDisplay));


body:
I agree with Gerben. But Byte datatype will not help you, since [Byte][1] type is an unsigned 8-bit type (the same as uint8_t). Why don't you try this header:

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint16_t val)

Or follow Gerbens idea, just using out of the box [shiftOut][2] routine. It shifts 8-bit variables, so you shouldn't need to re-implement the routine.

Regards.

  [1]: https://www.arduino.cc/en/Reference/Byte
  [2]: https://www.arduino.cc/en/Reference/ShiftOut


body:
Your problem is entirely that you declare val to be uint8_t, instead of uint16_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's [your project in 123D Circuits][1]. You can simulate it in the browser and look at the code running in the Arduino there.

[![enter image description here][2]][2]

  [1]: https://123d.circuits.io/circuits/1142474
  [2]: https://i.stack.imgur.com/QxbeP.png


message:
ESP8266 returns whatever is sent through Arduino serial

I am a newbie and working on a kind of WiFi-controlled vehicle (car or maybe hovercraft later). My ESP8266 repeats the commands I send. For example, AT gives AT, AT+GWR gives AT+GWR, dabdabik gives dabdabik, etc.

I am using an Arduino Uno to send commands, as I don't have FTDI related stuff (USB to Serial Converter). I use AA cells for power supply (1.5v*2=3v). I don't even have 3.3 volt direct supply. I am using the Arduino IDE Serial Monitor. I connected the Arduino's TX to the ESP8266's RX via a voltage divider (1.66K Ohm(TX) and 1.66K Ohm (GND)->3.29 Ohm(RX)).

My connections are:

    ESP8266----------------Arduino Uno
    TX---Voltage divider---RX(d0)
    RX---------------------TX(d1)
    GND--------------------GND
    VCC-------**3V**
    CH_PD-----**3V**

Sometimes it gives garbage otherwise it just repeats (weird). Garbage ONLY changes if baud rate is changed.

I flashed it (it seems) with the AT 9.5.2 firmware. Flashing works rarely ONLY with TX to TX connected directly without a voltage divider.

I tried as much as I could after searching the web and ESP8266 forum but still couldn't solve problem.

Please help. I am a student in a small town (Manipal) in Southern India so no good stores nearby and I don't want to buy FTDI or anything online. I am a bit new to electronics, but I am a C++ programmer and student.

UPDATE: I noticed after some resets that it gives full garbage to longer commands most of the time, whereas two-letter commands give partial garbage. For example AT gives IT,TT,OT,etc.

There is no coding.
I am sending the commands directly via Arduino hardware serial pins (rx,tx) and a bare minimum program.

body: I noticed when testing my ESP8266 using the Arduino IDE serial console that ending with a `CR` repeated what was sent, a `NL` executed the command and combination of the two yielded a combination of the two behaviours. This could have just been the firmware on mine (it seemed to be non-standard), but it is possible that the behaviour is similar on yours. If you are using `CR` & `NL`, it would explain repetition. However, I can't explain commands not executing, or executing abnormally.


body:
When I recieved my first ESP I struggled for weeks trying to get it working. First, the voltage divider is a good thing for its longevity but I got it working without it.

Next about baudrate, mine sent some data at startup on 76800 baud then would work on 9600 baud. You might want to check that out for the garbage you're seeing.

Finally, it might be related to a power draw problem. The ESP has 400mA peaks, this is high for an Arduino and even for a 3.3v USB serial programmer. I had to use a 1A breadboard power supply to actually get it to work. Before buying anything you should try putting a big (220µF or more) capacitor in parallel on the 3.3V power.


body:
1. AT commands must end with '\r\n'.
2. 'ATE'commands can enable/disable echo. (ATE0: disable, ATE1: enable)
3. AT commands documentation: http://espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf


message:
Trying to understand Arduino products

**Background:**

I am new to Arduino world, and I like to buy a board. I am a bit confused how Arduino products are being sold. Coming from Raspberry world, it seems that I don't know what actually Arduino is.

**Question**:

I am trying to understand what is it that this product offers:

[![Arduino UNO R3][1]][1]

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

.

1. Why it says "**For** Arduino UNO R3"? 2. Isn't it actually an "Arduino UNO R3"? So why it says "For"?
3. What are MEGA328P and CH340? Does "Arduino UNO R3" comes with other chipsets?

body:
The board in the picture is not an official Arduino board. It is a clone.  You will note that in the picture the board does not say "Arduino"  It may be 100% compatible or it may not, you have to decide if the low price is worth it.

If you want an official board you should check either http://arduino.cc or http://arduino.org to find official distributors. (see [this question](https://arduino.stackexchange.com/questions/11824/difference-between-arduino-cc-and-arduino-org) for information about why there is both arduino.cc and arduino.org).


body:
It sounds to me like an Arduino Uno **clone**.

> Why it says "For Arduino UNO R3"?

I would read that as "For Arduino UNO R3 **projects**" (ie. Uno-compatible).

>  Isn't it actually an "Arduino UNO R3

No, it's a clone. Or not really a clone (see below) because they used different hardware. It is compatible with the Uno in most respects.

> What are MEGA328P?

That is the **main** chip on the board (actually an Atmega328P).

> and CH340?

They have saved money by using a CH340 USB-to-serial chip instead of the Atmega16U2 used on genuine Uno boards. You may need to install a different driver to make that work. I disagree with the other answer(s) that this is a separate board or chip. It is clear from the photo of the chip near the USB socket that it is a CH340 chip there. See, for example <https://hackaday.com/tag/ch340/> from which I quote:

> The cheapest USB to serial chip on the market appears to be the CH340G, available for 20-40 cents apiece from the usual retailers. There is, however, almost no English documentation, and the datasheet for the CH340 family doesn’t include this chip

They used it because it is cheap.

> Does "Arduino UNO R3" comes with other chipsets?

Yes the **genuine** one comes with an Atmega328P (main processor) and Atmega16U2 (USB interface).

---

Having said all that, the Uno is a good all-rounder starting board to get going with Arduinos.

Note that they are using the SMD (surface mounted) main processor chip. If you fry it you need to replace the whole board, not just the chip. However the entire board is quite cheap. :)


message:
How to Create a water screen with solenoid valve in arduino

I want to make a water screen. I will create character with solenoid valve. Sometimes sequential valve will pass to water, sometimes not pass.

And I will create some shape or character.

But I don't know how can I create this character with Arduino.

Do you have any good idea ? Can you help me ?

body:
You can refer to [this page][1] for the generic actuation (iow Arduino board + relays shield + power supply for the valves), but that leaves one problem open: timing.

To draw something on a wall of water, you need to make sure that the water flows with a known, constant speed (unless your wall is very tall, I would ignore the effect of gravity, if the initial speed is high enough).

Maybe it can be achieved without this extra step, but to play it safe, I'd also add a pump that feeds all the valves.

This will ensure that you will have a known pressure/speed of the water, thus being able to calculate the timing of the valves.

You can use one of the relays to control also the pump.
Notice also that most likely an arduino UNO/Nano or equivalent will not be sufficient, as you will get relatively few lines.

An ArduinoMega2560 or DUE have far more GPIOs.

  [1]: https://cmosgr.wordpress.com/2013/10/04/electric-solenoid-valve/


message:
LM35 at higher temperatures

I have a question concerning the LM35 sensor: if I'm not too concerned about accuracy (I don't mind having 2 or more degrees off), is it possible to use the LM35 sensor at higher temperatures than the normal range? The project that I'm thinking of using this sensor, temperatures should reach 200 degrees, maximum.

Thanks!

body:
No, you cannot.  The LM35 is rated for an **absolute maximum** junction temperature of 150°C.  Any higher than that and you will damage it.

For temperatures above that you are better using a thermocouple.


message:
Arduino Uno + 12 relays

I'm using a basic relay and I want to use 12 like this. Each one needs 50 milliamps, but the Arduino can supply only 300 milliamps. What can I do?

body:
You should never drive relays direct from an Arduino.  You always need a driver circuit since each OP pin can only reliably provide up to 25mA.

Every relay needs (at least) an NPN transistor and a flyback diode.  Follow the myriad of examples for controlling one relay on an Arduino and multiply it by 12.

You might like to make things smaller and more manageable by using a paur of ULN2303 chips with 6 darlington drivers in each instead of using 12 discrete transistors.


message:
Best way to make an Arduino switch 8 12V LED's

I'm trying to switch multiple 12V LED's with my arduino, based on the input of a (serial-in parallel-out) shift-register.

The 12V comes from a separate battery, so I can use 8 mosfets to get my 12V, and I might even put a parallel-in serial-out shift register in between.

But I'm hoping that there is a cleaner way of doing this.
Is there some kind of component that combines a shift register and a mosfet?

Any ideas on the best way to solve this?

body:
I would recommend using something like the [STP08DP05](http://datasheet.octopart.com/STP08DP05TTR-STMicroelectronics-datasheet-8439803.pdf).  ST Microelectronics makes 16 and 24 bit versions as well.  You can also find TI and NXP parts that will do basically the same thing.

With these parts you can hardwire your max current value with a resistor to make sure you don't overdrive the LED.  Just because you can drive the LED at 90mA, doesn't mean you should... it will probably be way to bright.  The IC's can also be daisy-chained to your shift register and you can drive very large strings of LEDs... or use them for RGB LEDs.

Hope that helps!

**EDIT - Based on Comments**

There are a couple of options.  Note the Vdd represents the voltage supply to the IC itself and the nominal operating voltage is 3.0V up to 5.5V (I'm honestly not sure why they even added 7V as a max value when they specify 5.5V on the next page).

So, Vdd is not necessarily the voltage that your LED's are driven at.  You can drive the LEDs at 12V  (if you need to) and add a series resistor to the OUT pins of the IC's to dissipate the extra heat.

You would probably be fine with 200 ohms per pin.  If you set your current at 20mA, and assuming a 2.2V drop through the LED, that would give you approximately 5.8V at the OUT pins and the IC wouldn't have to dissipate much heat in terms of power.

However, if you don't need to drive them at 12V then I wouldn't bother.  Usually the forward voltage of an LED is 1.8 to 3.3V and you don't need 12V.  However, if you are driving a lot of them then it may be easier to use the 12V.  There are always trade-offs.


message:
less expensive alternative arduino board to CMUcam4

Is there any similar (less expensive alternative) arduino board to CMUcam4?

CMUcam4:The CMUcam4 is a fully programmable embedded computer vision sensor. The main processor is the Parallax P8X32A (Propeller Chip) connected to an OmniVision 9665 CMOS camera sensor module.

body:
I have used OpenCV on Intel Galileo for doing recognition of sub images from a larger image (given the cover of a magazine, identify it in a pile of magazines partially covering it). The frame rate is far from stellar.
I haven't tried with Edison but it should be much faster, as it's an Atom core vs the pentium-like Quark. OpenCV is optimized for x86.

I used a normal webcam to capture the image, so this solution gives more flexibility in the choice of the sensor.

You could have a look at [ROS on Edison][1].

  [1]: http://wiki.ros.org/Edison


message:
Problem with structs and pointers(?) - Mega with QueueArray

I'm writing a sketch to run on a Mega that builds up an array of timestamps (using the [QueueArray library][1] and [DS3231 library][2]). I'm having a problem where a struct I'm defining and then queueing is always referring to the first in the list. The relevant bits of the code looks like this:

    #include <QueueArray.h>
    #include <DS3231.h>
    struct payload_t
    {
       unsigned long timestamp;
    }

    QueueArray <payload_t> dataQueue;
    DS3231 clock;
    RTCDateTime dt;

    void setup() {
       clock.begin();
       clock.setDateTime(__DATE__, __TIME__);
    }

    void loop() {
        payload_t dataPayload;
        dataPayload.timestamp = getTimestamp();
        dataQueue.enqueue(dataPayload);

        payload_t tempItem = dataQueue.dequeue();

        /**
         * At this stage, the dataPayload.timestamp is correct,
         * but tempItem.timestamp will always show the value from
         * the first item in the queue
         */

        sleep(1000);
    }

    unsigned long getTimestamp()
    {
        RTCDateTime dt = clock.getDateTime();
        return dt.unixtime;
    }

As per the comment in the main() loop, the first time a packet is added to the queue, the timestamp matches. For subsequent items, the value retrieved from the queue always gives the timestamp from the first item in the queue.

I feel this is my C knowledge letting me down with something basic, but can anyone point me in the right direction?

  [1]: http://playground.arduino.cc/Code/QueueArray
  [2]: https://github.com/rodan/ds3231

body:
It's not your C knowlede letting you down, it's just that you haven't gotten used yet to the weirdness of the arduino ide/compiler.

You do not need to create a main() function.

You need to create a loop() function.

main() is already defined and calls loop() in a loop.

Check any other sketch and you'll notice that it usually defines setup() and loop(), almost never main().

You must put in the setup function all the code that needs to be executed once (settings and initializations) and in the loop() function whatever needs to be executed iteratively.

Also, leave declarations out of loop() unless you want such variables to have scope (and life) limited to only one round of loop()


message:
Arduino Uno and I2C

How does the arduino uno talk with i2c? i saw the circuit and it use analog input pins but as far as i know you cant use them as output. How does he send data over those pins?

body: Most pins on the Arduino are multi-function and can be switched into different modes. Analog is just one of those modes. I2C is one of the available modes for the pins that A4 and A5 are connected to.


message:
SoftwareSerial with ESP8266

I am communicating with ESP8266 using SoftwareSerial of Arduino UNO. I can successfully send AT commands and get response when communicating through the terminal. But if i **programmatically** send particular AT commands there is no response.
For eg:
I type AT in serial monitor I get OK
But if i send the following through SoftwareSerial pins

<!-- language: c -->

    mySerial.println("AT");

there is no response.

Can anyone tell what will be the solution as to how to send AT commands explicitly.

The sketch is

<!-- language: c -->

    #include<SoftWareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

    void setup() {
    // Open serial communications and wait for port to open:
      Serial.begin(9600);
      mySerial.begin(9600);
      mySerial.println("AT");
      delay(100);
      while (mySerial.available()>0 ) {
        char ch=mySerial.read();
        data.concat(ch);
        if(ch=='\n')
          Serial.println(data);
        data="";
      }
    }//setup

    void loop()  {
      while (mySerial.available()>0 ) {
        char ch=mySerial.read();
        data.concat(ch);
        if(ch=='\n')
          Serial.println(data);
        data="";
      }
      while (Serial.available()>0 ) {
        mySerial.write(Serial.read());
        delay(100);
      }
    }//loop

I am using Sparkfun Level Shifter to get 3.3V from 5V. The wiring is straightforward. ESP8266 Vcc and CH_PD to 3.3V; GND to GND; Tx to Arduino 2(Rx) directly; Rx to Sparkfun 3.3V RXO LV side and Arduino 3(Tx) to RXI HV side) so that when Arduino transmits it gets stepped down to 3.3V and ESP8266 receives it. The wiring should be correct as it is working perfectly when AT commands are sent manually.

I tried everything of sending mySerial.write("AT/r/n"), mySerial.print("AT") mySerial.print("\r\n"), etc but nothing seems to work.

Is it that there is some problem with SoftwareSerial. But then how is it working if i send AT commands manually through terminal ?

body:
I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.

If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.

I found, for example, that the `AT+CWJAP` (join access point) command takes quite a while, like 10 seconds or so.

Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.

If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. `OK`, `ERROR` etc.).


body:
Did you make sure that your lines end with \n\r?

Remember you need both newline characters to send over the line from the terminal.


body:
Same problem here with this code.

Three step for me to make it work :

* Use method write() and not println()
* Send newline \n when talking to esp8266
* don't wait newline to print the response

        esp8266Serial.write("AT\n");
        delay(100);
        while (esp8266Serial.available() > 0 ) {
          char ch = esp8266Serial.read();
          Serial.println(ch);
        }

I hope it helps


body:
It appears to me that when the ESP8266 sends a few characters to the Arduino, the initial version of the code always erases those characters (`data="";`) without ever printing anything to your serial monitor.
So there is no way to tell whether the ESP8266 is sending anything or not.

To make it easier to debug, try printing *every* character from the ESP8266 to the serial monitor, whether or not it makes a complete message.

What do you see on the serial monitor with the following code?

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

    String data = "";

    void setup(){
    // Open serial communications and wait for port to open:
      Serial.begin(9600);
      mySerial.begin(9600);
      mySerial.println("AT");
    }//setup

    void loop(){
      if( mySerial.available()>0 ){
        char ch=mySerial.read();
        data.concat(ch);
        Serial.print((int)ch, HEX); // debug: print *every* character, in hex.
        if( ch=='\n' ){
          Serial.println();
          // Use "F()" macro as recommended by
          // https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram .
          Serial.print(F("complete message:"));
          Serial.println(data);
          data="";
          Serial.print(F("waiting for next message ..."));
          }
      }
      if( Serial.available()>0 ){
        mySerial.write(Serial.read());
      }
    }//loop


message:
Arduino Wire.onReceive(handler)

It says in the description of the function:

> Registers a function to be called when a slave device receives a transmission from a master.

So when does it exactly called? I guess it's not been called for each byte, but its the meaning of receiving transmission from the master. Does it called for each byte? When the master use transmissionBegin? transmissionEnd?

body: It is called at the end of the reception of the entire packet - i.e., when the slave receives the final `STOP` bit.  It is passed the number of bytes received (which is the number of bytes you requested since I2C has no way of being able to work out if it is actually receiving real data - see [here](http://www.gammon.com.au/forum/?id=10896&reply=10#reply10)) as the only parameter so you know how many bytes you can then read from the internal buffer without overflowing it.


message:
How to add more inputs on Arduino?

I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?

If it makes any difference, the max number of buttons that can be pressed at once is 10.

body:
There is a whole concept you need to learn:

# Matrix

By using a matrix arrangement you can, using (8 + 9 = ) 17 IO pins you can create a grid of 8 × 9 buttons, which is 72 buttons.

This method is used all the time for keypads, and you can read more here: http://playground.arduino.cc/Main/KeypadTutorial

To further reduce the number of IO pins used you can replace the 8 IO pins for one dimension of the matrix with a 3-to-8 decoder, since only one pin is ever active at a time.  That reduces it down to just 12 IO pins for the whole shebang.


body:
There are quite a few GPIO expanders available that you could use to increase IO lines in your circuit, mostly running off I2C. Just search "I2C GPIO" on your favorite electronics site/google/ebay

Examples:
https://www.sparkfun.com/products/8130
[No affiliation]

If every sensed key has to be on a GPIO, then this is the way to go.

Having said that, with IO expanders, you will find that sensing large number of keys still takes lots of code on your uC. With some extra software effort, you could eliminate expanders, and rather scan a key matrix as suggested by Majenko


message:
DC motor kickback diode?

I have the following circuit: [![Arduino circuit][1]][1]

And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit: [![Circuit][2]][2]

Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.

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

body:
While the motor is being powered the current flows from Vcc to GND as in this circuit:

[![enter image description here][1]][1]

When the power is disconnected (such as the transistor in the ground connection in your circuit is switched off) amongst other things (including the collapsing of magnetic fields) the spinning of the motor turns it into a generator.  The power generated is the opposite of what was being provided to make it move.  As the magnetic field of the coils collapses additional high voltages are also generated.

When disconnected the motor can be represented as a battery connected backwards.  In that configuration the current flows from the + of this hypothetical battery through the diode into the - thus stopping any current from going elsewhere, as in this circuit:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/QULAI.png
  [2]: https://i.stack.imgur.com/1Rjim.png


message:
How to use Infra Red (IR) to reset arduino board

I am a big noob I know that

but can this code be used to reset arduino board (instead of pressing the usual reset button on the board)

I want to reset the board as If am pressing the reset button using IR

    int receiverpin = 2; // pin 1 of IR receiver to Arduino digital pin 2
    #include <IRremote.h>
    IRrecv irrecv(receiverpin); // create instance of irrecv
    decode_results results;
    void setup()
    {
    irrecv.enableIRIn(); // start the receiver
    }
    void(* resetFunc) (void) = 0; //declare reset function @ address 0

    void loop()
    {
     if (irrecv.decode(&results)) // have we received an IR signal?
    {
    if(results.value == 0x2FD847B) //if the button press equals the hex
    {
      resetFunc();
    }
    {
    irrecv.resume(); // receive the next value
    }
    }
    }

body:
Kind of, yes.  That doesn't actually reset the Arduino, it just sends the program to address 0.

There are two other ways of performing the reset that do a proper full reset:

1. Enable the watchdog timer and let it time out to reset the CPU.
2. Connect an IO pin to the RESET pin - keep it in INPUT most of the time but set it to OUTPUT and LOW when you want to reset.

By just jumping to address 0 you aren't resetting the internal peripherals and registers to their reset state, so things like timers and such will still be running when they shouldn't be, etc.  It's better by far to do a real reset instead of just jumping to 0 like that.


message:
Verifying the timing between relay activations

I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on [counting milliseconds][1]. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.

So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.

Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.

An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.

I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

body:
You could use [sigrok][1] with one of the many [supported devices][2].
For example, you can find on ebay an [8 channell 24MHz probe][3] for less than $10.

It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.

  [1]: http://sigrok.org
  [2]: http://sigrok.org/wiki/Supported_hardware
  [3]: http://sigrok.org/wiki/MCU123_USBee_AX_Pro_clone


message:
Using TMRpcm library, the audio does not play

I'm using the https://github.com/TMRh20/TMRpcm/wiki library to play wav files from an SD card to a speaker I have attached to my Arduino.

I have run separate tests/programs that ensures:

1. my speaker is connected properly and can play sound
2. my SD file is connected properly as it can read and files, text files.

However, I'm trying to use the `tmrpcm.play("example.wav")` command and nothing is happening. I used wav files that for sure works (from a demo I found online) so it's not the wav file problem.

Anyone have any clue on what is going on and how I can fix this?

body:
This is now 5 months later - but I recently had the same problem.

Because the TMRpcm library plays through pulse width modulation, make sure your speakers are hooked up to a PWM capable pin.

That caused me no end of headaches trying to figure out.


message:
Compilling error not highlighting line in code

A newbe here. How come when I compile with an error I do not get the line or line number highlighted? I Get the errors just can't find where they are.

body:
The line in error can often be highlighted, however because of the way the IDE plays with your source file this is not always the case.

See my post about [How the IDE organizes things](https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them).

The IDE adds extra lines to your source, and then tries to hide that with #line directives. This can confuse the way error messages are handled. It is another example of the "helpful" IDE not always being helpful.

In any event, as Igor said, you can look for the line number in the error message and use that to find the error. Failing that, look at the quoted source code and search for that.


message:
Arduino communicate between 2 different router in different location

I am on my final year project in I.T. my project is that i want to create a helicopter or quadcopter with a camera attached to it. And i want to control the copter via wifi from an android phone in another location. e.g, the copter is at home and i am somewhere else (work, university etc..). so i wanted to know if i can connect both via 2 different routers and control it and get the live video the camera is actually recording (the idea is to monitor your house when you are away). if that is possible, which arduino hardware will enable me to do that.
Thank you.

body:
It's not the Arduino that has anything to do with this but the routing, port forwarding and/or VPN that you set up between your routers.

I'd have thought, since you're in your final year of IT, you'd at least have some rudimentary knowledge of routing, port forwarding and VPNs...