message:
ATmega328P and other chip sharing clock

I am moving my Arduino project to another platform, operating at 3.3V. (5V from USB not useable due to some 3.3V-only chips in the design) Having read about this it seems that 12MHz is a good speed to use, and my stock USB to UART converter, CH340G does call for a 12MHz crystal.

Now what is the best way to share this 12MHz clock between CH340 and ATmega328P, eliminating an extra crystal? Can I tap off XO pin from CH340 with crystal attached, and carry it to the XTAL1 pin of the ATmega?

---

## EDIT

---

If sharing clock requires some fine tuning, what about building a reference clock out of `74LVC1G04` and `74LVC1G06` chips and clock both chips from this?

body:
Sharing a crystal between multiple devices is a very bad idea. The crystal is only a piece of the oscillator, the rest of it being a small bit of circuitry within the IC itself. Having multiple ICs connected to the same crystal will cause them to fight over who is driving it.

The datasheet for the CH340T/R, which I was able to find in English, says the following:

> When CH340 chip is working normally, the outside must supply 12MHz clock signal to XI pin.

This seems to imply that you can feed an external 12MHz clock into the chip and it will work. So we take the clock from the '328P and pass it to the '340G.

Programming the CKOUT fuse on the '328P will cause the internal clock to be output on CLKO, which we then connect to XI of the '340G. This means that that you will lose PB0/D8, but no longer need a second crystal. This also means that you will be unable to use the prescaler since doing so will affect the clock output.


sender: user

sender: assistant

body:
Often is is possible. The range of the crystals signals' max swing are small. Where the XI pin needs to accept these small AC signal. Hence on the FUSE on the ATmega. Which also enables the XO as a Hard clamp to excite the crystal. The crystal dominates the voltage making it small. Additionally, it is important to have the proper parallel capacitance on both the input and output of the crystal. When the XO(0) is tied to the XI(1) along with the crystal and its parallel capacitor, noting that it is in the range of 10-40pf, the total parallel capacitance will be significantly increased. Where it may be possible to reduce the XO(0)'s parallel capacitor, if XI(1) does not add too much.

Anyone attempting this should really inspect the signal on an Oscilloscope to ensure the nature of the wave form is stable and stress its tolerances. Likely by changing the parallel capacitors to find the min and max's before failure. And varying VCC of both chips across is allowed ranges. As to determine the ranges is not unacceptable.

That said the datasheets refer to a version with a suffix T that have an CKO or Clock output on pin 1. That would be best and change the ATmega's FUSE for TTL input. Where Ignacio's answer is very valid and stable. Just the opposite direction.

----------

I would point out that you will have the issue that 12MgHz is not a typically supported F_CPU speed in the code. I have toy'ed with changing the speed in the past, as to do just what you are attempting here, but with a different clock source. And found it requiring so many changes to the Arduino libraries, which are typically #IF'ed to either 8 or 16 so many places not using a nice formula, it was not worth its cost savings versus cost in maintenance. As a starter you may want to refer to [SE: "Arduino at 11.0592MHz"](https://stackoverflow.com/questions/20868853/arduino-at-11-0592mhz-modify-timer0-delaymicroseconds).


message:
Serial: active low or active high?

When I use the Mega 2560 additional serial ports, I realize that it is active low, active high. I know that TTL is active high and the serial port is obviously stated in arduino serial port page.
I also found out that the receive pin flashed (put an LED) when I typed in to the serial monitor. Is this a mistake or problem?

body:
The Serial Class of the Arduino uses Typical usage of the Serial Ports is the USART in Async mode. Which is hard coded to IDLE state of HIGH or 1 or VCC.

![enter image description here][1]

http://midas.psi.ch/mscb/hardware/bits.gif
(picture wont add - so here is a link to it)

If you need to drive the TTL inverted from its traditional values, the Serial Class can not do this. However, you can use the SoftwareSerial Class and enable the inversion in the constructor

    SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

As for why would someone want to invert the TTL UART. In some cases it is possible to drive RS232 directly. As RS232 converters inverts the TTL to +12V/-12V. 5V = -12V and 0V = +12V. So depending upon the RS232 receiver, it may actually trip its TTL output  at 2.5V and not 0V. If so then using the SoftwareSerial Class with inverse logic may drive the RS232 input of another device, without requiring a RS232 transmitter on the Arduino's TXout pin.

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


message:
Leonardo with xbee shield?

I'm trying to get a XBEE shield to operate on an Arduino Leonardo. Usually i use the AltSerialLibrary to emulate an extra serial for the xbee. However since the Leonardo comes with two sets of serial, i figured I use that instead.

    //#include <AltSoftSerial.h>

    //AltSoftSerial XBee(5,13); // RX, TX

    void setup() {

      Serial1.begin(9600);
      Serial.begin(9600);

    }

    void loop() {

      Serial.println("Odds");
      Serial1.println("Ends");

      delay(1000);

    }

The code above aims to write values to both the serial monitor (serial) and xbee (serial1). However in the Xbee's XCTU program, the remote xbee does not recieve any data.

Any feedback on how I might fix this will be appreciated.

body:
You said you are using a Xbee shield.  What shield is it, and what pins does it use for Serial communications?

If you were using software to emulate the second serial port on other arduinos, you were probably using different pins, and so if the shield is designed to communicate over (as an example) pins 2 and 3 then it will most likely not work with pin 0 and 1 without moving jumpers or switches.  For example, this
Xbee Shield: http://core-electronics.com.au/xbee-shield.html/?acc=9f61408e3afb633e50cdf1b20de6f466 has a switch to switch between pins 0 and 1 and pins 2 and 3.

You could also try some code that reads from Serial and prints the data to Serial1 and visa versa.  This means you can experiment to get a greater understanding of the problem.


message:
Temperature sensors TMP36 and LM35 have temperature diff. (offset) in the same circuit

I am trying to use the two temperature sensors TMP36 (from Sparkfun Inventor's kit) and KEYES LM35.

In read TMP36 Sensor and I convert the result to Celsius using the following code:

    // TMP36 input sensor -> degrees Celsius calculation
    TM36reading = analogRead(TM36sensor);
    TM36voltage = (TM36reading/1024.0)*5.0;
    //converting from 10mv per degree with 500 mV offset
    //             (TMP36 voltage - 500mV) times 100)
    TM36degreesC = (TM36voltage - 0.5) * 100;

In read LM35 Sensor and I convert the result to Celsius using the following code:

    // LM35 input sensor -> degrees Celsius calculation
    LM35reading=analogRead(LM35sensor);    // reads the LM35 output
    LM35voltage = (LM35reading/1024.0)*5.0;
    LM35degreesC=LM35voltage*100.0;

I have connected also a LCD display to monitor visually the values of these two sensors. Here is my [full code](http://pastebin.com/0W7hn9rg). I use also a serial log. Here is a sample from this serial log (as you can see there is a difference/offset between 0.5 to 0.9 Celsius).

    TM36: 17.38, LM35: 16.60 diff -> 0.78
    TM36: 16.89, LM35: 16.11 diff -> 0.78
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 17.87, LM35: 16.60 diff -> 1.27
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 16.89, LM35: 17.09 diff -> 0.20
    TM36: 17.38, LM35: 17.09 diff -> 0.29
    mean difference between sensors: 0.48
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 17.38, LM35: 16.60 diff -> 0.78
    TM36: 16.41, LM35: 17.58 diff -> 1.17
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 16.89, LM35: 17.09 diff -> 0.20
    mean difference between sensors: 0.71
    TM36: 17.38, LM35: 16.60 diff -> 0.78
    TM36: 16.89, LM35: 16.60 diff -> 0.29
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 17.38, LM35: 16.60 diff -> 0.78
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 17.38, LM35: 16.11 diff -> 1.27
    TM36: 17.38, LM35: 17.09 diff -> 0.29
    TM36: 16.89, LM35: 16.11 diff -> 0.78
    mean difference between sensors: 0.93

I power the Arduino from the computer using the USB cable. When the computer is ON we have the offset that I already demonstrated above. When the computer is turned off (after computer shutdown), immediately the sensor of TMP36 falls around 1 Celsius.. And then both sensors have similar temperature.
![Arduino powered by USB and Computer ON versus Computer off (LM35 and TMP36 temperature sensors)][1]

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

Why there is this temperature difference between TMP36 and LM35 sensors? How can we "fine tune" these sensors to monitor the real temperature?

body: There are many things, first different sensors have different accuracy or they may not have been calibrated from the factory. In addition both are analog and analog reading is susceptible to noise. My guess is there is a high frequency noise on power line coming from the computer interfering with your readings. Try putting a small (100nF) capacitor between AREF and GND pin. You can always just take median of the measured values as the actual temperature.


body:
The sensors have different accuracy, according to their datasheets.
The [TMP36][1] has **±2°C typical accuracy**, while the the [LM35][2] has **0.5°C typical accuracy** (over 25°C).
Read the datasheet carefully and pay attention to the characteristics, more specifically to the accuracy error graphs for each sensor. At your measured temperature (~17°C), you should expect the following error (the red line is not super accurate, but should give a general clue):

**LM35:**

![LM35 Accuracy Error characteristics as per datasheet][3]

**TMP36:**

![TMP36 Accuracy Error characteristics as per datasheet][4]

In addition, as **Michal** stated, you might have noise in your circuit, and you are not connecting the TMP36 as per the datasheet suggests (note the capacitor between +V and Ground):

![TMP36 typical application as per datasheet][5]

  [1]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Temp/TMP35_36_37.pdf
  [2]: http://www.biltek.tubitak.gov.tr/gelisim/elektronik/dosyalar/5/LM35.pdf
  [3]: https://i.stack.imgur.com/yt0rY.png
  [4]: https://i.stack.imgur.com/bzWWw.png
  [5]: https://i.stack.imgur.com/EzVTX.png


message:
ov7670 + Sd Card + arduino

I have three devices for making a motion activated security camera system:

 - this is the camera : [LINK][1]  OV 7670
 - this is the SD Card module: [LINK][2]
 - and a basic motion Sensor: PIR with 3 pin

I have an Arduino UNO and an Arduino Mega 2560.

I can connect the SD card and sensor, they work fine but I cannot connect the camera as there are not enough pins for it on UNO.

Is there a chance to connect all of them without any additional device?

I saw some working project with additional device (arducam) but I do not have much money to spend on this project.

  [1]: http://urun.gittigidiyor.com/ev-elektronigi/arduino-pic-kamera-modulu-ov7660-134509055
  [2]: http://urun.gittigidiyor.com/ev-elektronigi/arduino-sd-kart-modulu-140174113?opi=132220334
  [3]: http://urun.gittigidiyor.com/ev-elektronigi/arduino-pir-hareket-sensoru-modul-133785936?gclid=Cj0KEQiAwuSkBRC7qKq8rr7796sBEiQA5VnSuAeEeBgQs1334hhhFmA0k5d8q4aOPJ2APXnMjBOwptUaAsK48P8HAQ&mpch=ads&scxid=14489-145818-2357-0

body:
This camera module requires the use of additional hardware, as the camera and Arduino operating frequencies differ, which can result in loss of synchronization and changes to the image, and other connection problems.

Thus, we must use an integrated circuit intermediary, making the connection between the camera and the Arduino. The function of this chip is to receive the camera information, store them and then send them to the Arduino using the digital doors, much faster than if we used the serial communication.

An example of an integrated circuit that could be used is AL422, suitable for treating a video signal, which also is embedded in **some** OV7670 modules.

Looking like the connection pins behave in 7670, your module should be equal to it. So spare pins to be able to make other necessary connections.

![7670 with AL422 pin][1]

Would better check the connection through the datasheets:

[7670 datasheet][2]

[AL422 datasheet][3]

[An example of project][4]

But to answer your question; You'll need to purchase a piece more if you don't have AL442.

Regards,

  [1]: https://i.stack.imgur.com/c40y9.jpg
  [2]: https://www.openimpulse.com/blog/document-viewer/?pdf_file=OV7670-CMOS-VGA-Camera-Datasheet.pdf
  [3]: https://www.openimpulse.com/blog/document-viewer/?pdf_file=AL422-FIFO-Datasheet.pdf
  [4]: http://nicolasfley.fast-page.org/?page_id=35


message:
Read all Digital input in arduino once time and sent theme to serial

i need to read all Read all Digital input in arduino once time; example:

    Serial.write(digitalRead(0),digitalRead(1),...,digitalRead(13));

to receive state of all digital pin in one times from my app build with delphi

body:
According to the pin mapping, D0-D13 and A0-A5 are mapped to ports B, C, and D. So simply read the raw ports as bytes, send the values, and decode them on the other side.

    Serial.write(PINB);
    Serial.write(PINC);
    Serial.write(PIND);

Note that A6 and A7 (on boards that have them) are not mapped to digital pins and so cannot be read in this way.


body:
    void setup()
    {
      Serial.begin(115200);
    }

    void loop()
    {
      Serial.print("<");
      for (int p = 0; p < 14; p++)
      {
        Serial.print(digitalRead(p));
      }
      Serial.println(">");
    }


message:
IDE support for Arduino micro

I have an Arduino micro http://arduino.cc/en/Main/arduinoBoardMicro I was looking to know which is the lowest version of the IDE that support it. Actually on the IDE 0023 is not present in `Tools > Board`.

body:
According to the [Arduino Software Release Notes][1], support for the Arduino Micro was added in 1.0.2.

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


message:
Program got so many errors about expected ) or ; before either

This is my first time to try program arduino, and I am clueless. I have a friend who told me about things work, and he told me the programming language is C (or similar to C) which we have learned in our class. I just program as my friend examples, but it doesn't work and return error codes about expected ; before ( or ) before ; etc.

I'm not sure why this wont work. This is the hardware (simulated) I going to make.
     ![hw-planned][1]

here's the code:

    #define dw 8; //buttons down
    #define ri 9; //buttons right
    #define le 10; //buttons left
    #define up 11; //buttons up
    #define ok 12; //buttons ok
    #define mn 13; //buttons menu
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(6,5,4,3,2,1);
    int i=0;
    char input[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    void setup()
    {
      pinMode(dw, INPUT);
      pinMode(ri, INPUT);
      pinMode(le, INPUT);
      pinMode(up, INPUT);
      pinMode(ok, INPUT);
      pinMode(mn, INPUT);
    }
    void intext()
    {
      int c=0, lim=16;
      for(i=0;i<lim;)
      {
        lcd.setCursor(c,1);
        input[i]=97;
        if(dw=HIGH)
        {
          if(input[i]>122)
            input[i]=97;
          input[i]=input[i]+1;
          lcd.print(input[i]);
        }
        if(up=HIGH)
        {
          if(input[i]>97)
            input[i]=122;
          input[i]=input[i]-1;
          lcd.print(input[i]);
        }
        if(ri=HIGH)
        {
          c=c+1;
          lcd.setCursor(c,1);
          lcd.print(input[i]);
        }
        if(le=HIGH)
        {
          c=c-1;
          lcd.setCursor(c,1);
          lcd.print(input[i]);
        }
        if(ok=HIGH)
        {
          lim=i+1;
        }
      }
    }

    void loop()
    {
      lcd.begin(16,2);
      lcd.setCursor(0,0);
      lcd.print("Masukan kata:");
      intext();
    }

I have no idea why it wouldn't work. I'm sorry if I'm too stupid to understand.
Thank you!

Edit: oh yeah, the errors, here:

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.
    Arduino: 1.0.6 (Windows NT (unknown)), Board: "Arduino Uno"
    programyuhu.ino: In function 'void setup()':
    programyuhu:14: error: expected `)' before ';' token
    programyuhu:14: error: expected primary-expression before ',' token
    programyuhu:14: error: expected `;' before ')' token
    programyuhu:15: error: expected `)' before ';' token
    programyuhu:15: error: expected primary-expression before ',' token
    programyuhu:15: error: expected `;' before ')' token
    programyuhu:16: error: expected `)' before ';' token
    programyuhu:16: error: expected primary-expression before ',' token
    programyuhu:16: error: expected `;' before ')' token
    programyuhu:17: error: expected `)' before ';' token
    programyuhu:17: error: expected primary-expression before ',' token
    programyuhu:17: error: expected `;' before ')' token
    programyuhu:18: error: expected `)' before ';' token
    programyuhu:18: error: expected primary-expression before ',' token
    programyuhu:18: error: expected `;' before ')' token
    programyuhu:19: error: expected `)' before ';' token
    programyuhu:19: error: expected primary-expression before ',' token
    programyuhu:19: error: expected `;' before ')' token
    programyuhu.ino: In function 'void intext()':
    programyuhu:28: error: expected `)' before ';' token
    programyuhu:28: error: expected primary-expression before '=' token
    programyuhu:28: error: expected `;' before ')' token
    programyuhu:35: error: expected `)' before ';' token
    programyuhu:35: error: expected primary-expression before '=' token
    programyuhu:35: error: expected `;' before ')' token
    programyuhu:42: error: expected `)' before ';' token
    programyuhu:42: error: expected primary-expression before '=' token
    programyuhu:42: error: expected `;' before ')' token
    programyuhu:48: error: expected `)' before ';' token
    programyuhu:48: error: expected primary-expression before '=' token
    programyuhu:48: error: expected `;' before ')' token
    programyuhu:54: error: expected `)' before ';' token
    programyuhu:54: error: expected primary-expression before '=' token
    programyuhu:54: error: expected `;' before ')' token

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

