message:
I cannot find the I2C device by scanning

I've been trying to get a LCD I bought from deal extreme to work for some time with my ATTiny85 chip. It should be capable.
I've tried googling the device but there is no proper documentation, so I figured the best way to get the address is to scan for it. How ever, the code below does not work :( any pointers? Anyone else who has gotten this I2C LCD display to work with Arduino?

As I have no other output then the screen, the thought behind the code is to scan for devices and then when it finds one (the LCD is the _only_ one connected to the bus) should then print the address :)

I only have a serial programmer and attiny85 chips, so I have no way to bring it to a full Arduino UNO or whatever for further debugging.

    #include <TinyWireM.h>
    #include <LiquidCrystal_I2C.h>

    void setup()
    {
      TinyWireM.begin();
    }

    void loop()
    {
      byte error, address;

      for(address = 1; address < 127; address++ )
      {
        TinyWireM.beginTransmission(address);

        error = TinyWireM.endTransmission();

        if (error == 0) break;

        delay(5000);
      }

      LiquidCrystal_I2C lcd(address, 16, 2);

      lcd.init();
      lcd.backlight();
      lcd.clear();

      lcd.setCursor(0, 0);
      lcd.print("Hello World - " + address);
    }

I2C LCD: http://www.dx.com/p/iic-i2c-2-5-blue-screen-lcd-display-module-for-arduino-green-black-266170#.U6f_B_l_vIc

body:
I'm not sure on your program, but I bought a LCD display from Deal Extreme. I use the following address to communicate with the display:

    LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27

It seems as that is the correct address for the LCD.


sender: user

message:
Arduino and XBee Series1

I have actually reap 3 numerical values (3 sensors) from a remote XBee module and then manipulate these 3 signal with an Arduino card attached to another XBee module. To do this, I chose to use the IO line passing because it proved the easiest. My problem is this: for the XBee transmitter, I set:

    ATID 3001
    ATDL 2
    ATMY 1
    ATIU 1 / / to activate the IO option
    ATD0 3 / / where is plugged a pushbutton
    ATD1 3 / / where is plugged another pushbutton
    ATD2 3 / / where is plugged proximity sensor (presence)

For the XBee receiver (the one connected with the arduino board):

    ATID 3001 ATDL 1 ATMY 2 ATIA 1
    ATD0 4
    ATD1 4
    ATD2 4

Where I'm stuck is on the Arduino programming. Which command is used to determine the change of state of xbee remote? because I want to know if the states of the sensors on input are high or low.

sender: assistant

body:
There are two ways this could be tackled:

 1. physically through connections between the xbee and arduino and read the xbee pins directly (I've never done this, and it comes down to your shield supporting it). Each of the desired output pins of the receiving xbee would be tied to a GPIO pin of the arduino. Alternatively,

 1. serially using `AT` commands via the serial connection.

I have never worked with series one, but essentially:

 1. setup a serial connection to your arduino

 1. send the desired `AT` command requesting the pins value

 1. read the serial port response

Make sure to read the manual for the series 1 xbees for the right `AT` commands and in how to interpret the results. [Register at digi][1] and download the datasheet.

Also, just realise reading the xbee data is going to be different depending on how you have the xbee setup, ie `API` vs `AT` mode.

Here is someone who has done some work with series 1: http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index

I'll leave the actual implementation to you since this sounds a little like a homework assignment. Give it a go using the second method above and see how you go. Then post back here (ie update the question) including source code and exact layout (schematic preferred) and we'll see where we can help you from there.

Hint: google such terms as: "read data pins xbee arduino" (without the quotes).

  [1]: http://www.digi.com/products/wireless-wired-embedded-solutions/zigbee-rf-modules/point-multipoint-rfmodules/xbee-series1-module


message:
For which type of serial communication is Arduino Severino designed?

Arduino has become quite costly where I come from (2/3 of the price of Raspberry PI) so I have created an [Arduino Severino clone][1].

I had used the device with the RS-232 Usb-Serial converter. But after a (long) while, the device stopped working. My friend came up with a point that RS-232 communication ranges between +6 to -6 V (with thresholds at +3 and -3 volts).

So I have tried FT232 which uses 0 to 5 volts instead. I have a little <del>Chinese</del> [FTDI][2] chip designed to do that:
![usb to serial front side][3]

![usb to serial back side][4]

However, after connecting it, it behaves unexpectedly. (it had crashed my PC, one of the communication LEDs is on all the time...) I realised that the Arduino board might get broken for a different reason (an accidental short-circuit is *very* likely).

So for which type of communication is this *"Arduino"* designed?

  [1]: http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3
  [2]: http://www.ftdichip.com/
  [3]: https://i.stack.imgur.com/UI2pR.jpg
  [4]: https://i.stack.imgur.com/1hK83.jpg

body:
A typical 5V Arduino will use logic-level serial - that is 0 and 5V signalling.

RS232 has signal levels of plus or minus 3 to 15 volts. RS-232 drivers and receivers must be able to withstand indefinite short circuit to ground or to any voltage level up to ±25 volts

From [Wikipedia](http://en.wikipedia.org/wiki/RS-232#Voltage_levels)

Many RS232 interfaces will receive 0-5V signals.

I believe the original serial Arduino had circuitry to tolerate RS232 signal levels on it's inputs.

Since most computers now have USB rather than RS232 ports, Most users of Arduinos use a USB to logic-level serial interface. Some of the most popular chips for this are from FTDI such as the FT232RL on your Chinese clone of a "[FTDI Friend](http://www.adafruit.com/products/284)". In this case all the signals are logic-level 0-5V (or 3.3V if you change the jumper link).

So the following are probably OK

     PC DE-9 RS232    ----- Severino DE-9
     PC DB-25 RS232   ----- Severino DE-9
     PC USB port ---- "FTDI Friend" ---- Arduino 0(RX), 1(TX), Reset, GND and (optionally) VCC.


body:
The arduino you linked to is designed for RS232-level serial signals, which can be guessed from the use of a DB09 connector.

The FT232 print you show is for 5V TTL (or maybe 3.3V 'TTL') signaling. Not compatible with your arduino. (BTW: that chip is not Chinese at all, it is made by www.ftdichip.com IMO they make the best usb-to-serial chip/driver products.)


body:
Looking at the schematic of that board it uses a very crude signal inversion for the RS-232.  This allows it to work of a standard RS-232 signal direct from a computer - *just*.

It's far from ideal and really should use a MAX232 (or similar) chip for the interface.

Your FT232 adaptor should bypass that chunk of the circuit and connect direct to pins 0 and 1 of the Arduino clone.  The DTR pin of the FT232 should connect to the RESET pin of the Arduino clone via a 100nF capacitor to allow the IDE to reset the board to enter the bootloader.  Oh, and of course, connect the ground to your Arduino clone too (something Arduino users often forget).

You can follow the serial breakout board portion of the [Arduino breadboard tutorial][1] and apply it to your board.

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


body:
The Arduino Severino (Single Sided Serial version 3 - S3V3rino) is designed to work with RS-232 serial interface, not with the TTL serial signal levels of your FT232 board.

So, to use your FT232 board to connect your Severino to a USB port, you'll need connections like those in the schematics below:

![Serial TTL to ATmega328 schematics][1]

So, basically you need these connections:

      FTDI |  ATmega328           | Arduino Severino
    ----------------------------------------------------
      DTR  |  Pin 1 (thru cap C6) | RESET (thru cap C6)
      RXI  |  Pin 3               | TX (D1)
      TXO  |  Pin 2               | RX (D0)
      VCC  |  Not connected       | Not connected
      CTS  |  Not connected       | Not connected
      GND  |  Pin 8 & 22          | Ground

That's basically the same Majenko suggested (but with a picture added).

I'm not sure you can make these connections directly into the Severino without damaging the board or anything else. You'll probably need to cut the TX/RX traces that go from the ATmega328 to the DB9 female connector on the Severino and wire them to the FTDI header pins.

Best would be to modify the Severino EagleCAD schematics to remove all the RS-232 circuitry and replace it by TTL connector as shown in my schematics above and, with that, etch and assembly a new board. It's a lot of work, but can be done.

I hope this helps.

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


message:
Understanding arduino shield schematics

I am researching the schematic of the arduino GSM shield.
Link is this:
https://www.sparkfun.com/datasheets/DevTools/Arduino/cellular shield-v12.pdf

What i do not understand is the upper right part, wich says ARDUINO_SHIELDNOHOLES.

What i want to do is understand which pins are used for Rx and which for Tx.

But there are four usable pins on the arduino side and six(?) pins on the other side which says jumper, where are six pins on seeminly two jumpers...

Can anyone understand what is going on here?

body:
"ARDUINO_SHIELDNOHOLES" is a connector in the SparkFun EAGLE libraries which is basically, well, an Arduino shield. It provides the schematic symbol as well as the PCB landing pattern for such.

The pins on the top right of the schematic are two sets of 3, which should have jumpers connecting either 1 and 2, or 2 and 3. To use hardware serial to connect the Arduino to the SM5100B you connect 2 and 3 of the "top" one and 1 and 2 of the bottom one. This connects D0 (RX) and D1 (TX) of the Arduino to TXD0 and RXD0 of the SM5100B. If you want to use software serial instead, connect the other pairs. D2 will then be connected to TXD0 (and will become the software RX), and D3 will be connected to RXD0 (and will become the software TX).

As for "TXD0" and "RXD0" themselves, those are **net names**, and all wires with the same net name, such as those and the ones connected to pins 19 and 20 of the SM5100B, are considered to be the same wire even if they aren't connected in the schematic.


body:
A lot of good shields will give you the option to use hardware or software serial, and that is what's happening here.

While you think you see four pins on the arduino side and six on the jumper side, what you're actually seeing is (yes) the four pins on the arduino, but those four pins go to four pins on the jumpers.

The other two pins on the jumpers (the ones in the middle) go to the TX and RX of the shield. The shield itself only has one TX (`TXD0` pin 2 on `JP4`) and one RX (`RXD0` pin 2 on `JP6`). So the jumpers form the connection between your arduino and the shield. This is why they are the middle pins, because you put the jumper on the first two, or the last two, depending on what it is you want to achieve.

You will note the net names of pin 2 of `JP4` and `JP6` relate directly to (and are connected to) pin 19 and 20 respectively of the chip on the shield.

The whole benefit of the jumpers is you connect `JP4` and `JP6` pins 1 and 2 to which closes the circuit and uses the inbuilt hardware serial (pin 1 of the jumper being arduino hardware and pin 2 being the `TXD0` source from the shield). Connecting pins 2 and 3 means you close the circuit between the shields TX and RX to the arduino GPIO pins `D2` and `D3` which you can assign when initialising your software serial.


message:
Arduino diy wireless

Is it possible to do simple wireless on an Arduino, digital, or analog (SDR)? I would like to hook one pin to an antenna (or piece of wire) and generate signals with simple modulations (analog or digital).

body:
[here][1] there's a nice tutorial on how to obtain it.

Basically it sets the registers so that a pin outputs a PWM signal at 800 kHz and then modulates that signal in code by just switching the pin and off (pinMode set to INPUT or OUTPUT). If you plug a cable (20 cm and on) to pin 8, and tune your radio to 800Khz you'll hear some noise going on and off.

If you read down the forum you'll see people suggesting how to actually send tones, by putting a very small delay (delay(1)) between the on/off of the pin.

[In this link][2] they guys have ogn further and they even implemented a morse code library.

Now I am trying to figure out a way to do the same for a receiver.

  [1]: https://forum.arduino.cc/index.php?topic=88422.0
  [2]: http://mateslab.weebly.com/am-radio-broadcasting-with-arduino.html


message:
ATMega32u4 (Leonardo) Serial Baud Rate

Does anyone know what the actual baud rate that the CDC Based virtual serial port on the Leonardo runs at is? Serial::being() for the CDC version is just empty, so it's not setting a baud rate anywhere.

Basically, I'm debating between using the 32u4 or the 328p with an FTDI chip and trying to figure out if the 32u4 will be slower... since it uses a virtual COM port I'm assuming it is, but I'd be happy if I was wrong :)

body:
I'm not sure if the concept of an "actual baud rate" is really meaningful in a pure USB connection.

In my experience, the 32u4 is faster than the 328p at serial-heavy tasks. There is no intermediate chip, and USB has much larger hardware buffers than the serial port does. I don't know how much processing you're planning to do on your data, but I would expect that a 32u4 can process serial data pretty much as fast as you can generate/process it.

On the host side, it seems to me that there is very little difference in whether the "virtual COM port" has an FTDI or a 32u4 on the other end, so I don't see why one should be faster than the other (though admittedly they go through different device drivers).


message:
What background do I need to have before starting Arduino?

Like: basics of electrical circuits, etc..

In order to go far in Arduino and electronics.

body:
I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.

The end result is that he is the one showing me new stuff.

In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.

Good luck


body:
You need a basic understanding of programming because you will need to program in C++.
You need basic computer literacy, but I bet you've got that if you are on this website.
You need some understanding of electronics, such as a High-School level textbook. You need to understand resistors, diodes, voltages, current etc. Otherwise you'll get very frustrated.


body:
You need to learn some absolute basics about electronics so you don't fry your arduino. (Don't exceed the current limits on the i/o pins. How to use Ohm's Law to calculate current. How to tie inputs to ground with a resistor. How to tie inputs to +5 through a resistor.  How to estimate the total current load of your entire circuit to make sure it doesn't overload the +5 regulated power from the Arduino. Basic precautions against static electricity.)

Beyond that, it makes a great learning tool, and you should be able to learn as you go. Build the sample projects that are on the Arduino website.

You might want to buy a book on logic circuits. I read "The CMOS Cookbook" years ago, and it gave me a good strong grounding.

You'll also want to learn programming, since you need to use C or C++. Again, though, you can use the Arduino as a learning tool. Looking at the sketches from the website and modifying them will help you learn.


message:
Arduino core for ATMega16u2

I've looked around a ton so it's probably not available but does anyone know if there is a usable core for the ATMega16u2 (the chip the Uno and Due uses for USB to Serial). I have a project I was going to use the 32u4 for but they aren't really available for several months and the 16u2 has all the functionality that I would really need.

body:
As @IgnacioVazquez-Abrams said, a 16u4 is virtually identical with a 32u4, so you can use a Leonardo or Micro core with a tiny modification to boards.txt. A 16u2 is a rather different animal, with fewer timers, many fewer pins, and no A/D converter, so you’d have to do a fair amount of editing to obtain a usable Arduino core.

That said, if you’re reasonably fluent in C++, building your own Arduino core is not very difficult, and I found it an instructive exercise. If you care about getting your project up as quickly as possible and not get sidetracked, however, go with the 16u4.


message:
How can I send serial over RF?

I've got the following:

    #include <SoftwareSerial.h>

    const int rx = -1;
    const int tx = 4;

    SoftwareSerial mySerial(rx, tx);

    void setup()
    {
      mySerial.begin(2400);
      pinMode(tx, OUTPUT);
    }

    void loop()
    {
      if(mySerial.available())
      {
        String data = "Hello World";

        for(int k = 0; k < data.length(); k++ )
        {
          mySerial.write(0xAA);
          mySerial.write(data[k]);
        }

        mySerial.write(0xA9);
      }

      delay(1000);
    }

Which I'm trying to send to to a [RF transmitter module][1]. It all compiles just fine, but am I forgetting something? And does pin 4 = physical pin 3?

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

body:
First off, are you trying to send to the 433MHz transmitter? This will not work.
If you mean you are using the 433MHz transmitter to send data to a receiver, the VirtualWire.h library work.

If you are using another transmitter please add more info on the transmitter used in this project.

HumanHarddrive on youtube got a tutorial on the DX transmitter and receiver.
[Tutorial][1]

  [1]: http://www.youtube.com/watch?v=e8RhXtst7ME


body:
In your loop function you have:

    if(mySerial.available())
    {
      String data = "Hello World";

      for(int k = 0; k < data.length(); k++ )
      {
        mySerial.write(0xAA);
        mySerial.write(data[k]);
      }

      mySerial.write(0xA9);
    }

The `available()` function returns the number of bytes available in the receive buffer. You say your module is a transmitter, so there will never be any data to receive (I can see the module doesn't even have a tx pin). Hence you will never transmit any data.

That said it's not a good idea to send data plain over wireless. It might work to some extent, but you'll likely get much more lost data. Look at the virtual wire library or google "manchester coding" if you wan't to roll your own.


message:
Arduino standard libraries location

I want to read the source code of an arduino library that comes with the IDE.
Specifically the GSM.h

I dont know the location of the standard libraries that come with the IDE.

I only know the location of the user installed libraries.

So where is the source code of GSM.h?

body:
Ok, i found out the location.
In Win 7, it is C:\Program Files (x86)\Arduino\libraries


message:
Buffering data from EthernetServer clients

I was trying to write a Telnet server that would be able to accept commands of sorts using the Arduino Ethernet library, and in order to access what the client was saying (to compare it to strings to check what command the client entered), I made a buffer string that would read until `\n`, which is part of the standard Telnet library. However, the string would never get printed to the serial connection (just for debugging purposes). Here's my code:

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xFE, 0xED };  // this client's MAC address

    EthernetServer server(23);  // telnet is 23
    boolean alreadyConnected = false;

    void setup() {

      Ethernet.begin(mac);

      server.begin();  // open the socket

      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial to start, Leonardo only
      }

      Serial.print("Connect to ");
      Serial.print(Ethernet.localIP());
      Serial.println(":23.");

    }

    void loop() {

      EthernetClient c = server.available();

      if (c) {
        String messageBuffer = "";

        if (!alreadyConnected) {
          c.flush();
          Serial.println("New client");
          c.println("test post, please ignore");
          alreadyConnected = true;
        }
        if (c.available() > 0) {

          char thisChar = c.read();

          //server.write(thisChar);

          //buffer until the client sends a new line
          if (thisChar == '\n') {
            Serial.println(messageBuffer);
            messageBuffer = "";
          } else {
            messageBuffer += thisChar;
          }
        }
      }
    }

Most of this code was copied from the Telnet chat server example, but I changed the `Serial.write(thisChar)` line, because I wanted to put it into a string first. When this is run, and a user `telnet`s to the IP, the Arduino prints `New client`, but when the user sends data, it doesn't print anything.

Any suggestions for what I'm doing wrong?

body: Well, I asked on the #arduino IRC channel, and realized my stupid mistake. I was setting the buffer to `""` **inside** the loop.


message:
Cheap medium range wireless communication with a linux PC

I have a project that's currently using Arduino Uno with a cheap class-2 bluetooth serial adapter from ebay to send and receive data and control a LED light strip.

However, it struggles to establish connection at distances more than couple meters. I'd like to expand that range a bit - 15 meters with two load-bearing walls in the way. Bandwidth requirements are next to none - it should just move couple integers around.

Any suggestions how to do that on the cheap? From what I've seen, class-1 bluetooth adapters go for ~60$, two xbee modules + usb adapter end up costing even more, and wifi solutions seem to reside in the same price range. At that price point, it seems better to get a raspberry pi, wifi dongle and a couple beers for the software re-write. Am I overlooking some solution?

body:
Since one end is a PC I would look into a Wifi shield for the arduino. That way you would not need any extra hardware on the PC side.

You can get a Wifi shield for less than 2 xbee modules. But using wifi will require changes to your code since it won't be using the serial port for communication.