body:
Here's the first line of your code:

>     #define dw 8; //buttons down

Here's the first error line:

>     pinMode(dw, INPUT);

Let's put them together and see what we get:

    pinMode(8; //buttons down, INPUT);

That's not valid C++. Using the output I've shown you, modify the input until it looks correct. And then keep doing it until the code compiles.


body:
The errors are in your `#define` statements.

These should not have `;` as they are not executable statements


body:
In C and in C++, `#define` is not an instruction of the language, but a directive of the **pre-processor**.

What it does is define a "macro" which will be replaced everywhere it appears later on in the source file.

For instance:

    #define DUMMY 152

    int x = x + DUMMY;
    myfunction(DUMMY);

will be changed, before compilation, into:

    int x = x + 152;
    myfuntion(152);

In the example above, `DUMMY` is replaced everywhere by what follows it in the  `#define` line, i.e. 152.

As pre-processor directive is not an instruction, it shall not be ended by `;`. If you add `;` at the end of a `#define`, then it will be part of the replacement:

    #define DUMMY 152;

    int x = x + 152;;
    myfuntion(152;);

As you can see now, `DUMMY` is replaced by `152;`, not just `152`.

So the solution in you example is to remove all `;` that are at the end of `#define` lines:

    //buttons down
    #define dw 8
    //buttons right
    #define ri 9
    //buttons left
    #define le 10
    //buttons up
    #define up 11
    //buttons ok
    #define ok 12
    //buttons menu
    #define mn 13

Note that comments should also be removed from the `#define` otherwise they would also appear everywhere the replacements are done.


message:
Raspberry Pi with Arduino, Serial connection stops working

This is the hardware set-up at home,

Raspberry Pi GPIO -> Logic Level Converter -> Arduino -> Multiple Relays

![enter image description here][1]

I am running Raspbian and NodeJS on the Pi while the Arduino is loaded with StandardFirmata.
I connect NodeJS to the Arduino with the `johnny-five` package and it works well after it's started. But after extended periods, a few hours? The Arduino stops responding. Whatever command that I send to the Arduino won't be acted on. It's as though as the Arduino hung.
Both the Raspberry Pi and Arduino are being powered indenpendently with a 1A Nokia USB Adapter.

Does anyone know why this is happening?

1. [johnny-five][2]
2. [StandardFirmata][3]
3. [NodeJS Server Code][4]

  [1]: https://i.stack.imgur.com/J8Ja4.png
  [2]: https://github.com/rwaldron/johnny-five
  [3]: https://github.com/firmata/arduino/blob/master/examples/StandardFirmata/StandardFirmata.ino
  [4]: https://gist.github.com/zanechua/f52a3d72946d7214f7cc

body:
If none of the code is yours, and all code from the Firmata library, then the most possible cause that comes to mind after reviewing the library code is memory leak, which makes the next allocation to fail and by thus breaking the code.

The Firmata library does perform dynamic memory allocation, checkout Firmata.c, so it is realistic - I would suggest to take it with the Library's author.


message:
control a jack/cylinder to open/close a window

I want to open the window to let the cat enter or go out, but the mecanism of the window may me think that the best way should be to use a jack/cylinder (I don't know what term is more appropriate in english for that) to open and close the door.

I will use rfid or another wireless think to know it the cat is in the place and then open the wondow but I want to close the window and let the wndow close event if there is little bit of wind, so I need domething robust.

Do you know a good hardware with (this would be the best) piece of code that can help me for that?

Thanks in advance

body:
Check out [this instructable][1] - for opening a window for a cat :)
The guy used a servo, [Towerpro MG995][2] with 10 kg torque for opening/closing the window, and a 10cm distance sensor for sensing the cat (he used [Pololu Carrier with Sharp GP2Y0D810Z0F Digital Distance Sensor][3], but I believe that any proximity sensor will do).

This is a pictrure of the mechanism, seems quite robust:
![enter image description here][4]

  [1]: http://www.instructables.com/id/Arduino-controlled-window-for-cat/
  [2]: http://www.servodatabase.com/servo/towerpro/mg995
  [3]: http://www.pololu.com/product/1134
  [4]: https://i.stack.imgur.com/RT0EL.jpg


message:
avrdude: stk500v2_ReceiveMessage(): timeout with ADDAC VCC

I am getting the above error message uploading the ADDAC VCC, and the only thing that's changed I think is the patch is bigger.

Is there a fix for this or will I have to send it back? Hope my formatting is OK

    Binary sketch size: 12,330 bytes (of a 258,048 byte maximum)
    /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cwiring -P/dev/ttyUSB0 -b115200 -D -Uflash:w:/tmp/build953252908946386724.tmp/comps.cpp.hex:i
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

    avrdude: Version 6.0.1, compiled on Oct 21 2013 at 17:07:18
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
             User configuration file is "/home/luke/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : wiring
             Overriding Baud Rate          : 115200
    avrdude: wiring_open(): releasing DTR/RTS
    avrdude: wiring_open(): asserting DTR/RTS
    avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer

    avrdude done.  Thank you.

    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

body:
Your log is showing that communication is failing right away (avrdude never gets a proper response). This can mean that

 1. the VCC is not resetting
 2. there is no bootloader installed
 3. there is some other defect

You can test case is by manually hitting the reset switch around the time that avrdude starts. If the necessary pins are available, you can exclude case 2 by installing a new boot loader with a programmer, which also tests scenario 3 a bit.


message:
Is there a radar - like sensor that can tell me the distances of multiple things around the sensor?

I'm trying to develop something that requires accurate distance measurement of objects around the center of the contraption. However, I cannot find any way to achieve this other than using a bunch of infrared distance sensors. Really, I'm looking for something that costs at most $200 and is compatible either with arduino, PC, or raspberry pi.

This may not be the place for this, if not, please inform me.

Thanks in advance!

body: What you're looking for is called **lidar** - but it's not cheap. RPLIDAR is the current price leader for non-hacky solutions, and I haven't seen it for much less than $400 anywhere.


message:
Can an Arduino Micro receive commands from another microcontroller when hardwired together?

I plan to build functioning reaction wheels, controlled by an Arduino Micro. Ideally, I'd like to have the reaction wheels, and the micro, be a single unit which would receive external commands from another microcontroller.

I know you can link Arduino microcontrollers, and every time I've seen it done it has been with a RC module such as XBee. Is it possible to link units using something like the micro-usb on the Arduino Micro?

If this is possible, is it as simple as connecting the micro-usb ports on my microcontrollers, and then working out the programming?

body: Usually the RF links (xbee included) just replace a set of wires connecting two serial ports. You can very easily connect the serial ports on two arduino's and communicate between them without any special hardware in between. You will only need 4 wires (power, ground, transmit, receive).


body: You cannot do this with the micro USB ports.  You will need to use I/O pins.  Either serial or I2C would be good options.  It might be advisable to use I2C if you want to control multiple 'slave' microcontrollers as they can all sit on the same bus.  Using the serial port would require multiple transmit and receive pins on the master controller, likely requiring software serial ports (high overhead).  Also, if you don't use the serial port for comms, then you can use it for debugging.


body:
It might be worth explaining WHY you can't "just connect the micro-usb ports". There are two issues here:

 1. USB is not symmetric, and an Arduino micro is only designed to act as a client. One of your microcontrollers would need to have USB OTG support to act as a host.
 2. Even though there are microcontrollers that do have USB OTG support, you'd still have a nontrivial hurdle writing the software for them (Pretty sure the Arduino USB code is client specific as well, though I'm not familiar with the details of the serial over USB protocol).

In short, your basic idea is not physically or technically impossible, but would be fairly difficult to execute, while there are much simpler solutions available.


body:
You can use a USB **[connector][1]** ([micro][2]) (mounted on a custom PCB) for whatever you want and route the connector's pins to whichever Arduino pins you want. It will not be USB, but you could, at least, use USB cables for ease-of-connection.

This is *un-wise*, at best, because someone is, eventually, going to plug in a real USB cable.

  [1]: http://www.digikey.com/product-detail/en/87520-0010BLF/609-1045-ND/1001359
  [2]: http://www.digikey.com/product-detail/en/0475890001/WM17143TR-ND/1832253


message:
Servo motor swinging back to 0°

I just got my arduino and servo. But my servo may be acting strangely.

Whenever I tell the servo to go somewhere it keeps going to 0 than to that position and stops after 10-15 seconds or more.

This is the code used in this video

    #include <Servo.h>

        Servo myservo;

        void setup()
        {
          myservo.attach(11);
          myservo.write(50);
        }

        void loop()
        {
        }

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

It is connected like this:

Ground from Arduino to breadboard row 3

Ground from external power supply to breadboard row 3

Ground from SERVO to breadboard row 3

Power supply positive to servo VCC

Servo signal to pin 11

body:
Try with something like:

    #include <Servo.h>

        Servo myservo;

        void setup()
        {
          myservo.attach(11);

        }

        void loop()
        {
            delay(2000);
            myservo.write(50);
            while(1);
        }

and let us know.
But more important: disconnect the servo +5V wire from Arduino and use another power supplier!!!


message:
RCSwitch on Attiny85

I would like to use my Attiny85 as an remote controlled relay switch.
I have already tested the sketch on my Atmega328 and it worked.
Now I wanted to burn the sketch on my Attiny85 using ArduinoISP but I get the following error in the ArduinoIDE:

    sketch_dec25a.ino: In function ‘void setup()’:
    sketch_dec25a:13: error: ‘class RCSwitch’ has no member named ‘enableReceive’
    sketch_dec25a.ino: In function ‘void loop()’:
    sketch_dec25a:20: error: ‘class RCSwitch’ has no member named ‘available’
    sketch_dec25a:21: error: ‘class RCSwitch’ has no member named ‘getReceivedValue’
    sketch_dec25a:22: error: ‘class RCSwitch’ has no member named ‘getReceivedValue’
    sketch_dec25a:25: error: ‘class RCSwitch’ has no member named ‘resetAvailable’