Another wireless option that I have no personal experience with is [NRF2401](http://playground.arduino.cc/InterfacingWithHardware/Nrf2401) modules -- you can get them dirt cheap on ebay (caveat emptor) but they use an SPI interface so you can't directly interface with them directly on the PC side.

Be aware that depending on the LED strip you may not be able to drive it directly from a raspberry pi.  For example WS2811 driven LEDs (AKA adafruit NeoPixels) need precise timing that you can't get (or is tricky to get) with the raspberry pi.


body:
"[Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu](http://www.instructables.com/id/How-to-set-up-OpenWRT-on-a-pocket-router-WR703N/)" may lead you to some answers...

Just think of that solution as a kind of "homegrown Arduino YÙN"... just older and cheaper: "[Nah, you don’t need an Ethernet module for your Arduino](http://hackaday.com/2012/06/12/nah-you-dont-need-an-ethernet-module-for-your-arduino/)"


message:
What pins should I use when blinking AtTiny13 with arduino IDE?

I'm trying to program AtTiny13 using Arduino IDE. I have connected the atTiny to my PC using USBasp programer.

I want to write a simple blink application to test whether it works or not. Which pins should I blink?

body:
You'll need an Arduino library that supports that chip, to make it appear in the Tools > Board list.  The library docs will tell you which pins then correspond to which Arduino digital I/Os. From that you can decide which pin to attach an LED to (with resistor) and how to edit the blink sketch.

Example: http://www.instructables.com/id/Pimp-Your-Chocolates-with-Arduino-IDE-and-ATtiny13/step2/Program-the-ATtiny13/


body:
Because pins 0 and 1 (physical 5,6) are PWM's you should keep them for later ...
and you still have A3 and A2 for analogWrite so,
you should use Pin 2 (Physical 7, next to +5V) like this :

add this in the setup function

    pinMode(2, OUTPUT);

And add this in your loop function:

    digitalWrite(2,HIGH);

![In case you forget][1]

For reference :
[SparkFun's Help guide][2]

  [1]: https://i.stack.imgur.com/GwRJ9.png
  [2]: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/attiny85-use-hints
Remember : Physical pin "1", reset, has a dot  marked on it.


message:
How to add the -F switch for avrdude in Arduino IDE

So, before starting to learn with something else, I'll give it one last try. The avrdude is complaining that the device signature doesn't match. Whatever, I don't care. To me, what's written on it is what counts.

So I'd like to force it to upload the program. It promises to ignore the problem if `-F` is specified.

Where are settings for avrdude parameters, like other IDEs have settings for their compilers?

body:
The error probably means that you have selected a wrong configuration.

To modify the IDE to insert the `-F` seems to be the hard way,
however the easy way is to make a wrapper to `avrdude`:

    $ cd ./arduino/hardware/tools/
    $ mv avrdude avrdude.orig
    $ cat >avrdude.sh
      #!/bin/sh

      ./avrdude.orig -F $@
      ^D
    $ chmod +x avrdude.sh
    $ ln -s avrdude.sh avrdude


message:
Best Arduino board to play sound

I'm looking to purchase an Arduino for a little robot I'm going to make.  The reason I've chosen Arduino is because it's much easier to use with servos and LEDs than a Raspberry Pi, but a nice little touch would be to have it play some sounds (voice recordings and mechanical SFX).  I was just wondering (now I'm not after opinions here, but looking more at how each of the boards have been designed) what the *best* Arduino board for playing sound is, or if they are all pretty much the same in this regard.

(Note 'pins' was the best tag I could find for this post for lack of a 'sound' or 'speakers' one.  If you want to edit it to something more appropriate please do)

body: If all you need is to play back lo-fi audio then any with PWM will do, which means that any Arduino will do. If you want hi-fi sound then you'll need a DAC, which means either choosing the Due or using a discrete DAC via SPI. If you need decoding of complex audio formats such as MP3 or Vorbis then you'll need either the Due for its power, or a separate audio playback shield that supports the formats you're interested in.


message:
Mac Power via Keyboard Shortcut?

many mac keyboards have a power button. Is there a way to mimic this power button shortcut from an arduino?

body:
There are multiple ways to do that.

 - You could use an Arduino Leonardo as a keyboard, then send a shortcut command to shut down or sleep the computer. You can edit these from System Preferences>Keyboard>Shorcuts>Services.
The keycode 0x66 does not work for mac, but may for other operating systems [source][1]

 - You could write a small program (I'd do it in Python) which communicates with the Arduino over the serial port and shuts down the Mac if the Arduino wants it to.

 - You could sacrifice an USB keyboard and use a relay to "press" the power key.

[1]: http://joshfire-tech.tumblr.com/post/65032568887/arduino-keyboard-emulation-send-real-key-codes


message:
Frequency will not change

I am working on a project where I am trying to get an input signal filtered according to its frequency. I checked the signal before it went into my DSP algorithm to see where the problem was and I found that the frequency was remaining the same no matter if I put in 30Hz 120Hz or 58kHz. This leads me to think I have a problem with the sampling rate. Does that sound like it is the actual issue? Or am I barking up the wrong tree?

I was just using the readADC command to read in the data

    void setup()          //Setup Function to intialise ADC and Serial Communication
    {
    DDRC=0x00;            //PORTC as INPUT
    DDRD=0xFF;            //PORTD is OUTPUT
    DDRD=0xFF;
    for(i=0;i<N;i++)
      {
        InitADC();
        a=ReadADC(4);
        x[i]=a;
      }
      Serial.begin(9600);
    }

body:
I am not sure how you are sampling the frequency because you have not shown us your code.

At work we use a ATMega328P to sample frequency. This is done in 2 different ways:

 1. We use the pin that counts (using an internal counter) every time it transitions (ie from low to high and from high to low). After 1 second that counter is read and then that counter is cleared. With the number read in, it is divided by 2 to get the frequency.
 2. We use another pin that counts every time it transitions from low to high. From memory the counter is not very large so we count the number of times it overflows. When the 1 second interrupt fires we multiply out the number of overflows by the counters capacity. Lastly the remainder from the counter is added to the result to get the frequency. Again the counter is cleared.

The above examples use the AVR's internal counters. A less efficient way of getting the frequency is to have an interrupt to count the number of times a pin changes. Again this can be read and reset at one second intervals. This slows the overall execution of the program down when very high frequencies ( > 40K Hz) are being presented on the input.


message:
Bluetooth Master and Slave to track device's locations

I'm trying to create an app for my science fair that uses bluetooth to track people in a determined place.
I was thinking about one Arduino system to receive all the information and transmit through a network and some Arduino slaves to duplicate the signal and cover the hole place.

**Resuming...**

I'll have:

 1. Arduino slaves placed all over the place to track people
 2. One Arduino connected to the network to receive all the information from the slaves and pass it through the network.
 3. Some kind of web app inside the main Arduino with an API to manage the data and make it friendly for third-party apps

I was wondering of what kind of equipment should I buy to make this happen. Thanks!

----------

Each cellphone with it's bluetooth enabled will work as a person (sending signal) - my Arduino slaves will receive the signal (find bluetooth around it) and send the device name and signal strength to the arduino master - The arduino master (connected to the network) will interpenetrate the responses and send the results to the built-in web server - Apps will make requests to the web app to get this data and show in a plant where're these people.

Basically it will work like these bluetooth stickers that you can plug in to your keys, phone e etc... and with the app you can search for them in your house via bluetooth from your cellphone.

Here's a better explanation:
[Link][1]

  [1]: http://electronics.howstuffworks.com/bluetooth-surveillance.htm

body: Bluetooth generally support only one to one connection. Atmost 6 bluetooth can be connected to single module in latest bluetooth version(the basic model probably used by you connects only 1 device). Hence it is not a good idea to use bluetooth. Also if you need a web based platform you should switch to some more powerful platform like raspberry pi, beagle bone etc.


message:
Is there some sample code for operating a servo with an Adafruit Motor Shield?

I have an [Adaruit Motor Shield v2][1], and a [Tower Pro SG92R micro servo][2]. I've got it setup so the shield works with my Arduino Uno, and I've successfully tested using other types of motors on the shield. I could not find any sample code for working with a servomotor though. The shield has two dedicated spots for a servo (labeled "Servo 1" and "Servo 2"). I'm planning to use wall wart transformer to power the motor separately from the Arduino. Any pointers/links to documentation/sample code would be appreciated.

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/
  [2]: https://www.adafruit.com/products/169

body:
On the Motor shield the servo headers are directly connected to pins 9 and 10 (I think 9 is servo 2 and 10 is servo 1).  So you can use the standard servo examples using pins 9 and 10.

If you need to power the servos with an external power supply you must cut a trace on the back of the board -- the silk screen tells you where to cut.  Then you need to connect power to the "Opt Servo" input.

The power to the servos is not changed by the power jumper used for the DC/stepper motors.


message:
Need some help with controlling a fan through PWM

So lately I've been trying to control the speed of a 120mm 4-pin computer fan using PWM. This is what I've got so far, with the part above void loop() being from [this thread](http://forum.arduino.cc/index.php?topic=109403.0)

    // Definition of Arduino type
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    #define  IS_MEGA  (1)
    #define  IS_UNO   (0)
    #else
    #define  IS_MEGA  (0)
    #define  IS_UNO   (1)
    #endif

    // Analog output (i.e PWM) pins. These must be chosen so that we can change the PWM frequency without affecting the millis()
    // function or the MsTimer2 library. So don't use timer/counter 1 or 2. See comment in setup() function.
    // THESE PIN NUMBERS MUST NOT BE CHANGED UNLESS THE CODE IN setup(), setTransistorFanSpeed() AND setDiodeFanSpeed() IS CHANGED TO MATCH!
    #if IS_UNO
    // On the Uno we can only use the OC1B pin, so these pin numbers are both 10
    const int transistorFanPin = 10;     // OC1B
    const int diodeFanPin = 10;          // OC1B
    #else
    // On the Mega we use OC1B and OC1C
    const int transistorFanPin = 12;     // OC1B
    const int diodeFanPin = 13;          // OC1C
    #endif

    // Definitions for PWM fan control
    const unsigned char maxFanSpeed = 80;   // this is calculated as 16MHz divided by 8 (prescaler), divided by 25KHz (target PWM frequency from Intel specification)

    void setup()
    {
      // Set up the PWM pins for a PWM frequency close to the recommended 25KHz for the Intel fan spec.
      // We can't get this frequency using the default TOP count of 255, so we have to use a custom TOP value.

    #if IS_UNO

      // Only timer/counter 1 is free because TC0 is used for system timekeeping (i.e. millis() function),
      // and TC2 is used for our 1-millisecond tick. TC1 controls the PWM on Arduino pins 9 and 10.
      // However, we can only get PWM on pin 10 (controlled by OCR1B) because we are using OCR1A to define the TOP value.
      // Using a prescaler of 8 and a TOP value of 80 gives us a frequency of 16000/(8 * 80) = 25KHz exactly.
      TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << WGM11) | (1 << WGM10);  // OC1A (pin 9) disconnected, OC1B (pin 10) = inverted fast PWM
     #ifdef FAN_AUDIO_TEST
      // test code to get 440Hz output (= concert A) to test the logic
      OCR1AH = 0;
      OCR1BL = 71;  // 50% duty cycle
      TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);  // TOP = OCRA, prescaler = 256

      OCR1AL = 141; // TOP = 141, 16000000 / (256 * 142) = 440.014
      OCR1BH = 0;
     #else
      OCR1AH = 79;
      OCR1AL = 0;  // TOP = 79
      TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR0A, prescaler = 8

      OCR1BH = 0;
      OCR1BL = maxFanSpeed;  // max fan speed (i.e. pin 5 initially low all the time)
     #endif

      TCNT1H = 0;
      TCNT1L = 0;
    #else

      // On the Mega we use TC1 and OCR1B, OCR1C
      TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << COM1C1) | (1 << COM1C1) | (1 << WGM11) | (1 << WGM10);  // OC1A disconnected, OC1B = OC1C inverted fast PWM
      TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR1A, prescaler = 8
      TCCR1C = 0;
      OCR1AH = 0;
      OCR1AL = 79;  // TOP = 79

      OCR1BH = 0;
      OCR1BL = maxFanSpeed;
      OCR1CH = 0;
      OCR1CL = maxFanSpeed;

      TCNT1H = 0;
      TCNT1L = 0;
    #endif

      // We have to enable the ports as outputs before PWM will work.
      pinMode(transistorFanPin, OUTPUT);
      pinMode(diodeFanPin, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
    }

    // Set the transistor fan speed, where 0 <= fanSpeed <= maxFanSpeed
    void setTransistorFanSpeed(unsigned char fanSpeed)
    {
      OCR1BH = 0;
      OCR1BL = fanSpeed;
    }

    // Set the diode fan speed, where 0 <= fanSpeed <= maxFanSpeed
    void setDiodeFanSpeed(unsigned char fanSpeed)
    {
    #if IS_UNO
      OCR1BH = 0;
      OCR1BL = fanSpeed;
    #else
      OCR1CH = 0;
      OCR1CL = fanSpeed;
    #endif
    }

    void loop() {
      if (analogRead(A0) >= 800) {
        setTransistorFanSpeed(80);
        Serial.println("HIGH");
        Serial.println(analogRead(A5));
      } else {
        setTransistorFanSpeed(0);
        Serial.println("LOW");
        Serial.println(analogRead(A5));
      }
      delay(100);
      Serial.println("I'm running.");
    }

In the serial monitor I'm getting the output I'm expecting ("HIGH" and 1023 when I've bridged the arduinos 5V pin to A0), but the signal doesn't seem to have any effect on the fan at all. In the thread linked above there's talk about this being an inverted fast PWM signal, and that it's assumed I'm using an opto isolator. Could this be why the signal doesn't have an effect on the fan? If anyone out there has any experience on this and are able to help me, that would be greatly appreciated.. :)

body: You need to connect the ground of the fan (/12volt power-supply) to the ground of the Arduino. If you don't connect the grounds, there is no path for electrons to flow.


message:
MCP7940 RTC Library

I am looking to implement a Microchip MCP7940 real time clock into my sensor data logging circuit that I have based on the Uno. Would the most logical solution be to attempt at changing an existing library to work with this clock (ie [RTClib][1]), or to begin from scratch and do the configuration directly in my program?

  [1]: https://github.com/jcw/rtclib

body:
In case anyone comes looking for an answer to this question, here is my solution:

I started with the excellent library by jeelabs (link: https://github.com/jcw/rtclib)

To create my new library, I changed a few of the register addresses, and added the few functions that I wanted it to do (set alarm, create an ordinal date, manually adjust the time with user input)

I posted my code to a Git project: https://github.com/crako1t/MCP7940-library-for-logger.git


message:
Clear existing array when getting new serial command

I'm starting to build my first Arduino project but I'm running into some problems with serial communication.

I get serial data from the console and store it in a char array called "data".

Then, when I send a new console message to the Arduino, I want it to clear the existing "data" array and store only the new data in that array.

I don't understand exactly what's wrong with my code: I believe those nested Serial.available() statements don't work but I have no ideas on how to fix the code.

Data is correctly stored by the Arduino but it concatenates the newer string to the old one.

    int count = 0;
    char data[30];
    boolean dataComplete = false;

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

    void loop() {

      if (Serial.available() > 0){
        if (dataComplete == true){
        Serial.println("There is data already, clearing...");
        char data[30];
        dataComplete = false;
      }
        if (dataComplete == false){
          Serial.println("New command, collecting...");
          while (Serial.available()>0){
            char character = Serial.read();
            data[count] = character;
            count++;
          }
         dataComplete = true;
        }
      }
      Serial.print("Command received: ");
      Serial.println(data);
      delay(1000);
    }

Thanks in advance!

body:
This probably doesn't do what you intend it to do:

    Serial.println("There is data already, clearing...");
    char data[30];

Your output says you are clearing the `data` array, but you're doing no such thing. In fact, you are declaring a *new* local variable called `data`, which is independent of the global `data` you already have declared at the top of your program. Local variables only exist within the scope in which they are declared (inside their nearest enclosing `{ }`).

Instead, your `count` variable keeps track of how much data you have received. So perhaps do the following:

    Serial.println("There is data already, clearing...");
    count = 0;

This is not the only thing that might cause your program to operate unexpectedly, but it should at least fix the problem stated in your question.


body:
First of all, this is an *excellent* example why whitespace matters. Your code is really hard to read as it is, as skimming over it, it seems as the second if statement is outside of the first one.

Fixed code:

    int count = 0;
    char data[30];
    boolean dataComplete = false;

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

    void loop() {
      if (Serial.available() > 0){
        if (dataComplete == true){
          Serial.println("There is data already, clearing...");
          char data[30];
          dataComplete = false;
        }
        if (dataComplete == false){
          Serial.println("New command, collecting...");
          while (Serial.available()>0){
            char character = Serial.read();
            data[count] = character;
            count++;
          }
         dataComplete = true;
        }
      }
      Serial.print("Command received: ");
      Serial.println(data);
      delay(1000);
    }

Also, it seems as it prints "Command received:" every iteration, regardless of if there's new data or not (although, this could be the intended feature).

Like mentioned, you don't *clear* the variable, you just create a new one. You'll need to clear *and* reset `count` to fix this issue. However, just resetting count won't work if the second command is shorter than the one before.

Also, why do you complicate the code with the `dataComplete` variable? I simplified the code below:

    int count = 0;
    char data[30];
    boolean dataComplete = false;

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

    void loop() {
      if (Serial.available()){
        Serial.println("New command, collecting...");
        count = 0;
        data[] = "";
        while (Serial.available()){
          char character = Serial.read();
          data[count] = character;
          count++;
        }
      }
      Serial.print("Command received: ");
      Serial.println(data);
      delay(1000);
    }


body:
To clear an array you would do:

    for( int i = 0; i < sizeof(data);  ++i )
       data[i] = (char)0;

or

    memset(data, 0, sizeof(data));

, which does the same thing using a library function.

However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:

    data[0] = (char)0;

will do it.


body:
To speak to the point of the question, and what the author was attempting to accomplish.

None of this code actually works as a whole. The data would get over written and just keep looping continuously... anyway here is a working example of the original code.

This method I prefer to clear an array:

        for( int i = 0; i < sizeof(data);  ++i )
        data[i] = (char)0;

Here is working example. ( Make sure to select Carriage Return on the serial monitor )

        char message[32];
        uint8_t incomingByte = 0;
        uint8_t BufferPos = 0;
        int clearbyte = 0;

        void setup() {
        Serial.begin(9600);
        Serial.println("\n String conversion testing");

        }

        void loop() {

           if (BufferPos >= 32) {
                  Serial.print("Buffer Full\n");
                  BufferPos = 00;
                  incomingByte = 0;

           }

          if (Serial.available()) {
                 incomingByte = Serial.read();
                 message[BufferPos++]= incomingByte;

             switch(incomingByte)
          {
               case '\n':
               case ' ':
                 break;
               case '\r':
                  Serial.println(message);

              for( int i = 0; i < sizeof(message);  ++i )
             message[i] = (char)0;
                  BufferPos= 0;
                  incomingByte= 0;

          }
          }
        }


body:
I was read all comments on this question, but all codes was share so verbosing. After that, i create a code with simple functions and less of line. in this case, i think this code will working fine

if you set baudrate under 115200, must be add delay() for saving message to char array

    void loop() {
        char data[255];
        uint8_t k = 0;
        while (Serial.available()) {
            data[k] = Serial.read();
             k++;
        }
        for (int i = 0; i < k; i++) {
            Serial.print(data[i]);
            data [i] = '\0';
        }
        //delay(50);
    }


message:
Arduino IDE crashes without any warning

I'm a beginner in Arduino. I just installed Arduino IDE (arduino-1.0.5-r2-windows) but when I try to run its not responding and crashes after few minutes. I tried re-installing it and removing the temporary files but none of those helped.

Can anyone tell me what causes this problem and how to debug it?

body: Installing Arduino 1.5.6 solved the issue.


message:
How is stack memory used for fuctions and local variables?

I wanted to save some values to the EEPROM and also wanted to free up SRAM by avoiding some variable declarations, but EEPROM memory is byte wise.

If I want to store an int value, I have to use some expressions repeatedly. I thought I would make some functions for those. But I am concerned that, if I create a function, it would still occupy SRAM memory, better I declare an int variable instead of using EEPROM.

How are the functions and the local variables stored in SRAM? Does it only store the address of the fuction pointer from the flash memory or all the variables and commands are stored on the stack?

body:
Only the function's data is stored on the stack; its code stays in flash.
You can't really reduce SRAM use by using EEPROM instead because, as you have seen, EEPROM isn't addressable in the same way. The code to read and store EEPROM also needs to use some SRAM - probably as much SRAM as you were trying to save! EEPROM is also slow to write, and has a limited lifetime (in number of writes to each byte), both of which make it impractical to use for storing the kind of temporary data we usually put on the stack. It is better suited to saving infrequently changed data, like the unique device configuration for mass-produced devices, or capturing infrequent errors for later analysis.

**Edited:**
There is no stack for that function _until_ the function has been called, so yes, that is when any of the function's data get's put there. What happens after the function returns is that its stack-frame (its reserved area of SRAM) is no longer reserved. It will eventually be re-used by another function call. [Here is a diagram][1] of a C stack in memory. When a stack frame is no longer useful, it is simply released and its memory becomes available to be re-used.

  [1]: http://www.kriha.de/docs/lectures/operatingsystems/cruntime/foil09.html


body:
Local variables and function parameters are stored on the stack. However, that is not a reason not to use them. Computers are designed to work that way.

Stack memory is only in use while a function is active. As soon as the function returns, the memory is freed. Stack memory is a GOOD Thing.

You don't want to use recursive functions with lots of levels of recursion, or allocate lots of large structures on the stack. Normal use is fine however.

The 6502 stack is only 256 bytes, but the Apple II works just fine.


body:
The AVR (the microcontroller family traditionally used on Arduino boards) is a [Harvard Architecture](http://en.wikipedia.org/wiki/Harvard_architecture), meaning that executable code and variables are in two separate memories - in this case flash and SRAM. The executable code never leaves flash memory.

  When you call a function the return address is usually pushed to the stack - the exception is when the function call happens at the end of the calling function. In this case the return address of the function that called the calling function will be used instead - it is already on the stack.
  Whether any other data is put on the stack depends on the register pressure in the calling function and in the called function. Registers are the working area of the CPU, the AVR has 32 1-byte registers. The registers can be accessed directly by CPU instructions, whereas data in SRAM will first have to be stored in registers. Only if arguments or local variable are too big or too many to fit in registers will they be put on the stack. However, structures are always stored on the stack.

You can read the details of how the stack is used by the GCC compiler on the AVR platform here: https://gcc.gnu.org/wiki/avr-gcc#Frame_Layout
Read the sections "Frame Layout" and "Calling Convention".


body:
Immediately upon a function call entering the function, the first code that is executed is to decrement the stackpointer by an amount equal to the space required for temporary variables internal to the function. The brilliant thing about this is that all functions therefore become re-entrant and recursive, because their variables are built on the calling program's stack.
That means if an interrupt halts execution of one program and transfers execution to another, it too can call the same function without them interfering with eachother.


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

I've been trying quite hard to make an example bit of code to demonstrate what the excellent answers here are saying, without success so far. The reason is that the compiler aggressively optimizes things. So far my tests have not used the stack at all, even with local variables in a function. The reasons are:

---

* The compiler may **in-line** the function call, thus the return address might not be pushed onto the stack at all. Example:

      ```void foo (byte a)
          {
          digitalWrite (13, a);
          }
        void loop ()
          {
          foo (5);
          }
       ```

    The compiler turns that into:

       ```void loop ()
          {
          digitalWrite (13, 5);
          }
       ```

    No function call, no stack used.

---

* The compiler may pass arguments in **registers**, thus saving it having to push them onto the stack. Example:

    ```digitalWrite (13, 1);```

    Compiles into:

    ```158:  8d e0         ldi r24, 0x0D ; 13
    15a:  61 e0         ldi r22, 0x01 ; 1
    15c:  0e 94 05 01   call  0x20a ; 0x20a <digitalWrite>
    ```

    The arguments are put into registers and thus no stack is used (apart from the return address for calling digitalWrite).

---

* Local variables may well be put into registers, again saving having to use RAM. This not only saves RAM but is faster.

---

* The compiler optimizes away variables you don't use. Example:

     ```void foo (byte a)
       {
       unsigned long bar [100];
       bar [1] = a;
       digitalWrite (9,  bar [1]);
       }
     void loop ()
       {
       foo (3);
       }  // end of loop
     ```

    Now that's **got** to allocate 400 bytes for "bar" doesn't it? Nope:

      ```00000100 <_Z3fooh>:
       100: 68 2f         mov r22, r24
       102: 89 e0         ldi r24, 0x09 ; 9
       104: 0e 94 cd 00   call  0x19a ; 0x19a <digitalWrite>
       108: 08 95         ret
     0000010a <loop>:
       10a: 83 e0         ldi r24, 0x03 ; 3
       10c: 0e 94 80 00   call  0x100 ; 0x100 <_Z3fooh>
       110: 08 95         ret
      ```

    The compiler optimized away the **entire array**! It can tell that we are really just doing a `digitalWrite (9, 3)` and that is what it generates.

---

Moral of the story: Don't try to out-think the compiler.


message:
How to reset ATmega328P fuses using USBasp programmer?

I think I bricked two ATmega328Ps when I was trying to burn new bootloaders using Arduino Pro Mini, the USBasp programmer and the Extreme Burner AVR software. I had two ATMega328p with bad booloaders and I intended burn the correct bootloader to the chips.

First I connected the USBasp programmer to my Arduino Pro Mini equipped with an ATmega328P. I verified that communication was good as I could read and write to EEPROM. All was excellent.

I was using the following fuses:

LOW Fuse Byte=0x62
High Fuse Byte=0xD9
Extended=0xFF
Lock = 0xFF
Calibration = 0xFFFF FF8A
Then the following happened:

I killed the 1st chip when I only pressed button ERASE CHIP on the programmer.

I killed the 2nd chip when I wrote the following fuses to it:

LOW Fuse Byte=0xFF
High Fuse Byte=0xDA
Extended=0xFD
Lock Fuse = 0xCF
In both cases I had the following error message:

Cannot Communication with chip
Power On failed
avrdude output similar messages:

RC=-1. No answer...
(avrdude -c usbasp -p m328p -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m )
How can I solve this problem?

How can I reset all the fuses to factory default to make the chips respond again?

body:
As someone mentioned, the first chip you may be able to fix by passing -B10 to avrdude.  In order to program an AVR, the programmer has to be running at a slower speed than the chip you're programming is running.  The fuses you have set cause the chip to run at 1Mhz using the internal clock, and -B10 will cause it to go slower (the defaults are suitable for programming a chip that is running faster than 4MHz).

The second chip, the fuses are set to 8MHz using an external crystal, so in order to fix it, you'll need to hook up an 8MHz crystal, or use a high voltage programmer.

Good luck!


body:
Its possible you may have disabled the `SPIEN` or the `RSTDISBL` fuses. The only way to check and fix is to use a High Voltage Programmer like the STK500, STK600 or AVR Dragon and see. I have the AVR Dragon and it saved me a few times.

Also, do a search for [AVR Fuse Doctor][1]. Its a homemade fuse repair device. Pretty cool. But save yourself some time and invest in a programmer/debugger that has HVPP (high voltage parallel programming) and HVSP (high voltage serial programming). You won't regret it.

  [1]: http://mdiy.pl/atmega-fusebit-doctor-hvpp/?lang=en


body: Hi that happened to my Nano with atmega 328p using a usbasp programmer just checking the fuse settings to make a backup with out programming, the Extreme Burner AVR software caused the problem as it read the wrong device signature, it gave me 0x0f951e after disconnecting and trying my Nano 328p it would not work I do not use that software anymore and never had a problem with making backups with other software.


message:
What is the frequency of PWM output on Arduino

What frequency do Arduinos use for normal PWM when you use analogWrite()?

And is it different for different Arduino model? I'm interested specifically in the Mega 2560, but also want to know if it's consistent between models.

I've seen a passing references to the Arduino using 500 Hz, which seems really slow.

body:
The PWM signal is generated by timers on the AVR chips. Each timer can generate a PWM signal on two or three different pins. Each pin can have it's own duty cycle, but they share the PWM frequency. You can change the frequency of the PWM by changing the clock source for the timers. By default they use the CPU clock divided by 64, ie. they have their prescaler set to 64 by Arduino initialization code.
  To confuse things more there are two different PWM modes: fast PWM and phase correct PWM. In fast PWM the timer counts to 255, then overflows and starts over from 0 (256 different states). In phase correct PWM the timer counts to 255, then changes direction and counts downwards to zero, changes direction and so on (510 different states).

The Arduino Mega has 5 timers, timer0 - timer4. Because timer0 is also used for the millis and micros functions it uses fast PWM, whereas the other timers are configured for phase correct PWM. This results in different frequencies on different pins:

 - Pin 4 and 13, controlled by timer0:
   16 Mhz / 64 / 256 = 976.56 Hz

 - Other PWM pins, controlled by timer1-4:
   16 Mhz / 64 / 510 = 490.20 Hz

The calculation is: Clock / Prescaler / PWM mode number of states

The situation is the same for all other Arduino boards I know of, except they have less timers that connect to different pins.

You can change the PWM frequency by changing the timer prescaler. See this page: http://playground.arduino.cc/Main/TimerPWMCheatsheet

It is also possible to make the timers count to a different value than 255. On the 8 bit timers you will loose an output pin, but on the 16 bit timers you can use the Input Capture Register to define a TOP value. The input capture functionality is a feature rarely used in the Arduino community so you likely won't miss it.

The Arduino libraries only allow you to use 8 bit resolution, even on the 16 bit timers. If you want the higher resolution, you will have to write your own analogWrite, or use a library made for the purpose.
On the Arduino Mega timer0 and timer2 are 8 bit, while the rest are 16 bit.

By changing the mode of the 16 bit timers to make use of the full resolution, in combination with changing the prescaler and the TOP value, you can achieve a very wide range of PWM frequencies.

The maximum frequency you can achieve is clock / 4, by setting the prescaler to 1 and TOP to 3 in fast PWM mode - a lower value isn't allowed. This will give you a 4 MHz PWM with 2 bit resolution. It can be on 0%, 25%, 50%, or 75% of the time. A higher TOP value will give you a higher resolution at a lower frequency.

For a longer explanation read this [article](http://www.righto.com/2009/07/secrets-of-arduino-pwm.html) or refer to the [datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf).

Changing the prescaler, PWM mode, or TOP value for timer0 will mess with `millis()` and `micros()`.


message:
Arduino communicating back and forth with PHP server

I am researching to find the best method to work with in order to control the arduino from a web interface (hosted on a web server using PHP) and also sending data from arduino to webserver and save to mySql.

2 methods which I have found that a lot use are save the data to a text file or in the url.

Which is the best or are there any better methods?

body:
I would suggest your best bet would be to pass messages back and forth via JSON, via Get/Post http request.

So to send data, you send a POST request (to the PHP server) with your data in JSON in the content.  To get instructions, you send a GET request to the PHP server and get a contents field with JSON in it.


body:
Another method is to use MQTT. That's a protocol often used for embedded messaging. Find [here][1] the (one of the?) arduino client.

As a server you can install [mosquitto][2] either on the same system running the web server, or on a different one.

Than the communication logic with php will be done with [mosqitto-php][3]

advantages:

- decoupling the web server(s) from the arduino(s)
- lightweight protocol for the arduino
- easy interface with more applications (eg, storing data in mysql, independently of the web server, or any new in the future)

disadvantages:

- few more work setting up the mosquitto server.

  [1]: http://knolleary.net/arduino-client-for-mqtt/
  [2]: http://mosquitto.org/
  [3]: https://github.com/mgdm/Mosquitto-PHP


body:
Buy a uart wifi such as WiFly series chip. You can control e chip via UART AT command. The chip capable of sending http post get to/from a server.

See this guide as an example

http://the.machini.st/posts/35


body:
It sounds like your first need is a way to send the bytes back and forth.  A secondary question will be what that data should consist of (eg: text commands, binary commands, etc).  Let's tackle the "how" first.

You have described two dynamics to the communication between server and Arduino:

 1. The arduino "sends data to the server" where PHP code will save it
    to MySQL; if your Arduino can be an internet client (eg: has an
    ethernet or wifi interface), it could use GET or POST (or PUT) HTTP calls to
    php code.  GET is easiest, but normally GET calls shouldn't change the server, only
    query it -- but many people make exceptions for small devices and small
    amounts of data which can be encoded in the URL.

 2. The web server "controls the Arduino".  Unless the Arduino sets up
    an internet server, it is going to have to poll the web server from
    time to time to find out what it should do (ie: to be controlled).
    It can pretty easily use a GET to fetch some text which it can
    interpret.

I'm guessing that HTTP will be the easiest path for communicating, because you probably understand that if you are a PHP programmer, and because it can often get through firewalls more easily if that matters; but a simple TCP socket or UDP datagrams are also possible.

Once you can send blocks of bytes between the server and the Arduino, you can focus on what those bytes should contain.  That could be simple text commands, or some binary protocol, or even the MQTT protocol transactions that another answer references.  You haven't given enough info to help select the protocol and format, so I'm assuming you are mostly looking at this time for the method of communicating, as described above.  If you want to ask about the format of what to send back and forth once you have the data flowing, please make that a new question.  You can test the basics by just sending a "Hello" text string between server and Arduino.


body: If it's not too much data, a textfile as a database should suffice, if you want something more scalable; I'm quite impressed with node.js: http://weworkweplay.com/play/raspberry-pi-nodejs/


message:
Does Arduino run AC or DC

? Based on my small knowledge on the crystal in an arduino, it seems like AC makes sense. True? No?

body:
Have a look at this: http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf and try and have a guess.

I don't want to be nasty, but have you at least googled this? Google: "Arduino Power Source" and the first hit is http://playground.arduino.cc/Learning/WhatAdapter

It runs from USB as well as from an external power source.

To answer your question: DC


body:
As a general rule, any modern electronic device with computational ability has to use DC. The reason is that they use specific voltage levels to indicate binary/logical states (i.e. 0's and 1's).

In theory, an ideal DC supply (Direct Current) should provide a constant voltage. That allows the circuit to effectively turn it on an off to represent binary states. (In reality, there's no such thing as truly "off" though, because voltage is relative.)

However, the voltage from an AC supply (Alternating Current) is constantly varying. If you plot it on a chart, you should see a nice sine wave, flowing smoothly between positive and negative several times per second. Hypothetically, if a digital circuit tried to use AC then it would get very confused, because everything would seem to be turning on and off all the time.

With all that said, it's very common to turn AC into DC through a process called rectification. For example, that's what allows DC devices to get power from an AC outlet (e.g. to run your computer or charge your phone).


body:
All digital logic circuits run on DC.

Most Arduino boards include a voltage regulator. You can feed them an input ranging from 7 to 12 volts, and they "clean up" that input and lock it to precisely 5 volts, the voltage needed by the Arduino.

They can also run directly off the regulated 5 volts from the USB connector.


message:
Questions on programming logic?

So I am learning arduino code by going through examples and playing with them, and I came across something interesting. I am not fluent in any coding language but I am fully familiarized with computer logic and function so I can read what you suggest just fine.

What I want to know is, why are these two code pieces different?

    const int ledPin =  13;

    int ledState = LOW;

    long interval = 1000;

    void setup() {

    pinMode(ledPin, OUTPUT);
    }

    void loop()
    {

      unsigned long currentMillis = millis();

      if(currentMillis > interval) {

        currentMillis = 0;

        if (ledState == LOW)
          ledState = HIGH;
        else
          ledState = LOW;

        digitalWrite(ledPin, ledState);
      }
    }
This is my code, or rather modification to this code:

    const int ledPin =  13;

    int ledState = LOW;
    long previousMillis = 0;

    long interval = 1000;

    void setup() {

      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {

      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis > interval) {

        previousMillis = currentMillis;

        if (ledState == LOW)
          ledState = HIGH;
        else
          ledState = LOW;

        digitalWrite(ledPin, ledState);
      }

    }
How is it that the first code works, and the second code turns the led on and either terminates or never turns the LED off? The code is designed to blink the LED once every 1 second.

body:
Ah yes, *this* problem.

Note the declaration of `currentMillis`:

    unsigned long currentMillis = ...;

And now note the declaration of `previousMillis`:

    long previousMillis = ...;

You wouldn't think that one little word could make that much difference, but it does. It *completely* changes how C performs mathematics. `previousMillis` *must* also be `unsigned` or you will get undesired results.


body:
http://en.wikipedia.org/wiki/Two's_complement - good read regarding signed numbers in binary format. It really isn't "complex"; the highest bit being "1" denotes a negative number. As there is no "-0" the negative numbers also have an offset of one.

If you mix unsigned and signed - you simply get unexpected results.

You need to be very precise, i.e. check if the signed number is negative and handle it with care to make it "compatible" with the unsigned number before you use them together.
What "care" ends up be in reality depends on what you expect to get out of it, as result.


message:
How to send multi variable information over serial?

I would like to send information between my Arduino and my computer. Is there a way to send multiple variables from one Arduino? If so, how would I go about separating the variables?

body:
**You have three options for what you want to achieve (if I understand it right):**

 - **Have a fixed length for each variable:** If I know each number is going to be two digits, I can send "1234" and the other side can figure out the numbers are "12" and "34".
 - **Have a delimiter character:** Have a character that signals a new variable. For example: "213|1234" would translate into "213" and "1234". You could even use the newline character to signal a new line (with `Serial.println();`).
 - **Do some sort of validation to separate the data:** If sending a favorite number and favorite color, I can send "12RED345BLUE" and the other side it can find that it's "12" (both numbers), then "RED" (all letters), then "345" (three numbers), and finally "BLUE" (again, all letters).


message:
Arduino 433Mhz weather sensor receiver

I want to monitor the temperatur around the house and outside. I want to save the data to mysql and then create some kind of webapplication that displlays the data. It is pretty easy to find temperature sensors that transmitts over 433Mhz, and I have thought about [Telldus tellstick][1] to receive data and store them. This receiver costs about 30 - 40 $ and 10 - 20 $ for each sensor.

But since I just learned that Arduino can be used for everything, I would love to hear more about it.

Can someone please give me an introduction to what I would need to make this solution? The arduino should basicly receive data from 433 Mhz sensors and store it to MySQL.

What woulds be the challanges when doing something like this?

  [1]: http://www.telldus.com/products/tellstick

body:
You could use an Arduino with an ethernet shield to store the data to a MySQL server on the local network. See this [blog post](http://drcharlesbell.blogspot.dk/2013/04/introducing-mysql-connectorarduino_6.html) for an introduction to a library.

The tellstick is designed to be plugged into a USB host, so it doesn't make much sense in combination with an Arduino. You can get a USB host module but it's an expensive solution and you are using way more hardware than necessary.

Instead you could get 433 MHz receivers dirt cheap on ebay, but I'm afraid they only work on one channel, and there are a bunch of channels in the 433 MHz spectrum. So they might not work with the sensors you are talking about.

Another option would be to use eg. Arduino Pro Mini's in combination with a 433 MHz transmitter, powered by a battery. You could get the temperature reading from the internal sensor, or use an external one. The internal sensor takes quite a bit of calibration work to give a precise reading though.
You can get Pro Mini clones on ebay for a few dollars. You would have to dive into sleep modes and such, if you don't want't the batteries eaten away in a short time. To program it, you'll need an FTDI cable, or another Arduino programmed as an ArduinoISP (In System Programmer).
As an alternative to the Pro Mini board you could use a plain AVR chip, but it will be more work.


message:
Running an LCD keypad shield from a separate power source

I need to use a motor shield and an LCD keypad shield simultaneously hooked up to a single Arduino Mega Board. Since I can't physically stack them, I decided to reroute all the pins used for the LCD keypad shield. When I reroute all pins **except** the two power pins, the LCD and keypad work fine. But when I disconnect those 2 pins and connect them to any other power source than the Arduino Mega, it fails. The screen becomes either blank / jumble of illegible characters / brief moments of expected output followed by the same jumble.

This behavior is really strange since the power pins don't carry any information, they are just power sources. The LCD keypad shield shouldn't be able to discriminate whether the power is coming from the Arduino Mega or not - but it does. I checked with a voltmeter that all power sources I tried are DC 5V.

At first I thought this is because the `lcd.begin()` function is called only once, so I rewrote my code to re-initialize the lcd at every iteration. This doesn't solve the problem.

Here is a picture of the setup that works. (rerouting all pins *except* the power.) Ignore the location of analog input cable, since it doesn't do anything in the current code.

![][1]

And one that fails. The only difference from above is the power source.

![][2]

And my code.

    #include <LiquidCrystal.h>

    // select the pins used on the LCD panel
    LiquidCrystal lcd(28, 29, 24, 25, 26, 27);

    void setup()
    {
      lcd.begin(16, 2);
      lcd.print("Hello World!");
    }

    void loop()
    {
      lcd.begin(16, 2);
      lcd.setCursor(0, 0);
      lcd.print("Hello World!");
      delay(1000);
      lcd.setCursor(0, 0);
      lcd.print("Hello Again!");
      delay(1000);
    }

Any suggestions?

  [1]: https://i.stack.imgur.com/yGRiL.jpg
  [2]: https://i.stack.imgur.com/60Trk.jpg

body: You can use a different power source, but the two circuit need to have a common ground, since all electrical signals are relative to ground. So connect a wire from GND on the LCD to GND on your Arduino and everything should work as expected.


body:
Those little 16x2 LCDs are quite prone to power fluctuations.  Even powered solely by an Arduino I've seen them run OK for a few minutes than turn to showing gibberish.  Ensure you have good power connections, bring your power in as close as possible.

Maybe a capacitor across the power input to the display might help.


message:
Cannot upload program to Arduino Duemilanove w/ Atmega328

![Upload Debug][1]

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

This is the error I receive while trying to upload to the Arduino.
I have installed FTDI drivers for mac. (http://www.ftdichip.com/Drivers/VCP/MacOSX/FTDIUSBSerialDriver_v2_2_18.dmg)

The board is part of a quadcopter: https://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=50460

The processor is an Atmel 328P. Do I have the correct drivers?

What else could be the issue?

body: You may have wrong port:  **/dev/tty.usbserial-A9007LXq** works with Duemilanove on my Mac.


message:
Arduino based small LCD screen with camera video capturing

i have a idea to create a small screen which displays video recorded from arduino with camera. so camera will be back side of human and screen will be at near to eye. human can see the pictures from back side.

i have found [https://electronics.stackexchange.com/questions/29139/processing-ntsc-video-feed-for-spi-display][1]

but its not give me a clear idea. is there any one who can advice me for that kind project?

  [1]: https://electronics.stackexchange.com/questions/29139/processing-ntsc-video-feed-for-spi-display

body:
An Arduino doesn't have anywhere near the processing ability to transcode video from a camera unless you had an abysmal frame rate and very low quality. Even then, you would have to add extra storage because the Arduino would be over capacity in a heartbeat.

I recommend converting this project to a higher powered board like the Udoo. I have the [Udoo Quad][1] and it's beastly considering its form factor. You're going to need something a lot bigger than an Arduino!

  [1]: http://www.udoo.org/


message:
Digital Read Serial tutorial - calculating the resistor value

The Arduino [Digital Read Serial](http://arduino.cc/en/Tutorial/DigitalReadSerial) tutorial guides you through the wiring of a simple button. My questions are centered around the resistor.

# Why is the resistor necessary?
I think I understand this, but correct me if I am wrong. To ensure that the input pin reads a low signal, and does not float, we should connect the pin to ground when the button is not pushed. When the button gets pushed, we will have a 5V signal flowing to both the pin and to ground. Kirchhoff's voltage law states that total voltage in closed loop must equal zero, so we have to deal with this 5V that is flowing directly to ground. That is why we put a resistor between the button and ground.

# How was the resistor value chosen?
This is what I am unclear on. Ohm's law states that...

    resistance = voltage / current

This is a 5V supply and the [Arduino Uno](http://arduino.cc/en/Main/ArduinoBoardUno) spec says that the pin provides 40 mA of DC current. So..

    resistance = 5V / 0.04A = 125 Ohms

In the [Digital Read Serial](http://arduino.cc/en/Tutorial/DigitalReadSerial) tutorial, **why do we have a 10K Ohms resistor?** That is way overkill, right? Which leads to another question: **Can you ever put too much resistance in place, if your only goal is to obliterate voltage?**

Thanks in advance for any feedback!

body:
You're very close. The resistor is there to act as a pull down resistor; If the input pin is floating it is just an antenna picking up random static. The key is that when positive is supplied (by pressing the button) the positive source needs to "overwhelm" the pull down resistor so that the input pin reads positive.

If there were no resistance, than the input pin would be reading in the middle of a direct path that does not favor positive or negative. Asside from the direct short that would be occurring, Which state the arduino would read I suspect would either be random or some property of the power supply; It would probably still read ground.

With the resistor, the signal is read directly connected to positive, before the load resistance. This way it will be sure to get a HIGH signal.

The exact size of the resistor is of little consequence. Too small and you waste current, but too much resistance is effectively just disconnecting ground again. There is a very wide range of values that will work fine between those.

I would like to note that when an arduino pin is set to input mode, it will effectively supply no current. It can be moddeled is being in series with a 100 megaOhm resistor. see http://arduino.cc/en/Tutorial/DigitalPins
for details.


body:
> **Why is the resistor necessary?**

The Arduino inputs have very high resistance. The datasheed of the Atmega328
says 100 MOhm for ADC, Such high values are good, but have also the drawback to deal with parasitic effects (resistance, inductance, capacitance). Such effects can also be used as [Capacitance Sensors][1].

> **How was the resistor value chosen?**

The resistor needs to have an arbitrary value, that is smaller than the input resistance. 10k and above are good for disabling the input leakage.

However you can also leave out the resistor when you use the internal pull-up resitors. In this case you deal with negative logic:

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

On pin 3 you'll measure `HIGH` and the button needs to be connected to the pin and the ground. The internal I/0 pull-up resistor has the value of 50k.

[1]: http://wiki.edwindertien.nl/doku.php?id=modules:capacitive


body:
You've already gotten a couple of good answers on why a pull-down resistor is needed.

To summarize, you need to connect the input to ground to keep the input from floating semi-randomly between high and low. You use a resistor so that when you close the switch, you don't create a short circuit between the +5V supply and ground.

Another point, though. The Arduino's inputs include an optional internal, software-controlled **pull-up** resistor. If you first set up the pin as an input, then write a HIGH value to that port, it activates the pull-up resistor. That causes the pin to read as HIGH when nothing is connected to it.

You can then connect your switch to ground instead of +5V. You then need to change your code logic to treat a HIGH value as not pressed, and a LOW value as pressed. This lets you simplify your wiring a little, since you don't need an external resistor.


message:
How can I make my Arduino code work?

I am trying to make an automatic lock which stays open during different times and on different days. I want the door open Monday through Friday 8am to 5pm. On Saturdays and Sundays I want the door locked. I will be using an electric lock strike the + wire to pin 9 and - to ground on arduino. I am using an LED for development purposes for now because I don't have the lock yet. The code I have now works (stays open) for 8am to 5pm through the whole week but i want the door locked for Saturdays and Sundays. This is my code so far:

    #include <Time.h>
    #define doorPin 9
    void setup() {
      // put your setup code here, to run once:
      pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
      setTime(10,1,1,6,7,2014);
    }

    void loop() {
    if (hour()>=8 && hour()<=17){
      digitalWrite(doorPin, HIGH);
    }
    else if (weekday()==1 || weekday()==7){
      digitalWrite(doorPin, LOW);
    }

body:
This is what's happening: it's still between 8 AM and 5 PM on the weekend, so it unlocks it. Since you use an `else if`, it terminates the `if` statement and never checks the day between 8 and 5. I'm almost positive that if you checked it another time in the day, it'd be "locked."

Fixed code:

    #include <Time.h>
    #define doorPin 9
    void setup() {
      // put your setup code here, to run once:
      pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
      setTime(10,1,1,6,7,2014);
    }

    void loop() {
    if ((hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7)){
      digitalWrite(doorPin, HIGH);
    }
    else {
      digitalWrite(doorPin, LOW);
    }

Note: `!` means "not." Thus, the door is locked only if it's not a weekend and it's between 8 and 5.

<strike>Additionally, you might want to get a lock that is the other way around: unlocked only with power applied so someone can't unplug the Arduino to get access.</strike> EDIT: miscommunication, ignore this part paragraph...


body:
Adding to Annonomus Penguin's answer, it might be cleaner and easier to understand if you extract the variable:

    bool doorOpen = ( (hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7) );

Or in my eyes even nicer if you unnegate the last part, ymmv:

    bool doorOpen = ( (hour()>=8 && hour()<=17) && (weekday()!=1 && weekday()!=7) );

And then use them directly in the code without the if statement:

    digitalWrite( doorPin, doorOpen ? HIGH : LOW );

This way you make sure that the doorPin always gets set and you din't forget a path like in your if-elseif-nothing version.

Another benefit is you can test independently if the doorOpen variable is correct and if the functionality that is triggered by it is correct.


message:
Error building Arduino WiShield Flash example: 'dflash' was not declared in this scope

I'm using WiShield library from: https://github.com/jcmuller/WiShield

What is wrong with this library?

The code:

    /*
     * Web Server using Flash
     *
     * A simple web server example using the WiShield 2.0
     * that reads the manufacturing ID from the Flash and
     * displays it on a webpage.
     */

    #include <WiShield.h>
    #include <dataflash.h>

    #define WIRELESS_MODE_INFRA    1
    #define WIRELESS_MODE_ADHOC    2

    #define FLASH_SLAVE_SELECT 7
    #define WIFI_SLAVE_SELECT  10

    // Wireless configuration parameters ----------------------------------------
    unsigned char local_ip[] = {192,168,1,2}; // IP address of WiShield
    unsigned char gateway_ip[] = {192,168,1,1}; // router or gateway IP address
    unsigned char subnet_mask[] = {255,255,255,0}; // subnet mask for the local network
    const prog_char ssid[] PROGMEM = {"ASYNCLABS"}; // max 32 bytes

    unsigned char security_type = 0; // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

    // WPA/WPA2 passphrase
    const prog_char security_passphrase[] PROGMEM = {"12345678"}; // max 64 characters

    // WEP 128-bit keys
    // sample HEX keys
    prog_uchar wep_keys[] PROGMEM = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,     0x09, 0x0a, 0x0b, 0x0c, 0x0d, // Key 0
         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Key 1
         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Key 2
         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Key 3
        };

    // setup the wireless mode
    // infrastructure - connect to AP
    // adhoc - connect to another WiFi device
    unsigned char wireless_mode = WIRELESS_MODE_INFRA;

    unsigned char ssid_len;
    unsigned char security_passphrase_len;
    //---------------------------------------------------------------------------

    unsigned char mfg_id[4];

    void setup()
    {
      initShield();
    }

    // This is the webpage that is served up by the webserver
    const prog_char webpage[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type:     text/html\r\n\r\n"
         ""
         ""
         "
Flash Mfg ID: 000 000 000
"
         "<form method=post action=\"/upload\" enctype=\"multipart/form-data\">"
         "FS Image Upload"
         "
"
         "<input type=file name=i size=40>   <input type=submit value=\"Upload\">"
         "</form>"
         ""
         "";

    void loop()
    {
      dflash.read_id(mfg_id);

      WiFi.run();
    }

    void initShield()
    {
      // there is some contention on the SPI between the flash and wifi chip,
      // so disable both devices at the beginning until they are properly
      // initialized by their respective libraries
      pinMode(FLASH_SLAVE_SELECT, OUTPUT);
      digitalWrite(FLASH_SLAVE_SELECT, HIGH);
      pinMode(WIFI_SLAVE_SELECT, OUTPUT);
      digitalWrite(WIFI_SLAVE_SELECT, HIGH);

      // now init dataflash
      dflash.init(FLASH_SLAVE_SELECT);

      // now init wifi
      WiFi.init();
    }

body: I doubt anything is wrong with the library, but in your initShield and loop methods you refer to a variable called 'dflash' which does not seem to be defined anywhere.


message:
Breadboard-to-Arduino wiring with flat flex cable assemblies?

I want to wire Arduino Due connectors to a breadboard 8-at-a-time, so they're easier to remove and more reliable.

I tried these [Flat Flex Cable Assemblies][1] (FFC assemblies) terminated with "solder lugs" from Digi-Key, but the pins are just a little too short to penetrate the Arduino connectors well.  Similarly they barely reach into to the breadboard contacts, so they tend to fall out.  Anyone find a workable product for this?

![enter image description here][2]
 ![Flat Flex Cable Assembly][3]

[This solution][4] is good but requires a lot of manual soldering.  Looking for prepackaged.

  [1]: http://www.digikey.com/product-detail/en/A9AAT-0802F/A9AAT-0802F-ND/160785
  [2]: https://i.stack.imgur.com/a47tU.jpg
  [3]: https://i.stack.imgur.com/WiCEB.jpg
  [4]: https://arduino.stackexchange.com/questions/1649/how-to-improve-wiring-a-breadboard

body:
Search for male-male jumper wire. Some of what you'll find is individual wires but there are also many that are connected together and you can rip off the width you need.

Here's [one from Adafruit][1] but there is no shortage of them on ebay/amazon.
![enter image description here][2]

  [1]: http://www.adafruit.com/products/758
  [2]: https://i.stack.imgur.com/3FKgE.jpg


body:
Although [Sachleen's answer](https://arduino.stackexchange.com/a/3217/220) is preferable in a lot of situations, there are a few other options that you have.

*Quick note on his answer: I find clamping a row of those wires together and rubbing a thin line of superglue over the connectors a useful way to keep them together. It's not very neat, but it works pretty well and, with that many wires connected, can make it more stable than before.*

There are two main alternatives I see:

 - **Ribbon cable:** very similar to the wires pointed out in Sachleen's answer, only the connectors come already as one piece.
> ![][1]
> *Source: http://www.adafruit.com/blog/wp-content/uploads/2012/06/window-207.jpg*

 They are typically two rows, but I've seen them before with one (although pretty rare). You could just ignore one row of those and use some male headers to connect the same side of the ribbon cable to the breadboard/Due.

 - **DIY:** although you said that you didn't like soldering, it's still the best solution here IMHO. You'll need soldering later on, and breadboards aren't reliable beyond just simple development, so you'll need to learn at one point or another. This is a great entry project because it's pretty hard to mess a simple thing like this up, unless you accidentally bridge two joints. However, you won't damage an expensive chip if you mess up (which you will on the first few times you solder), you can just clean the joints and start over.

 Anyway, just grab some perf board and some wire (twisted pair (similar to CAT5e)/ribbon cable with or without an adapter and plug/loose wires, and a few rows of male headers. The type of wire you choose doesn't really matter, just don't get something too thick or too thin. Anyway, solder some headers to the perf board and then you can solder the wires/the socket (if you choose a ribbon cable with ends) together. You can then cut the perf board to size (you can do this step before soldering) and you're done!

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


body:
Again similar to Sachleen's answer. You can crimp your own connectors onto a ribbon cable, that way you can have the desired header size.

I've just done this manually with some pliers (I couldn't afford the crimping tool) a bit tricky but I'm pleased with the results. I got all of the bits I needed from www.hobbytronics.co.uk. Anywho I'm happy with the results now after a few failed attempts.

![You can see my attempts here][1]

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


message:
Sending MIDI messages using PING ultrasonic sensor

I am working on a project that uses a potentiometer and an ultrasonic sensor to create MIDI signals. This is my first time working with an arduino. I took a class in C++, but am teaching myself some C in order to program the arduino. So far I have been looking at code that has been written, I've been trying to understand it and mess with it so that my arduino works. The first code creates notes, but I have no control over what notes play or when they play. The first code:

    #include <SoftwareSerial.h>

    int val;
    int AnalogValue = 0;
    byte note = 0;
    SoftwareSerial midiSerial(2, 3);

    void setup ()
    {

      pinMode(Pingpin, OUTPUT);
      Serial.begin(9600);
      midiSerial.begin(31250);
    }

    void loop()
    {
      val = 0;
      digitalWrite(Pingpin, LOW);
      delayMicroseconds(2);
      digitalWrite(Pingpin, HIGH);
      delayMicroseconds(5);
      digitalWrite(Pingpin, LOW);

      AnalogValue = analogRead(0);
      note = AnalogValue/8;

      pinMode(Pingpin, INPUT);
      val = digitalRead(Pingpin);
      while(val == LOW)
      {
        noteOn(val, note, 0x40);
      }
      while(val == HIGH)
      {
         noteOn(val, note, 0x40);

      }

    }
    void noteOn(byte cmd, byte data1, byte  data2)
    {
        midiSerial.write(cmd);
       midiSerial.write(data1);
       midiSerial.write(data2);
    }

The second code makes more sense to me, but I get no notes to play. I am lost, and can't seem to get the second code to work. Second code:

    #include <SoftwareSerial.h>

    int val;
    int timecount;
    int AnalogValue;
    int ultrasoundValue;
    const int Pingpin = 8;

    byte note = 0;

    SoftwareSerial midiSerial(2, 3);

    void setup ()
    {

      pinMode(Pingpin, OUTPUT);
      Serial.begin(9600);
      midiSerial.begin(31250);
    }
    void loop()
    {
      AnalogValue = analogRead(0);
      note = AnalogValue/8;
      Serial.print(note,HEX);
      Serial.print("\t");

      timecount = 0;
      val = 0;
      digitalWrite(Pingpin, LOW);
      delayMicroseconds(2);
      digitalWrite(Pingpin, HIGH);
      delayMicroseconds(5);
      digitalWrite(Pingpin, LOW);

      pinMode(Pingpin, INPUT);
      val = digitalRead(Pingpin);
      while(val == LOW)
      {
       val = digitalRead(Pingpin);
      }

      while(val == HIGH)
      {
       val = digitalRead(Pingpin);
       timecount++;
      }

       ultrasoundValue = timecount;
       ultrasoundValue = ultrasoundValue - 14;
       ultrasoundValue = ultrasoundValue / 5;

      Serial.print(ultrasoundValue);

    if(ultrasoundValue > 127)
     {

     }

    else
      {

       noteOn(ultrasoundValue, note, 0x40);

      }

    }
    void noteOn(byte cmd, byte data1, byte  data2)
    {
       midiSerial.write(cmd);
       midiSerial.write(data1);
       midiSerial.write(data2);
    }

body:
There is quite a bit that needs to be addressed for these programs to work, and I don't know too much about midi, but i'll use the arduino midi tutorial for info. http://arduino.cc/en/Tutorial/Midi?from=Tutorial.MIDI

The first code will take one measurement of an analog value, set it to note, make one digital reading of pingPin, set that to val, and then write noteOn() forever afterwards. The second code will continually make analog and Ping readings and then write those to serial if the ping reading is greater than 127.

Infinite loop aside, Your programs don't work largely because they send the sensor data in the wrong ways. The first byte sent to noteOn is a command byte, it should not contain sensor data. the arduino tutorial uses the command 0x90 to control the note being played on channel one. the second byte is the note and the third byte is velocity, which seems to work like volume.

to set the pitch and volume of channel one, you need to repeatedly send

    noteOn( 0x90, note, volume);

If you want to play a note based on the analog readings that both of your codes set to "note" only when the ping value is larger than 127, you need something like this

    if(ultrasoundValue > 127){
        noteOn(0x90, note, 0x45); //middle volume according to arduino tutorial
    } else {
        noteOn(0x90, note, 0x00); //make the note silent by using 0 volume
    }

if you instead wanted to control the pitch with the ultrasoundValue, you would need to scale the value to being within 0-255, and then use that as note instead of the analog reading. You can get much more complicated than this, but you will need to find a reference for the MIDI protocol you can use.


message:
Can I hook up a compass directly to my GPS module?

I have a Parallax PMB-688 GPS module I'm using with an Arduino and was wondering if I could hook up a compass directly to my GPS. The GPS has an RX port which I hypothesized a compass could be attached to but I don't know if the GPS would be able to comprehend the compass data alone or if I would need to hook it up to the Arduino separately. Please let me know if you have done this or know whether or not it will work. Thanks,

Chris

body:
Unfortunately this will not work. If you take a look at the documentation for the module ([here][1] and [here][2]) you'll see that the RX pin is just there to receive commands for doing things like changing the baud rate and the protocol. The GPS wouldn't be able to comprehend the compass data.

  [1]: http://www.parallax.com/sites/default/files/downloads/28501-PMB-688-v0.1.pdf
  [2]: http://www.parallax.com/sites/default/files/downloads/28501-Polstar-NMEA-Commands.pdf


message:
3.5" TFT LCD Display is not working with Arduino Mega 2560 R3

Even I can't do similarly with my 2.4" TFT LCD in here still: https://arduino.stackexchange.com/questions/1138/2-4-tft-lcd-shield-isnt-working-on-arduino-mega

Now, I have bought 3.5" TFT LCD display for my Arduino Mega 2560 R3 to try whether I could run the screen or not, and it is not working now! I am so depressed and angry for these two's misbehaviors. I have already checked website and a lot of Arduino IDE code examples and libraries such as UTFT.h, UTouch.h, UTFT_MEGA, UTFT_CTE, TFTLCD. I tried these and I can not run my 3.5" screen. Where am I faulty? There is something below the screen shield: www.mcufriend.com and 3.5" TFTLCD for Arduino 2560. Are there any basic code or have anyone tried to run Mcufriend's displays correctly?

![enter image description here][1]

![enter image description here][2]

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

body:
Try this code:

https://www.dropbox.com/s/fce43rxofttl001/Librerías UTFT + UTouch para 3.5 TFTLCD para Arduino Mega 2560  - copia.rar

First delete the old UTFT library, then copy and paste the library inside de RAR file.


body:
http://www.henningkarlsen.com/electronics/library.php?id=51

Download hennings new UTFT library.

in myGLCD define R61581 as this is the driver chip for 3.5 display.

Regards!


body:
This might be a silly suggestion, but the mega2560 is 5v, and the display is 3.3v...and you need an interface board between.  I have successfully run a 3.2" display using this interface board

http://www.elecfreaks.com/store/lcd-tft01-arduino-shield-v20-shd09-p-213.html

Hope this helps


body:
I have the same lcd shield from mcufriend. It has ILI9327 in 8 bit mode.

This shield doesn't work with original UTFT library (it supports only 16-bit mode).

Try modified version from https://github.com/dgolda/UTFT and use:

    myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com


message:
What is causing my Uno to wake up?

NOTE: this code was working perfectly fine in another program.

I have a simple piece of code that puts the Arduino to sleep. When it is finished and intergrated into my project, it will only wake the processor up when an alarm from an external RTC triggers one of the hardware interrupts.

    #include <avr/sleep.h>
    #include <avr/power.h>

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

    void loop(){
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);        //deep sleep mode
        Serial.println("Device is going to sleep...");
        sleep_enable();        //put device to sleep

        sleep_disable();        //Device restarts here on wake
        Serial.println("Device is awake...");
        delay(1000);        //to slow down serial output
    }

In theory, the program should shut down the processor indefinitely because there is nothing available to wake it up.

However, the device continues waking itself up immediately after shutting down.

I have tried attaching the interrupts hoping it was some kind of anomalous watch-dog function. I have tried tying the interrupt pins to +5V and also (in a separate attempt) to GND. Nothing has helped.

What is causing the processor (and/or program) to constantly wake itself up?

body: `sleep_enable()` *allows* the MCU to sleep, but it does not *cause* it to sleep. Call `sleep_cpu()` after enabling.