That's my code:

    #include <SoftwareSerial.h>
    #include <RCSwitch.h>

    int RELAY_PIN = 2;

    RCSwitch mySwitch = RCSwitch();
    SoftwareSerial mySerial(1, 3); // RX, TX

    void setup()
    {
      pinMode(RELAY_PIN, OUTPUT);
      mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() // run over and over
    {
      if (mySwitch.available()) {
        Serial.println(mySwitch.getReceivedValue());
        if(mySwitch.getReceivedValue() == 1234567){
          digitalWrite(RELAY_PIN, HIGH);
        }
        mySwitch.resetAvailable();
      }
    }

I am using these cores: https://code.google.com/p/arduino-tiny/

I am using the SoftwareSerial just for debugging.
Sorry for my bad english and thanks for your help!

body:
The issue you face is that RCSwitch does not seem to support receive mode for ATtiny.

This is what you can find in `RCSwitch.h`:

    // At least for the ATTiny X4/X5, receiving has to be disabled due to
    // missing libm depencies (udivmodhi4)
    #if defined( __AVR_ATtinyX5__ ) or defined ( __AVR_ATtinyX4__ )
    #define RCSwitchDisableReceiving
    #endif

Then all methods related to receptions are not defined in `RCSwitch` class for ATtiny MCUs:

    #if not defined( RCSwitchDisableReceiving )
    void enableReceive(int interrupt);
    void enableReceive();
    void disableReceive();
    bool available();
    void resetAvailable();

    unsigned long getReceivedValue();
    unsigned int getReceivedBitlength();
    unsigned int getReceivedDelay();
    unsigned int getReceivedProtocol();
    unsigned int* getReceivedRawdata();
    #endif

I am really not sure if there is a way to work around it, I have not looked at the code in `RCSwitch.cpp`.

Maybe you best option would be to find another RC library.

For instance, if you can use Infra-Red RC, then there are libraries out there that could work for ATtiny:

https://github.com/shirriff/Arduino-IRremote


body:
I have tested with Digispark ATtiny85 and https://github.com/sui77/rc-switch work perfect

just comment `#define RCSwitchDisableReceiving`
than use in setup code `enableReceive(0);` and external pin 7 PB2(int0) as RF source

Or you can use other software pin interrupt

in setup:`
PCMSK |= (1<<PCINT0);//here pin number
GIMSK |= (1<<PCIE);`

interrupt function
`
ISR(PCINT0_vect) {
  rd.handleInterrupt(); // you need also put handleInterrupt() in public section in RCSwitch.h
}`


message:
Serial debug output looking messy

I've got this quite basic code running on an Arduino Mega 2560, and the output is looking like I have the serial settings wrong, though I can't work out what to change.

    void setup()
    {
      Serial.begin(9600);
      Serial.println("test123");
    }

    void loop()
    {
      Serial.println("test" + millis());
    }

The output looks like this:

    ð¦·Z©÷
    ×ï¾üÿ7ß^|ïüûÿVÏuØëo~ìÿÓûzëýÿ{ßþ©×xñ×¤¿ïßûÏûýoÏ¿îãõI
    õfwi÷`p¬½Ïª»QáÀª»¦·ð¦·Z©÷
    test123
    D

    4ñjü¯÷~µÞMz¹Ý~¼
    Ûþ}iû}ÒÖ¦Ç¿÷ÿÂï½Õ¾;îö

I'm using the inbuilt "Serial Monitor" in the Arduino suite with settings 9600 baud and no line endings.

I see that the first println in `setup()` is sending the data as expected but all other comms are coming through as nonsense.

Any suggestions of what to do?

body:
This is unfortunately not valid in C++:

    "test" + millis()

Rather than concatenating two strings, it's actually doing pointer arithmetic. It's taking the memory address where `"test"` is stored, and offsetting by the value retrieved from `millis()`. The result is a totally arbitrary memory location which gets treated like a string.

Generally speaking, it's arguably best to avoid string concatenation on Arduino anyway unless absolutely necessary. The reason is that it can use more memory than you might expect.

A simpler approach would simply be to do the serial output as a sequence of individual operations, e.g.:

    Serial.print( "test" );
    Serial.println( millis() );

Note the difference between `print()` and `println()`. The first one doesn't add a line break at the end, but the second one does.


body:
Just as a minor addition to Peter's excellent answer and comments on concatenation and implicit typecasting with `String` objects:

Alternatives to construct the message (as a `char[]`) to be send might be:

  1.  use `sprintf()`

<!language: lang-c>

    char buffer[80];  // for the complete output
    char value[4];    // for millis(), which returns an unsigned long

    sprintf(buffer, "I'm running for %u ms now", millis());
    Serial.println(buffer);

*Note that `sprintf()` uses quite some memory!*

  2. build the message 'manually':

<!-- language: lang-c>

     char buffer[80] = "I'm running for ";

     itoa(millis(), value, 10);
     strcat(buffer, value);
     strcat(buffer, " ms");
     Serial.println(buffer);


message:
Why does Arduino use USB A-B plug, instead of A to micro USB plug?

I understand that A-B plug used to be common but they could have switched to micro without issues.

My questions:

 - Why does Arduino use USB A-B plug, instead of A to micro USB plug?
 - What are the challenged Arduino would be facing if they switched to micro USB?

Note:
By "Arduino" I'm referring to Arduino models that do not come with a micro USB port such as the most common Uno & Mega.

body:
*Please note that this answer is based on speculation and some common sense rather than on insider information*:

If you take look at the [hardware index](http://arduino.cc/en/Main/Boards), you'll notice that significant parts of the layout (drill holes, pin spacing, and position and **type of the USB jack**) haven't changed between the *Arduino Extreme* and the current *Arduino UNO R3*), while other improvements have been made. For changes between the UNO R2 and R3, please see [Arduino UNO FAQ at adafruit](https://learn.adafruit.com/arduino-tips-tricks-and-techniques/arduino-uno-faq) (link provided by **jfpoilpret**).

It is thus reasonable to me that keeping the USB jack was a deliberate design decision: Improve if possible, but keep the layout changes to a minimum and allow for maximum backwards compaptibility.

*But again, this is just the guess of a user!*


message:
What are the benfits of global variables over static class members?

On an embedded system we use global variables often to keep dynamic memory consumption on heap and stack low. But global variables are also considered bad programming practice if they aren't used in a global sense, i.e. they are used only inside one or two functions.

So I really want to make use of the possibilites to protect my code from myself. Of course, the instantiation mechanism of c++ is to avoid on an embedded system with low resources, like an arduino. So I write classes with static members (and member functions) only. Many of the libraries shipped with arduino seem to work this way, too.

I'm curious if there's a single drawback of moving static variables or even const arrays (designed for deposit in progmem) from global namespace to a class namespace and making them private?

I'm primarily interested in drawbacks arising from the combination of OOP with the arduino platform (using an arduino uno) with avr-gcc.

body:
I can see no specific drawback in using static class members instead of global variables on Arduino. They will be managed the same in the end program.

The only difference I can see may arise based on how you design your classes (if design is correct, then no special problem shall arise):

Let's suppose you decale a class A:

    class A {
        public:
        void f();
        void g();
        ...
        static void z();

        private:
        static int myStaticField;
        ...
    };

if you need an instance of `A` for method `f()`, which does not need `myStaticField`, then that field exists anyway in your SRAM space.

But this is a corner-case, as in good OOD, `myStaticField` should be needed as soon as you need to work with class A (whatever method youwant to use).


message:
SD Initialization Failing

I am using a SEEED SD Card Shield. Everytime I attempt to write the card, I get

When Using File> Examples> SD > CardInfo:

    initialization failed. Things to check:
    * is a card is inserted?
    * Is your wiring correct?
    * did you change the chipSelect pin to match your shield or module?

Or when using File>Examples> SD> Files:

    Initializing SD card...initialization failed!

I even tried SdFat (IDE couldn't find anything), the "SD Library" by Adafruit (No change), and other things.

I'm using a Funduino MEGA 2560. Could that be the problem?!

body: I also use a Seeed Studio SD Shield, and used to have the same problem. To rectify this I have to insert the SD card into my PC and Format it. This almost always helped. If you have a card that has too large of storage, the Arduino will take too much time to check the full memory for information stored on it (initialize). Some SD card readers require a card of 2 gigabytes or less to work. Check the Data Sheet for this limit (if there is one). That should do it for you.


body: I spent ages failing to get my SD card working. Then installed an earlier version (1.0.8) of the SD library which fixed the issue for me.


message:
Photoresistor is not working, is there something wrong in the code?

I am trying to make the photoresistor work in a simple project.

The project is as follows:
The LED light should light up brighter and brighter as the photoresistor reads less light in the room.

The problem:
The reading is fixed on 1023. Therefore the LED never lights up. I cannot understand why.. Sometimes if I cover the sensor the readings go down to 900- 950 but never less even though it is completely dark around the sensor. Is there something wrong in the code? What could have gone wrong?
Please note that the resistor connected to the sensor is 10k Ohm as is the one connected to the LED.

Here is the code

    int photoPin = 0;
    int pReading; // analog readings

    int LED = 11; // red LED connected to pin 11
    int LEDbrightness; //

    void setup()
    {
      //set up the serial connection
      Serial.begin(9600);
    }

    void loop()
    {
      pReading = analogRead(photoPin);
      Serial.print("Photocell reading = ");
      Serial.println(pReading); // Analog reading

      pReading = 1023 - pReading;
      //map 0-1023 to 0-255
      LEDbrightness = map(pReading, 0, 1023, 0, 255);

      analogWrite(LED, LEDbrightness);
      delay(50);
    }

Here are the connections
![enter image description here][1]

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

thank you!

body:
Your wiring is wrong.

Analog inputs are high impedance and probably the impedance isn't really linear. So what voltage do you expect on your analog input, if its inner impedance is one or more orders of magnitude greater than that of your sensor and series resistor?

The inner impedance builds up the lower part of a voltage divider and your sensor and series resistor the upper part. The voltage measured will almost anytime almost 5V.

How to fix this?
You will have to make a suitable voltage divider outside your arduino. Simly connect your input via another resistor to ground. So, how to determine the right value of the additional resistor? It strongly depends on your sensor and the brightness range you want to perceive. I recommend starting with 1kΩ. Let us know,
what your readings are for full light and darkness. Then we can give some more hints.


body:
The code looks OK. It looks like it's your circuit which is the problem.

The main role of a photoresistor is to restrict the amount of **current** flowing through it when the light level is reduced. It won't directly affect voltage the way you're expecting (the analog pins respond to voltage).

However, it's pretty easy to make it affect voltage with a slightly different circuit. Try creating a **voltage divider** circuit, such that the supply voltage (5V) goes through the photoresistor, then through another resistor, and then to ground. The Arduino's analog pin should be connected between the photoresistor and resistor. (See the image below, although the resistor on the output probably isn't necessary in this case.)

This should cause the voltage on the analog pin to decrease when the light level decreases. You may need to experiment a little to find a suitable resistor value on the ground connection, although 2K Ohms is probably a good starting point. It basically affects the sensitivity of the circuit.

![Photoresistor circuit diagram][1]
Image credit: Morteza Lahijanian ([source][2])

  [1]: https://i.stack.imgur.com/GpQSC.jpg
  [2]: http://www.bu.edu/gk12/morteza/lesson3.html


message:
Arduino Yun RFID-RC522 module not working

I have tried to use Arduino Uno with RFID-RC522 module. It is good work[1] and read rfid cards. But Arduino Yun doesn't work with RFID-RC522 module.

What is diffrent Uno and Yun?

1- http://www.grantgibson.co.uk/2012/04/how-to-get-started-with-the-mifare-mf522-an-and-arduino/

body:
According to the link you provided, we can see that the RFID-RC522 uses SPI to communicate with Arduino.

On Arduino UNO, the SPI pins are located as follows:

 - pin 11: MOSI,
 - pin 12: MISO,
 - pin 13: SCK

On the Arduino YUN, this is different though; as stated [there][1] (bold highlight is mine):

> SPI: on the ICSP header. These pins support SPI communication using
> the SPI library. **Note that the SPI pins are not connected to any of**
> **the digital I/O pins as they are on the Uno**, They are only available
> on the ICSP connector. This means that if you have a shield that uses
> SPI, but does NOT have a 6-pin ICSP connector that connects to the
> Yún's 6-pin ICSP header, the shield will not work.

Hence you can not wire the RFID-RC522 module the same on UNO and Yun.
For the Yun, you'll have to follow this wiring picture:

![enter image description here][2]

Pin 1 in image above is the pin that is marked with a dot on the Yun PCB.

  [1]: http://arduino.cc/en/Main/ArduinoBoardYun
  [2]: https://i.stack.imgur.com/1WZQo.png

Also see the ISP-header layout, at the lower-right corner of the [yun_by_pighi](http://www.element14.com/community/servlet/JiveServlet/showImage/38-18269-212515/yun_by_pighixxx-d6qvbq4.png) Yun pinout diagram.


body:
I had the same issues Thanks for help .However I made the  following connections then above mentioned

RC522 RFID borad     Arduino YUN  (as per the github example code dumpinfo)
chip select (nss ) - Pin 10
Rst                - Pin 9

Link for Gihub RFID RC522
  [1]: https://github.com/miguelbalboa/rfid

Hope it helps someone who is stuck


message:
arduino wifi shield not present error

I'm using an HLK-RM04 WIFI shield and arduino uno R3 board. whenever I mount my shield on the uno board and connect it to the pc using a usb only the power led(red) of my wifi shield glows. I tried to upload the example code on wifi(provided by arduino)but whenever I run the code it shows "wifi shield not present". Looking into the previous discussions on this website I even tried to connect my arduino with usb+9v supply. In that case my trackpad of the laptop ceases to work. whenever I power my system(arduino+shield) using a 9v external supply all the 3 leds(power,link,wan led) on my wifi shield glow but still the same error of "wifi shield not present" persists.

What is going wrong?

Has anyone configured an HLK-rm04 wifi shield with uno r3 before?

Thanks

body:
I DON'T have experience with the shield you are mentioning, but it sounds to me that no data is being sent from the WiFi shield to the Arduino.  I suggest you do a bit of debugging with:

1) Print Statements
2) A multimeter (better yet, an oscilloscope)
3) Check that the pins you are connecting the shield to are not blown


body:
Might be because of a non-compatible version of the Arduino IDE? (latest version isn't always the fittest, apparently).

I found evidence for this weird behavior in various forums around the web - even when using the Uno R3 board with its official WiFi shield, I had to go back to version 1.0.3 of the Arduino IDE (and to flush its compatible firmware version for the WiFi shield) in order to get the sample code to work. Later versions just didn't work!


message:
Arduino Pro Micro clone not recognized, flickering RX LED

I have an Arduino Pro Micro clone that seems to be in some sort of reset loop. The RX LED is flickering very fast and very dim. The power LED also seems to flicker at the same frequency but has normal brightness.

The Arduino is not recognized by the PC at all anymore. It was working fine before. It doesn't matter if I try to go into the bootloader, by pressing reset twice, or not. Nothing happens. It feels like it is constantly resetting. The flickering stops if the reset pin stays connected to GND.

Another clone from the same shipment is still working fine. Both running the blink sketch. Just this one started to malfunction all of the sudden - after probing the pin I set in the blink sketch with my multimeter to see if the flashing was a success.

body:
I bricked my Pro-Micro within ten minutes of ripping it out the packet. I didn't realise that (a) it's not so brilliant on USB 3.0 - or in my case, unuseable, and (b) it's not actually an Arduino board - the Pro-Micro is a **SparkFun** product, and any clones thereof are from SparkFun's schematics.

The latter was only a problem to begin with, while I was scrabbling around on the Arduino website in vain trying to find answers. Once I realised to visit SF's website everything calmed down. Read [this section on bricked/unrecognised pro-micros](https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#troubleshooting-and-faq), and then have a look at the rest of the page as further reading.


body:
Try this: unplug the Arduino, hold down the reset button, and then plug it in to power. Hold down the reset button a few seconds after you power it on. If this works, you should get the "blink" sketch, and be able to reprogram it.

Alternatively, if you have an ICSP programmer (I use the FreeTronics USBASP), plug this in (you will need to wire up the appropriate 6 pins), and then use the Arduino IDE to burn the bootloader - select the board, serial port, and programmer,then select "burn bootloader" - all from the "Tools" pull-down menu.


body:
If your pro micro does not have a reset button, wire one between reset and ground.

Press reset twice, quickly, and immediately hit upload on the IDE.

Secondly, make sure you've downloaded and installed the Sparkfun board files for the pro micro.


body:
Try this:

 1. Connect a push button switch to ground and reset (RST) pin;

 2. Click upload then push the button twice (fast) = it doesn't matter if your computer does not recognize the pro micro;

 3. Repeat this if it failed (repeat until you are successful).

After this the Pro Micro port will comeback to life.

I tested it. The reason I think that you bricked it, is because you uploaded using the wrong board setting - commonly the 3.3 V and 5 V (or vice versa)


body:
This is a very common problem. See [my answer][1] to https://arduino.stackexchange.com/questions/2987/arduino-micro-just-blinks-wont-connect-to-pc.

As Asenkhan says in [his answer][2], it is often caused by attempting to upload to a Pro Micro using the wrong board setting 3.3 V en lieu of 5V, or vice versa.

----

I have written two lengthy blogs about the whole experience:

 - [The case of the broken Pro Micro][3]
 - [The case of the broken Pro Micro (reprise)][4]

  [1]: https://arduino.stackexchange.com/questions/2987/arduino-micro-just-blinks-wont-connect-to-pc/30604#30604
  [2]: https://arduino.stackexchange.com/questions/6702/arduino-pro-micro-clone-not-recognized-flickering-rx-led#answer-34241
  [3]: https://gr33nonline.wordpress.com/2015/08/05/the-case-of-the-broken-micro/
  [4]: https://gr33nonline.wordpress.com/2016/10/19/the-case-of-the-broken-pro-micro-reprise/


body:
You can make it work but only if you use a ISP programmer and burn the bootloader. The internal serial programmer would not work still some HID functions are retained. To me everything works fine except the Mouse functionality.

This a pain in the acc* but it will work for other options. The other thing I have not tried is setting an old arduino ide and use the old addon for pro micro board to see if there a was a change in those files that caused it to fail.

So my next step would be as follow:

 1. Setup the old arduino environment, download the old addon files and burn the bootloader.

Edit: While writting my findings I came with the solution. Just as I thought! You need to use the old files to make this work completely.

Steps:

**You'll need to buy an ISP Programmer for burning the bootloader or use another arduino board as an ISP Programmer**

I used the USBtinyISP Programmer. In specific:

[![USBtinyISP][1]][1]

Download the old sparkfun files (zip) version

[Sparkfun Old Addon Files](https://github.com/sparkfun/SF32u4_boards/releases/tag/pre-1.6)

Download the old Arduino IDE - I used the 1.0.6 portable (zip) version

[Old Release Files] (https://www.arduino.cc/en/Main/OldSoftwareReleases#previous)

Extract the Arduino IDE to Desktop. After doing so open the Sparkfun addon zip file and extract it to the Desktop. Then rename the extracted folder from:

> SF32u4_boards-pre-1.6

To

> sparkfun

Alright copy that folder and if you do as I mentioned above now you'll head for the Arduino IDE we just downloaded. When you see the arduino files move into the hardware folder and paste the sparkfun folder inside of it (don't navigate any further than this).

Then connect the ISP following this diagram: Always double check the connections!

[![Sparkfun Pro Micro Pinout][2]][2]

Now the next steps would be:

 1. Open the Arduino IDE v1.0.6
 2. Select your programmer under Tools (mine was USBtinyISP)
 3. Select your Sparkfun Pro Micro board either the 3.3v or 5v version
 4. Now under Tools select **Burn Bootloader**

If you do this right after a couple of seconds or minutes you will see a message that the process of burning the bootloader was completed. Depending on your hardware speed, if you store things in a flash drive or system is running on a linux live session you will need to wait a bit so just relax.

If things go according to plan then you can disconnect the ISP programmer and upload a simple sketch to corroborate the board is now working.

    int ledPin=10; // let to pin 10

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

    void loop() {
       digitalWrite(ledPin, HIGH);
       delay(1000/2); // 1/2 a second
       digitalWrite(ledPin, LOW);
    }

Upload as you normally would! Double check the board version!!

Perfecto! If the steps were followed in order you'll now have a working device

  [1]: https://i.stack.imgur.com/mtAJf.jpg
  [2]: https://i.stack.imgur.com/Aq9Fc.png


message:
Attiny85 and 433Mhz RF

I have [this cheap RF link][1] that I had working with the Arduni UNO, but I wanted to make it smaller and ATTiny85 should do the trick. The RF module is connected (data pin) to PB3 on the ATTiny.

But I am having some problems. It does not work, and I don't know why. My code:

    #include <SoftwareSerial.h>

    // PINS
    #define SERIAL_TX PB3

    SoftwareSerial mySerial(-1, SERIAL_TX);

    void setup() {
      pinMode(SERIAL_TX, OUTPUT);
      mySerial.begin( 1200 );
    }

    void loop() {

      mySerial.write(0xAA);
      mySerial.write(0xAA);
      mySerial.write(0xAA);

      delay(1000);
    }

  [1]: http://www.dx.com/p/433mhz-wireless-transmitter-module-superregeneration-for-arduino-green-149254#.VJ2MwF4AQ

body:
The code you presented does not fit for working with the RF 433Mhz. I'm not sure what you think this code should do, but this is not the way to go with a 433Mhz transmitter.

I would suggest using a dedicated library for transmitting information using the 433. There are many libraries out there for doing that; two popular libraries would be the [ManchesterRF][1] and the [VirtualWire][2], both includes code samples.

For example, [sending data with ManchesterRF][3]:

    #include "ManchesterRF.h" //https://github.com/cano64/ManchesterRF

    #define TX_PIN 3 //any pin can transmit
    #define LED_PIN 13

    ManchesterRF rf(MAN_4800); //link speed, try also MAN_300, MAN_600, MAN_1200, MAN_2400, MAN_4800, MAN_9600, MAN_19200, MAN_38400

    uint8_t data = 0;

    void setup() {
      pinMode(LED_PIN, OUTPUT);
      digitalWrite(LED_PIN, HIGH);
      rf.TXInit(TX_PIN);
    }

    void loop() {

      rf.transmitByte(++data, data*data);
      digitalWrite(LED_PIN, digitalRead(LED_PIN)); //blink the LED on receive
      delay(100);
    }

In addition, [there][4] [are][5] [many][6] other blogs around going step-by-step how to use 433Mhz Tx/Rx with ATtiny85, google is your friend :)

  [1]: https://github.com/cano64/ManchesterRF
  [2]: http://www.airspayce.com/mikem/arduino/VirtualWire/
  [3]: https://github.com/cano64/ManchesterRF/blob/master/examples/ManchesterTX_Byte/ManchesterTX_Byte.ino
  [4]: http://nerdralph.blogspot.co.il/2014/04/attiny85-as-433mhz-transmitter-fail.html
  [5]: http://pidome.wordpress.com/manual-howtos/pidome-hardware/attiny85-433mhz-transmitter-with-i²c/
  [6]: http://labalec.fr/erwan/?p=1520


message:
Arduino UNO GPS module

I am thinking about buying a gps module for Arduino UNO.

I would like to install it on a self-build RC-car which is also controlled by Arduino.
The problem is, I cannot install the gps module on the top of the car (on the surface), only the bottom and or/middle space is "free".
My questions are:

1)Is there a module which can overcome a small layer of steel (max 2cm thick) and some plastic and still get a good signal?

2)It would be nice to be able to store the data into a memory card.

3)It would be a great plus to be able to gather data real-time through some kind of connection. Sadly I do not know how to do here. Is there some place where I can look up any of this?

Do you think that this http://www.adafruit.com/products/1272 is what I need?

thank you

body:
1) Just break out the headers on the GPS module to make for connections to the UNO.

2) Add a SD expansion slot on top of the GPS Module and break out the pins for those as the required pins for those as well.

3) I am not sure what you are asking exactly, but it seems to me that you want to analyze the data real-time.  Get a network shield and make sure you can SSH into it through another computer.

Note: When I say "break out the pins", I am simply saying either solder on some extra headers, or wires.


message:
Powering Arduino from a shield

I'm designing a shield for Arduino which drives two stepper motors. They are small and require 5V but their max combined current is around 1A, way too much for the USB supply. Therefore I will have external 5V power supply connected to my shield.

The entire device will usually operate being connected to a PC through USB, but still I'd like to have a possibility to run it separately.

The question is: how to power Arduino itself?

 1. From my external PSU through the pins: Sounds as the simplest solution but I'm bit worried about the onboard regulator of Arduino while reverse powered.
 2. Separate power circuits for electronics and motor: My L293D chips allow for separate power and even different voltage for the motors. It could even be an advantage for my shield, as I could use other motors and different power for them in the future. I will, however, lose the possibility of running the device without USB connection.
 3. Same as above with additional barrel jack power connection to supply Arduino when USB is disconnected. This, however, could fail with 5V supply, because of the voltage drop of the regulator which handles power coming from barrel jack.

body:
Option 1 is by far the simplest. Just have one 5V power supply for everything.  Make sure you have enough capacitance on there to absorb the noise of the motors - maybe separate the digital side from the drive side with an inductor.

You can add a diode connected backwards between the 5V and VIN pins to bypass the regulator when reverse powered.  That is, anode to 5V and cathode to VIN.


body: What I am doing for similar is powering 7.2v to motorshield EXT_PWR and same to RAW pin of Arduino mini pro, where taking 5v out from vcc and input to motor shield 5v. It works for my car well.


message:
Is SoftwareSerial left out for the ATTiny85/84?

I want to use SoftwareSerial with my ATTiny85 and when I google it several projects claim that they are using it... I downloaded the hardware from https://code.google.com/p/arduino-tiny/, but when I try to add SoftwareSerial and compile I get:

    fatal error: SoftwareSerial.h: No such file or directory

Switching the board to UNO makes the problem go away, so did they leave it out? How can I fix this?

body:
Short answer - no. It's not left out, on the contrary.

But before addressing to the compiler error you mentioned, a small clarification:

> I downloaded the hardware from https://code.google.com/p/arduino-tiny/

The link you provided is not *hardware*, but *software* called the **ATtiny core files**. It contains the necessary files that will help you compile and upload code from Arduino IDE to the ATtiny (even when using ArduinoISP as programmer).

The **SoftwareSerial** is a library that comes with the Arduino IDE zip/installation. If you have downloaded the latest version of Arduino IDE from the [Arduino Website][1], you should be able to find the SoftwareSerial library files located at:

    [Path to Arduino installation folder]\libraries\SoftwareSerial

Example for SoftwareSerial library files you should expect to find there are **SoftwareSerial.cpp** and **SoftwareSerial.h**.

> fatal error: SoftwareSerial.h: No such file or directory

The compiler error you receive seems to imply that the compiler cannot find the header file (SoftwareSerial.h) for SoftwareSerial library. This indeed seems quite odd, since this library does not require any special installation, and as mentioned, is part of the libraries that are built into the Arduino IDE installation.

So, to mitigate this, I would recommend that you will:

- Make sure the library folder exists in the location mentioned above
- If it doesn't, then you should probably re-download the Arduino IDE installation, and after that install the ATtiny core files as per the instructions (important!). Installation instructions are located in the **README** file inside the ATTiny core zip file
(tiny\avr\README).
- If it does exist, and you still get this compiler error, then you must have a corrupted installation (perhaps the compiler include folders is messed up). I would still recommend following the re-installation as mentioned in the previous bullet.
- Make sure that you can find the **ATtiny 85** in the board list, at Tools->Board and that it is selected.
- Another angle that might shed more light on this error, would be to turn on the verbose output for the compiler (you can do it in the Arduino IDE, by choosing File->Preferences-> "Show verbose output during" and checking "compilation"). Verbose output can help you track down any compiler command line errors, like missing include folders.
- Last but not least, if the SoftwareSerial folder exist, you could use the Arduino IDE to check if the IDE can identify its existance, by going to Sketch->Import Library, and looking for *SoftwareSerial*. If it's not there, then the folder is not located properly under the 'libraries', verify the path as mentioned above (did you move it?)

Finally, when you will be able to compile your code, try using the SoftwareSerial example that comes with the library to check it. Note that it is not going to work 'out-of-the-box' as with the Arduino Uno; The ATtiny does not have the same FTDI hardware for communicating directly with USB, so for sending and receiving serial messages using the ATtiny you will have to either use the Arduino Uno as a proxy (using the Uno's pins 0 & 1) or to use dedicated USB to Serial hardware similar to [this one][2].

> Switching the board to UNO makes the problem go away

As a side note, switching to the Uno will make most ATtiny problems 'go away' since the Uno is much more equipped than ATtiny85/4, both on the MCU level and on the breakout board level, which you get with the Uno (and which you don't get when working directly with a chip like ATtiny). Also, most of the code base out there is targeting the Uno and not ATTiny.
So if you are doing your first steps with the ATtiny, be prepared that many things that 'just worked' with the Uno will require extra/different code before they could work with the ATtiny (and some won't work at all).

You can use my simple Analog to Serial code :

    /*
    Takes an input on the AtTiny85 from the VERY TRICKY analogue input pin 2 (as labeled in HLT tutorial)
     and outputs these with Software serial to the arduino uno, or Duemillanove
     Hookup
     ATTINY85 pin 3 -> Arduino Uno pin 0
     ATTINY85 pin 4 -> Arduino Uno pin 1

    http://www.instructables.com/id/Easy-ATTiny-Serial-Communication-with-Tiny-AVR-Pro/
     */

    #include <SoftwareSerial.h>
    // Definitions
    #define rxPin 4
    #define txPin 3
    SoftwareSerial mySerial(rxPin, txPin);
    int sensorPin = 7; //ACTUALLY PIN LABELED AS "2" on the HLT tutorial
    int sensorVal = -1;

    // the setup routine runs once when you press reset:
    void setup() {
      pinMode(sensorPin, INPUT);
      mySerial.begin(9600);
    analogWrite(0,1); // This is kind a heart beat to show the ATTINY is "alive"
    }

    // the loop routine runs over and over asensorpingain forever:
    void loop() {
      sensorVal = analogRead(sensorPin);
      mySerial.print("Input Val: ");
      mySerial.print(sensorVal);
      mySerial.println();
    }

  [1]: http://arduino.cc/en/main/software
  [2]: https://www.sparkfun.com/products/9716


body:
I had the same problem and it appears that with Arduino IDE 1.6.x, libraries are defined "per board" and not shared any more.  At least, not all libraries are shared, and SoftwareSerial appears to be one of those.

So the solution is to copy the SoftwareSerial library from the Arduino installation at `[programs]/Arduino/hardware/arduino/avr/libraries/SoftwareSerial` to your ATTiny hardware folder at `[documents]/Arduino/hardware/tiny/avr/libraries/SoftwareSerial`, and restart the IDE, as per [this thread].[1]

  [1]: http://forum.arduino.cc/index.php?topic=302080.0


body:
Yes, in IDE 1.6.x, libraries are defined "per board", they reside in special folders and are provided by the atuhor of the board-bundle.
Digispark's library is named SoftSerial and is included. In IDE Check File/Examples/DigisparkSoftSerial. Also check https://digistump.com/wiki/digispark/tutorials/debugging

In short, you have to include:

       #include <SoftSerial.h>
       #include <TinyPinChange.h>

and then define RX and TX pins (could be also the same in special cases):

       SoftSerial mySerial(SOFT_RX_PIN, SOFT_TX_PIN); // RX, TX

Then use `mySerial.println()` & co.


body:
Below you can find the code for a minimal bit-bang send serial implementation ideally suited for debugging. Code size is about 60 bytes.

It gives 38400 baud for 1 MHz or 230400 baud on 8 MHz Attiny clock.

I wrote it for an Attiny 85.

[ArminJo/AttinySendSerial_1Mhz_38400Bd][1]

  [1]: https://github.com/ArminJo/AttinySendSerial_1Mhz_38400Bd


message:
5 Switches 1 AI pin

Im starting to get into Arduino a little. Ive got a Small project to start me off,
To keep it simple its: 5 level Switches, 1 flow switch and 3 solenoid valves.

This question is for the Level Switches.

Now Im wanting to save Pins as I'm using a Arduino UNO.
So would I be right to use the method ive seen around here a few times of Making a Resistance  ladder.

Question is. 1- Will the method of using the same value of resistors (2k2) work? I dont think so..

As multiple "buttons" ie the flot switches will be pressed at once it will end up having no idea whats happening correct?, I need to be able to Identify each one (0%,25% etc etc)

If I was to use different vales of resistance would that make a difference ?

Cheers

body:
Just look at [this answer](https://electronics.stackexchange.com/a/99419). When you press the LEFT switch, the SELECT button has no effect when pressed (i.e. it doesn't get detected, but also doesn't hinder detecting the LEFT button press). So in your case, you aren't really interested in the 0% button, when the 25% is pressed.

I wouldn't use same value resistors, as the resulting voltages would be non-linear, making it difficult to differentiate between the button at the far end ladder. If you'd use 2k2 everywhere, the voltages would be

 - 100% 0.00v
 - 75% 2.50v
 - 50% 3.33v
 - 25% 3.75v
 - 0% 4.00v
 - no value: 5v

In the answer provided above, voltages would be: 0, 0.71, 1.61, 2.47, 3.62, 5v


message:
Audio Frequency White Noise generation using Arduino Mini Pro

For DIY, how to program Arduino Mini Pro to act as an **Audio Frequency White Noise generator**?

Presumably,

a) using one Digital Output pin

b) feed to a simple passive RC low pass filter to reduce out of band signal

c) feed to a simple class-D IC chip audio amplifier and speaker

d) since it is DIY and noise, lo-fi (not hi-fi) is good enough.

Specific questions,

a) How to program?

b) Wonder if it is better to use to chip act a Pulse Width Modulated 'digital to analogue converter'?

c) How to calculate value for RC filter (assume amplifier has high input impedance)?

Many years ago, I have programmed a hardware sound generator chip as part of a game machine. It has two registers for amplitude and 'frequency' control (band of 'white' noise). It worked very well. I once looked at the output using oscilloscope and it was square wave. I believe that it works, basically, using the above principles. Since I do not have the chip now, I cannot verify it. Now, I would like to duplicate its function using Arduino in software.

body:
I don't know that you need all that - just an Arduino and a piezo speaker and a pot if you want to play with the volume.

    byte speakerPin = 1;

    void generateNoise() {
      static unsigned long int reg = 0x12345678; //seed
      unsigned long int newr;
      unsigned char lobit;
      unsigned char b31, b29, b25, b24;
      b31 = (reg & (1L << 31)) >> 31;
      b29 = (reg & (1L << 29)) >> 29;
      b25 = (reg & (1L << 25)) >> 25;
      b24 = (reg & (1L << 24)) >> 24;
      lobit = b31 ^ b29 ^ b25 ^ b24;
      newr = (reg << 1) | lobit;
      reg = newr;
      digitalWrite (speakerPin, reg & 1);
      delayMicroseconds (50);  // Changing this value changes the frequency.
    }


body:
Mike's answer uses a Fibonacci Linear Feedback Shift Register configuration, but the compactness Galois Linear Feedback Shift Register Configuration could be faster:

    #define speakerPin 8

    unsigned long lastClick;

    void setup() {
      // put your setup code here, to run once:
       pinMode(speakerPin,OUTPUT);
       lastClick = micros();
    }

    /* initialize with any 32 bit non-zero  unsigned long value. */
    #define LFSR_INIT  0xfeedfaceUL
    /* Choose bits 32, 30, 26, 24 from  http://arduino.stackexchange.com/a/6725/6628
     *  or 32, 22, 2, 1 from
     *  http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf
     *  or bits 32, 16, 3,2  or 0x80010006UL per http://users.ece.cmu.edu/~koopman/lfsr/index.html
     *  and http://users.ece.cmu.edu/~koopman/lfsr/32.dat.gz
     *  or generate a one with https://github.com/hayguen/mlpolygen
     */
    #define LFSR_MASK  ((unsigned long)( 1UL<<31 | 1UL <<15 | 1UL <<2 | 1UL <<1  ))

    unsigned int generateNoise(){
      // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs
       static unsigned long int lfsr = LFSR_INIT;  /* 32 bit init, nonzero */
       /* If the output bit is 1, apply toggle mask.
                                        * The value has 1 at bits corresponding
                                        * to taps, 0 elsewhere. */

       if(lfsr & 1) { lfsr =  (lfsr >>1) ^ LFSR_MASK ; return(1);}
       else         { lfsr >>= 1;                      return(0);}
    }

    void loop() {
          /* ... */
          if ((micros() - lastClick) > 50 ) { // Changing this value changes the frequency.
            lastClick = micros();
            digitalWrite (speakerPin, generateNoise());
          }

    }

For a 16 bit implementation (faster, but only a cycle of 2^16) try:

    #define LFSR_MASK 0x8016
    static uint16_t lfsr = LFSR_INIT;  /* 16 bit init, nonzero */

Written in a more compact form:

    #define speakerPin 8

    #define LFSR_INIT 0xfeed /* non-zero seed value for generateNoise() */
    #define LFSR_MASK 0x8016 /* magic number from http://users.ece.cmu.edu/~koopman/lfsr/ */

    unsigned long lastClick;

    void setup() {
      // put your setup code here, to run once:
       pinMode(speakerPin,OUTPUT);
       lastClick = micros();
    }

    unsigned int generateNoise(){
       // Return 1 bit of noise using a Galois Linear Feedback Shift Register
       // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs

       static uint16_t lfsr = LFSR_INIT;

       if(lfsr & 1) { lfsr =  (lfsr >>1) ^ LFSR_MASK ; return(1);}
       else         { lfsr >>= 1;                      return(0);}
    }

    void loop() {
          /* ... */
          if ((micros() - lastClick) > 50 ) { // Changing this value changes the frequency.
            lastClick = micros();
            digitalWrite (speakerPin, generateNoise());
          }

    }

For an 8 bit implementation (faster than 32 bit, slightly slower than 16, but only a cycle of 2^8) try:

    #define LFSR_MASK 0x8e

    static byte lfsr = LFSR_INIT;  /* 8 bit init, nonzero */

Where the mask constants are from the 8.txt and 16.txt files at http://users.ece.cmu.edu/~koopman/lfsr/index.html

The https://github.com/hayguen/mlpolygen program can search for maximum length feedback polynomials of various bit sizes.


message:
too few arguments to function 'void setColor(int, int, int)'

When I put "c" inside `setColor(c);`

it tells me:

    error: too few arguments to function 'void setColor(int, int, int)'.

I understand that I should put 3 arguments. What I don't understand is that the serial is correctly displaying the 3 arguments (255, 000, 000) so why it keeps telling me this error. What am I doing wrong ?

    int rPin = 11;
    int gPin = 9;
    int bPin = 10;

    void setup() {
        Serial.begin(9600);
        pinMode(rPin, OUTPUT);
        pinMode(gPin, OUTPUT);
        pinMode(bPin, OUTPUT);
    }

    void loop() {
        if (Serial.available() > 0) {
                delay(100);
                while (Serial.available() > 0) {
                    char c = Serial.read(); // serial will display an rgb code, for exemple: 255, 000, 000 (red color)
                    setColor(c);
                }
            }
    }

    void setColor(int red, int green, int blue) {
        analogWrite(rPin, red);
        analogWrite(gPin, green);
        analogWrite(bPin, blue);
    }

body:
In the context of C/C++, the type `char` refers to a primitive type that can contain exactly one byte of information, or 8 bits if you like.

> the serial is correctly displaying the 3 arguments (255, 000, 000)

In your question, you do not specify how you verify that this is indeed the information that returns from Serial.read. [Serial.read][1] returns one byte, which can be cast or parsed to an Integer but cannot be interpreted as the triplet (255,000,000) in no way. If you keep calling it repeatedly, however, as long as there is data (meaning that the result is greater than -1 or `Serial.available` returns a number greater than 0) - you can accumulate the characters to a meaningful string, which you can later split to three different `int` values. For example:

    String incomingData = "";

    void loop()
    {
        if (Serial.available() > 0) {
             delay(100);
             while (Serial.available() > 0) {
                 char c = Serial.read();
                 incomingData.concat(c);
             }

             // now, the string incomingData will contain "255,000,000" which you can split into 3 different integers and send to setColor.
             // so, assuming the format "ddd,ddd,ddd":

             int color1 = incomingData.substring(0,3).toInt();
             int color2 = incomingData.substring(4,7).toInt();
             int color3 = incomingData.substring(8).toInt();
             setColor(color1, color2, color3);
        }
    }

  [1]: http://arduino.cc/en/Serial/read


message:
How to attach interrupts to Arduino UNO timers?

I understand there are 3 timers on the Arduino UNO.  What specific registers do I need to use to access them?

My goal is to use these timers to poll different sensors I am using with a ms period. Are there any pre-made libraries out there to do this?

body:
Timer 0 is use'd by the arduino core libraries for functions like millis(). It is best left alone. Leaving timer1 and 3 are available for general use. Both 1 and 3 have well established libraries, for simple implementation, without the need to know the mechanics under the hood, about the registers and such.

You can find links and general explanations at [timer1](http://playground.arduino.cc/Code/Timer1). I always recommend the github versions.

And if you are still wanting to know the details the source is quite readible.

-------

Note you don't need 3 timers to read 3 sensors. One timer on a multiple of the the 3, should suffice which can then implement a statemachine to sample at the correct periods.


body:
For the UNO, use Timer1.

An example of the way you can use it is as follows:

Download the TimerOne library: https://code.google.com/p/arduino-timerone/downloads/list

    /*
     *  Timer1 library example
     */

    #include "TimerOne.h"

    void setup()
    {
      pinMode(10, OUTPUT);
      Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
      Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
      Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
    }

    void callback()
    {
      digitalWrite(10, digitalRead(10) ^ 1);
    }

    void loop()
    {
      // your program here...
    }


message:
how to make arduino as mind thought reader?

I'm trying to create arduino base mind reader... And for that I thought that EEG electrode connected to arduino and then the data send to arduino in 01 form .. But I facing problem in how to convert this or which wave (alpha, beta,delta)give very high or acutrate result.

body:
You could hack an existing device like the Mattel Mind Flex ($20-50 on Ebay).

There have been a number of projects that do exactly what you have described - there's even an arduino library: https://github.com/kitschpatrol/Brain

http://frontiernerds.com/brain-hack


body:
Even if the answer provided by Mike is really doable and can be implemented you should really think about what you want to reach and what is your goal.

The big difference between EEG and mind readers is that the process of thinking, even if you can record all that waves: alpha, gamma,... can be never decoded to get useful informations. I mean: you can record and get a confirm that you have more gamma waves when you are doing meditation. Or that aplha and beta wave are going to be much more present when waking up or in particular hours of the days, but you never get an image of what the person is thinking or what are its emotions... That because you can get some waves coming from the brain but you cannot reconstruct the billion of processes that are happening *inside* the brain.

A lot of researcher are trying to decoder those informations to move as an example an arm or a leg. But it is the front edge of the reasearch really not doable with an Arduino....

Anyway good luck!


message:
Discrete H-Bridge very low current output

I have built two parallel H-bridges from "Design 1" [on this page](http://www.talkingelectronics.com/projects/H-Bridge/H-Bridge-1.html) as you can see in the attached schematic.

However when I apply the external power (VCC1 in the center of the diagram) the two motors do not spin.

Using my multimeter, I can see that the entire circuit is working: the motor is getting a 'forward' and 'backward' current as the Arduino sets the pins high. The multimeter is reading +/- 5.54V with the motor replaced by the multimeter. (Across the motor this drops to 0.13V)

So then I measure the current by putting my multimeter both in series with the motors and replacing the motors. There's only 40mA available! Looking around the web I found the suggestion to reduce the 220Ω resistors at R2, R3, R5 and R6. So I switched in (randomly) 27Ω resistors and the output current is still only 40mA.

What else should I try to bring up the current enough to drive the motors?

**Edit:** So my uneducated guess is that it's likely that the limitation is coming from the transistors. The Ns are BC549 and the Ps are BC559. The datasheets list "low current" as a feature, but I figured that was the collector.

**Edit 2:** The motor is [this one](http://www.icstation.com/product_info.php?products_id=2535) which requires 70mA when running (and presumably more during startup)

![Schematic of two H-bridges controlled by Arduino][1]

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

**Edit 3:** Code driving the Arduino:
<!-- language: c -->

    // Pin setup
    int pinLeftMotorFwd   = 5;
    int pinLeftMotorBck   = 6;
    int pinRightMotorFwd  = 10;
    int pinRightMotorBck  = 11;

    // Directions for the {left, right} motors to achieve the four directions
    int FORWARD[]   = {  1,  1 };
    int BACKWARD[]  = { -1, -1 };
    int RIGHT[]     = { -1,  1 };
    int LEFT[]      = {  1, -1 };

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

        pinMode(pinLeftMotorFwd,  OUTPUT);
        pinMode(pinLeftMotorBck,  OUTPUT);
        pinMode(pinRightMotorFwd, OUTPUT);
        pinMode(pinRightMotorBck, OUTPUT);
    }

    void loop() {
        go( FORWARD, 10 );
        go( RIGHT,    3 );
        go( FORWARD, 10 );
        go( LEFT,     6 );
    }

    // Move the bot in a particular direction from the array above for a given number of seconds
    void go ( int dir[], int dur ){
        leftMotor(  dir[0] );
        rightMotor( dir[1] );
        delay( dur * 1000 );
    }

    // Sill both motors (OK, so stop both motors. But stop is a keyword in C)
    void still(){
        leftMotor(  0 );
        rightMotor( 0 );
    }

    // Set the left motor to Backward (-1), Forward (1), or Stop (0)
    void leftMotor( int dir ){
        // Pull both pins low
        digitalWrite(pinLeftMotorFwd, LOW );
        Serial.println("pinLeftMotorFwd LOW");
        digitalWrite(pinLeftMotorBck, LOW );
        Serial.println("pinLeftMotorBck LOW");

        // If we're going forward, pull the Fwd pin high
        if( dir == 1 ){
            digitalWrite(pinLeftMotorFwd, HIGH);
            Serial.println("pinLeftMotorFwd HIGH");
        }

        // otherwise, pull the Bck pin high
        else if( dir == -1 ) {
            digitalWrite(pinLeftMotorBck, HIGH);
            Serial.println("pinLeftMotorBck HIGH");
        }
    }

    // Set the right motor to Backward (-1), Forward (1), or Stop (0)
    void rightMotor( int dir ){
        // Pull both pins low
        digitalWrite(pinRightMotorFwd, LOW );
        Serial.println("pinRightMotorFwd LOW");
        digitalWrite(pinRightMotorBck, LOW );
        Serial.println("pinRightMotorBck LOW");

        // If we're going forward, pull the Fwd pin high
        if( dir == 1 ){
            digitalWrite(pinRightMotorFwd, HIGH);
            Serial.println("pinRightMotorFwd HIGH");
        }

        // otherwise, pull the Bck pin high
        else if( dir == -1 ) {
            digitalWrite(pinRightMotorBck, HIGH);
            Serial.println("pinRightMotorBck HIGH");
        }
    }

body:
Design 1 wouldn't be my first thought on how to do this either! The transistors aren't a great choice, but are cheap & common.

The layout [here](http://www.robotroom.com/BipolarHBridge.html) is more conventional, and you can physically link 1-2, & 3-4 to connect to your arduino without the risk of short circuits.

I suspect your code may be setting both lines high together - the only advantage I can see to the posted circuit is that this does not necessarily cause smoke (but may well do as you describe). This is why posting the code is recommended!


message:
Can I use the setup() function inside the loop() function

In the normal case the setup() function will be run once automatically and and then the loop() function will run many times.

I want to initialize several modules in the setup() function and then in the loop() I want to read values from them periodically. But if the period between usage is long I want to power off the modules. After defined time the modules will be powered on again and need to be initialized. Can I use the already existing setup() function inside the loop() to initialize the modules or I have to write another similar function? Is there any other better way to power off/on sensors and modules during the execution of code.

body:
It could be possible, since it is going simply to call the same function **BUT** it is really a very bad design*.

Usually the main purpose for a microcontroller is just sitting there and run a procedure or main function repeatedly until the end of the world. And during one loop just to check if some conditions are met.

You should never stop or influence your `loop()` function and never mess up the default design of the arduino.

In you case (but it depends on your code and your application), you just want to run the `loop()` once all sensors have been already started (in the `setup()` function).

In your run, you check periodically the sensor and start a timer (better if interrupted). If an amount of time has expired and the sensor should be turned off, then the timer will call another function, which has the only target to switch sensors off.

The `loop()` runs again and again and if the original condition is met, then you can start your sensors again.

To save up time and code typing, I suggest you write only ONE function for switching on the sensors and call this function in `setup()` and in your `loop()`, something like this:

    void startSensors();
    void stopSensors();

    void setup() {
      startSensors();  // I start all sensors here
    }

    void loop() {
      if( condition?!?! )
         {
           ...
           stopSensors();
           ...
         } else {
           ...
           startSensors();  // I call the same function here
           ...
         }
    }

*: for istance you define in your `setup()` the connection through serial port. This means that your object "serial port" is going to be recreated each time you call `setup()` whit undefeined behavior in case it is outputting datas or has same data in the FIFO Buffer. Simply...`setup()` has that name because needs to setup things once. Everything that must be done more than once, then must be called from `run()` too.


message:
Compilation error when trying to give pointer to a function to another function

I'm trying to write a library for Arduino using the Wire library.
Here's my code:

PiCom.h:

    #ifndef PiCom_h
    #define PiCom_h

    #include "Arduino.h"
    #include <Wire.h>
    class PiCom
    {
 public:
  PiCom(int address, int* integers[], double* doubles[]);
  static void onReceiveCallback(int numbytes);
  static void onRequestCallback();
 private:
  //Actually arrays of pointers to the data to be sent, has to be declared that way cause the size of the array isn't known at compile time
  int** _integers;
  double** _doubles;

  void onReceive(int numbytes);
  void onRequest();

  static PiCom instance;
    };

    #endif

PiCom.cpp:

    #include "Arduino.h"
    #include "PiCom.h"

    static void onReceiveCallback(int numbytes)
    {

    }

    PiCom::PiCom(int address, int* integers[], double* doubles[])
    {
     _integers = integers;
     _doubles = doubles;

     Wire.begin(address);
     void (*receiveFunction) (int);
     receiveFunction = &PiCom::onReceiveCallback;
     Wire.onReceive(receiveFunction);//Here i get an error
    }

I want the  constructor to be created when a new instance is created. A mehtod in this object should be called when data is requested or received. When trying to pass onRequest(int) directly to Wire.onRequest(void (*) (int)) an error is thrown. Same happend when saving it to receiveFunction.

This problem was solved by using a static function (onReceiveCallback(int). I wanted this static function to call onRequest(int) in the object saved into PiCom::instance.

But now i'm getting another error:

    PiCom\PiCom.cpp.o: In function `PiCom':
    C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'
    C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'

body:
Pointer to a member function is [a painful corner of C++][1] until C++11. This is why when you try to pass an instance method pointer to `Wire.onReceive` (without the `static` keyword), you will get an error similar to:

    error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say '&PiCom::onReceiveCallback'

Well, you can't argue with the C++ ISO standard... changing the function to a static one (with external linkage, as they say) is indeed a workaround, as you have found out.
For this workaround to compile properly you just need to omit the `static` keyword from your **definition** (where it is implemented), and leave your **declaration** (in the header file) as is:

PiCom.h:

    ...
    static void onReceiveCallback(int numbytes);
    ...

PiCom.cpp:

    void PiCom::onReceiveCallback(int numbytes)
    {
        ...
    }

By doing this you can pass it to Wire.onReceive without any problem, from the PiCom constructor, as follows:

    PiCom::PiCom(int address, int* integers[], double* doubles[])
    {
        ...
        Wire.onReceive(&PiCom::onReceiveCallback);
        ...
    }

  [1]: http://sphaleron.blogspot.co.il/2012/01/evil-c-5-member-function-pointer.html


message:
Data Report Which Technology

I want to create a small position reporter for cars. I found some good GPS Modules with which i could collect data. But i'm unsure with what technology i should send the data.

A possibility would be to setup a service in the www which is feeded by the arduinos.

I want to track the data live. so i think GPRS should be the right choice ?
Or more better are there any shields which make this GPRS LOG and SEND as a package ?

Which GPRS hardware would you use ?
Would you use something else?

Any hints are very welcome

body:
You can actually find all the information for what you want to do on the formal Arduino.cc website. [They suggest a GSM shield][1]:

![enter image description here][2]

But of course you can find many other GSM shields for purchase. Most of them works the same. Arduino.cc also offer a [nice GSM Library][3], with which you [can perform HTTP GET/POST][4] queries to a remote webserver (visible over the web).

You can select whatever web server technology you prefer for receiving the data. Using NodeJS, PHP, MVC.NET or any other, you could expose a REST API to perform the update from the Arduino+GSM Shield side using HTTP.

The web server then could analyze the incoming data and display it in any way you like.

  [1]: http://arduino.cc/en/Main/ArduinoGSMShield
  [2]: https://i.stack.imgur.com/Fncge.jpg
  [3]: http://arduino.cc/en/Reference/GSM
  [4]: http://arduino.cc/en/Tutorial/GSMExamplesWebClient


message:
Arduino motor shield will only work in one direction

I have this Arduino [motor shield][1] which is hooked up with two DC motors. The board is the same [as this one][2] from Sparkfun.

A PWM output controls the speed of the motor, and a digital out controls the direction. The problem is that it only works in one direction, namely if the direction pin is high.

With the direction pin HIGH and 255 is written to the PWM pin, Vout on the terminals is similar to Vin. If I reverse the direction by setting the direction pin LOW I would expect Vout to be -Vin, ie. the polarity reversed. But not so. I get a little more than zero volt across the terminals.

It's the same for both channels.

**Edit: The setup is powered from a 9V power adaptor through the barrel jack on Arduino.**

![Photo of the DC motor connected to the driver board][3]

Is the board defective, or am I misunderstanding something?

SOLUTION: Thanks to the edited post (especially #3) in the accepted answer, I not only looked at the schematic (again), I actually understood it. I had already noticed the jumper called V-LOGIC which on the picture from Sparkfun was set to 5V where it on my shield was not set. I really didn't know what it was used for, but I set it to 5V so it was the same. But by looking at the schematic and the inverters, I realized that the inverter was fed from V-LOGIC which was connected to 5V. And bingo: I had not connected the 5V pin on the shield, only vIN which I assumed would be sufficient. The thing is, I am awaiting a set of stackable headers instead of the ones supplied, so I only connected the minimum numbers of pins because I will need to desolder them when I get the new headers.

  [1]: http://www.ebay.com/itm/161276647817
  [2]: https://learn.sparkfun.com/tutorials/ardumoto-shield-hookup-guide
  [3]: https://i.stack.imgur.com/EznN2.jpg

body:
I think you may be having an issue with how you are powering the shield.  Are you trying to do it with just your USB connection?

In your photo, I do not see a connection to your Arduino's barrel jack or to the Vin connector of the shield itself.  According to the [SparkFun](https://learn.sparkfun.com/tutorials/ardumoto-shield-hookup-guide) site:

>The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:

>1. The **barrel jack** input on the Arduino.
2. The **Vin input** on the shield

>If you don’t want to use the Arduino’s barrel jack input, you can use the **Vin input on the shield** instead. This voltage input will supply **both the shield and the Arduino**. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.

>Do not supply power to both the Arduino barrel jack input and Vin on the shield!

I hope this helps!

**EDIT BASED ON COMMENTS**
Since you are properly powering the shield, I would recommend the following (see the [shield's schematic](https://www.sparkfun.com/datasheets/DevTools/Arduino/Ardumoto_v13.pdf?_ga=1.206814291.1113379437.1408059991) for specifics):

1. Maintaining the connection shown above (with the addition of the 9V power supply connected to the barrel jack) ensure that you are able to properly set the DIRA input.  You can check this with a multimeter on pin 7 of the LN298 whenever you are trying to switch directions.
2. If you are getting the expected results on pin 7 (pin goes HI when your code wants the motor to go one direction and pin goes LOW for the other) - check pin 9... the value here should always be the opposite of what you are setting for DIRA on pin 7.  If that is all good, then you probably have an issue with the LN298.
3. If you are not getting the expected results at pin 9, but pin 7 looks good, then you are having a problem with the 74HC1G04 IC (although I would doubt this since you are having problems with both the A and B motor outputs).
4. If you are not getting the expected results at pin 7, then double check the code to make sure you have set and cleared the correct output pin.  I would also check the solder joints of the connectors on the shield - you can set a multimeter to do a resistance check from the shield's connector (pin 12) to the direction input on the LN298 (pin 7).  If the continuity is measuring close to 0 ohms then there is probably an issue with your code.
4. If your code looks good, I have also had issues with bad outputs on the Arduino - you can check to see if you are properly toggling the direction pin (pin 12) on the Arduino without the shield connected.  Then, if the pin is not toggling, there is probably an issue with your Arduino - try toggling a different (unused) pin and jumpering it.


message:
Choosing right Sleep state

I'm planning on building an LED clock, but I want it to be lit only when I press the POWER button on my remote control. Using an IR receiver, which Arduino sleep mode should I use to reduce the current consumption but still be able to receive this interrupt?

body:
I recommend reading [ArduinoSleepCode](http://playground.arduino.cc/Learning/ArduinoSleepCode). Where it demonstrates placing the avr into a sleep state and using an interrupt to awake from the sleep state. In your case you can connect the output of your IR demodulator to the interrupt  pin, to simular awake.

Ken Shirriff's IR library allows you to use any pin as a receive input, so that you can use INT0 or 1 on D2 or D3. If you need to use a different pin, the Microtheron's github fork uses Pin Change interrupts. (I am not sure if stock sleep.h will awake from PCint, like int0 or 1 will, without tweek. Section 10.1 of data sheet says it will.)


message:
Serial interrupts?

In a project, I’m using an EIA485 bus to send encrypted data packets. That works with Arduino’s buffered serial, but it is kind of awkward, and I’m using none of the more complex stuff in that class anyway.

If I do not use `Serial` anywhere in my Arduino sketch, is it safe to create my own interrupt handlers for `USART_RXC` etc. and to directly manipulate the USART registers?

body: Absolutely. The only interrupt that Arduino takes for itself unilaterally is the timer 0 overflow interrupt, used for timing purposes (`delay()`, `milliseconds()`, et alia).