body:
> Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory.

**All** constants are initially in program memory. Where else would they be when the power is off?

> I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture.

It's actually [Harvard architecture](https://en.wikipedia.org/wiki/Harvard_architecture).

> Why on earth do I have to copy the damn content to RAM before accessing it?

You don't. In fact there is a hardware instruction (LPM - Load Program Memory) which moves data directly from program memory into a register.

I have an example of this technique in [Arduino Uno output to VGA monitor](http://www.gammon.com.au/forum/?id=11608). In that code there is a bitmapped font stored in program memory. It is read from that on-the-fly and copied to the output like this:

      // blit pixel data to screen
      while (i--)
        UDR0 = pgm_read_byte (linePtr + (* messagePtr++));

A disassembly of those lines shows (in part):

      f1a: e4 91        lpm r30, Z+
      f1c: e0 93 c6 00  sts 0x00C6, r30

You can see that a byte of program memory was copied into R30, and then immediately stored into the USART register UDR0. No RAM involved.

---

However there is a complexity. For normal strings the compiler expects to find data in RAM not PROGMEM. They are different address spaces, and therefore 0x200 in RAM is something different from 0x200 in PROGMEM. Thus the compiler goes to the trouble of copying constants (like strings) into RAM at program startup, so it doesn't have to worry about knowing the difference later on.

> How is the code (32kiB) handled then with only 2kiB RAM?

Good question. You won't get away with having more than 2 KB of constant strings, because there won't be room to copy them all.

That's why people who are writing things like menus and other wordy stuff, take extra steps to give the strings the PROGMEM attribute, which disables them being copied into RAM.

> But I'm bewildered by those instructions to just read and print data from program memory:

If you add the PROGMEM attribute you have to take steps to let the compiler know that these strings are in a different address space. Making a complete (temporary) copy is one way. Or just print directly from PROGMEM, a byte at a time. An example of that is:

    // Print a string from Program Memory directly to save RAM
    void printProgStr (const char * str)
    {
      char c;
      if (!str)
        return;
      while ((c = pgm_read_byte(str++)))
        Serial.print (c);
    } // end of printProgStr

If you pass this function a pointer to a string in PROGMEM, it does the "special read" (pgm_read_byte) to pull the data from PROGMEM rather than RAM, and the prints it. Note that this takes one additional clock cycle, per byte.

> And even more interesting: What happens to literal constants like in this expression `a = 5*(10+7)` are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.

No, because they don't have to be. That would compile into a "load literal into register" instruction. That instruction is already in PROGMEM, so the literal is now dealt with. No need to copy it to RAM and then read it back.

---

I have a lengthy description of these things on the page [Putting constant data into program memory (PROGMEM)](http://www.gammon.com.au/progmem). That has example code for setting up strings, and arrays of strings, reasonably easily.

It also mentions the F() macro which is an easy way of simply printing from PROGMEM:

    Serial.println (F("Hello, world"));

A bit of preprocessor complexity lets that compile into a helper function which pulls the bytes in the string from PROGMEM a byte at a time. No intermediate use of RAM is required.

It is easy enough to use that technique for things other than Serial (eg. your LCD) by deriving the LCD printing from the Print class.

As an example, in one of the LCD libraries I wrote, I did exactly that:

    class I2C_graphical_LCD_display : public Print
    {
    ...
     size_t write(uint8_t c);
    };

The key point here is to derive from Print, and override the "write" function. Now your overridden function does whatever it needs to output a character. Since it is derived from Print you can now use the F() macro. eg.

    lcd.println (F("Hello, world"));


sender: user

message:
Cheap arduino wi-fi TRIGGER

I am looking for cheap way to have very basic wireless communication between an Arduino and a iphone.
I don't need to send complex data, it would be sufficient to "trigger" the arduino: let's say it is reading a certain pin voltage and waiting for it to be up in order to do stuff, my goal is to trigger this pin up by any (wireless and iphone friendly) mean.

I have figured out two solutions: wi-fi shield, cheap RF transceiver. The problem with the latter is that it is not trivial to communicate with a RF transceiver from an iphone. I should add another arduino controlling an RF transceiver on the iphone side and commanding this arduino with an usb.

The wi-fi shield on the other hand is too expensive. Even small routers such as the wr703n (30 euro more or less) is too expensive in my opinion. I just want to send a "bit" of information, so I don't want to spend more than 10 euro.

The third option would be to hack some cheap wi-fi controlled tool, such a lamp or plug: do you know any?
Do you have any other idea?

Thanks!

sender: assistant

body:
WiFi you either need a WiFi router or for either the iPhone or Arduino to create a network.

RF transceiver you need external circuitry.

The common way to do this at the moment is using Bluetooth Low Energy. Using a Bluetooth Low Energy (BLE) shield you can directly connect the Arduino to a modern iPhone or Android phone (supporting Bluetooth 4.0).

Check out redbearlabs, who have a range of shields and BLE-enabled Arduino clones. There are example sketches and iOS apps on the net. I have made a BLE controlled RGB light using the redbearlabs BlendMicro and example OSX application.


message:
Error: 'SofwareSerial' does not name a type

I have trouble compiling this sketch. The error I get is

> 'SoftwareSerial' does not name a type

Any ideas how could I fix it?

    #include SoftwareSerial.h

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("Ready!");

      // set the data rate for the SoftwareSerial port

      // for HC-05 use 38400 when poerwing with KEY/STATE set to HIGH on power on
      mySerial.begin(9600);
    }

    void loop() // run over and over
    {
      if (mySerial.available())
        Serial.write(mySerial.read());
      if (Serial.available())
        mySerial.write(Serial.read());
    }

body:
You forgot the quotation marks, try

    #include "SoftwareSerial.h"


body:
Add to @geometrikal.

or

    #include <SoftwareSerial.h>


body:
    #include "SoftwareSerial.h" worked instead of
`#include <SoftwareSerial.h>`
ie " " not <>


message:
Simple compiler design help: Variable length arrays?

I'm trying to write a simple compiler in C++ for a language that I am making up for my lab.  The compiler will have to be able to turn a string like this:

    "do command_one 3 times"

into a data structure that represents this:

    <command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:

    "do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:

    <c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                    <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.

These examples show all of the functionality that I would want from the compiler.

I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem.

I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.

EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries.  I found the vector solution to work in my C++ code, but it will not work in the Arduino interface.  Is there a way to do the compiling WITHOUT using vectors?

body:
In C++ there is a std library container called vector you can use to create variable length arrays. You can use it like this:

    #include <vector>
    // ...
    std::vector<int> commands;
    // ...
    // parse string and generate commands, add your commands with push_back
    commands.push_back(new_command);
    // and you can access elements in the array like normal
    commands[0];
    // and also see how many elements are in the array
    commands.size();

I also want to mention the std stack, which I think would be a helpful class for managing the states of your nested loops. Each time your interpreter enters a new loop for example, push to the top of the stack how many times to run, and each iteration count down till 0 and pop (just as an example).

Edit:
Because you can't use vectors C++ also supplies the new and delete keywords to dynamically allocate and delete memory. However as arduino has really low memory I don't recommend trying to implement an expansible array on this.
This post here mentions that program memory and global memory is shared on 2K: [new operator on arduino][1]

You may just want to go with a reasonably sized static array on arduino considering the memory limitations. I would suggest using a pool or the new + delete stuff but any implementation you add to deal with memory management will take away space you need for your interpreter and its instructions.

Also I don't know what data type you've chosen to represent your instructions but char is probably best  on the embedded implementation if your instruction set is small as it only occupies one byte each.

  [1]: https://stackoverflow.com/a/16281821/996197


body:
After Edit:

Since you cant use vectors ...

... or use variable length arrays, if the compiler you are using it, supports it.

... the other viable solution is to get your own list or vector library, either from an existing open source library or implementing your own.

Cheers.


message:
Help connecting an Arduino and an electronic speed controller

We have [this controller][1] that we are planning to use with [this motor][2]. How do we plug it to the Arduino to make it work?

This is a totally new subject for our school team, since we are mostly programmers, so your help will be really appreciated.

  [1]: http://www.servocity.com/html/precision_digital_speed_contro.html
  [2]: http://www.servocity.com/html/12_rpm_hd_precision_planetary_.html

body:
As the controller and motor are from the same vendor, they can help you with specific questions.

That motor controller is designed to emulate a servo motor. So it takes a servo-motor signal:
Ground
Power
PPM signal

The Arduino servo library will drive the PPM signal. Power and ground for the controller need to come from a separate power supply. The Arduino can't power it.


body:
HobbyKing, which sells Arduinos and is a great source for motors and controllers, has an instructable on this at http://www.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/

I found another on the OpenROV site, at http://community.openrov.com/forum/topics/how-do-i-activate-electric-speed-controller-with-arduino

Did you actually try googling "arduino electronic speed control" before coming here?


message:
Using timers on an Arduino Mega 2560

I'm an amateur and I wish to use timers in my project. I'm using an Arduino Mega 2560 with a touch-sensitive screen with six  DS18B20 temperature sensors and a DS1307 RTC (real time clock). I would like to query my sensors every 1 or 2 minutes to refresh the screen for temperature acquisition. I do not how to program timers to schedule the readings and which timers to use?

body:
You can use the function `millis()`, that returns the number of milliseconds since the Arduino board began running the current program (unsigned long). This number will overflow (go back to zero), after approximately 50 days.

The code below uses the `millis()` function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED.

 /* Blink without Delay

  Turns on and off a light emitting diode(LED) connected to a digital
  pin, without using the delay() function.  This means that other code
  can run at the same time without being interrupted by the LED code.

  The circuit:
  * LED attached from pin 13 to ground.
  * Note: on most Arduinos, there is already an LED on the board
  that's attached to pin 13, so no hardware is needed for this example.

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
  */

 // constants won't change. Used here to
 // set pin numbers:
 const int ledPin =  13;      // the number of the LED pin

 // Variables will change:
 int ledState = LOW;             // ledState used to set the LED
 long previousMillis = 0;        // will store last time LED was updated

 // the follow variables is a long because the time, measured in miliseconds,
 // will quickly become a bigger number than can be stored in an int.
 long interval = 1000;           // interval at which to blink (milliseconds)

 void setup() {
   // set the digital pin as output:
   pinMode(ledPin, OUTPUT);
 }

 void loop()
 {
   // here is where you'd put code that needs to be running all the time.

   // check to see if it's time to blink the LED; that is, if the
   // difference between the current time and last time you blinked
   // the LED is bigger than the interval at which you want to
   // blink the LED.
   unsigned long currentMillis = millis();

   if(currentMillis - previousMillis > interval) {
  // save the last time you blinked the LED
  previousMillis = currentMillis;

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

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

Source: http://arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
You can use the watchdog timer for that. Below is part of the code that I use to make temperature readings every 8 seconds using the watchdog timer. It compiles on Arduino IDE 1.0.5 for Arduino Uno R3 board, but be warned that I didn't run it as it is below (so it's untested). You can change variables `COUNTER_TRIGGER` and `WATCHDOG_PARAM` to adjust its timing it to your liking. Note also that I'm using ATmega328P, so map it accordingly to your MCU.

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

 #define WDTCR_REG WDTCSR
 #define SERIAL_DEBUG

 int COUNTER_TRIGGER = 1; // 1 * 8 sec = 8 seconds
 int WATCHDOG_PARAM = 9; // 9 = 8 sec
 // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms, 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec

 volatile long watchdog_counter = 0;
 int counter_trigger = COUNTER_TRIGGER;

 const byte TEMP_PIN = A5;

 void setup() {
   #ifdef SERIAL_DEBUG
   Serial.begin(9600);
   #endif

   pinMode(TEMP_PIN, INPUT);

   //Power down various bits of hardware to lower power usage
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);
   sleep_enable();

   // ADCSRA &= ~(1<<ADEN); //Disable ADC
   ACSR = (1<<ACD); //Disable the analog comparator
   DIDR0 = 0x3F; //Disable digital input buffers on all ADC0-ADC5 pins

   sei();
   setup_watchdog(WATCHDOG_PARAM);
 }

 void loop() {
   #ifdef SERIAL_DEBUG
   Serial.print("Sleeping...");
   Serial.flush();
   delay(20);
   #endif

   sleep_mode();

   #ifdef SERIAL_DEBUG
   Serial.println("awake");
   #endif
   // Zzzz...

   #ifdef SERIAL_DEBUG
   Serial.print("watchdog_counter = ");
   Serial.println(watchdog_counter);
   Serial.print("counter_trigger = ");
   Serial.println(counter_trigger);
   #endif

   if (watchdog_counter >= counter_trigger) {
  watchdog_counter = 0;
  doSomething();
   }
 }

 void doSomething() {
   // do your thing here
 }

 // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms, 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
 void setup_watchdog(int ii) {
   byte bb;
   int ww;
   if (ii > 9 ) ii=9;
   bb=ii & 7;
   if (ii > 7) bb|= (1<<5);
   bb|= (1<<WDCE);
   ww=bb;

   MCUSR &= ~(1<<WDRF);
   // start timed sequence
   WDTCR_REG |= (1<<WDCE) | (1<<WDE);
   // set new watchdog timeout value
   WDTCR_REG = bb;
   WDTCR_REG |= _BV(WDIE);
 }

 // executed when watchdog timer expires
 ISR(WDT_vect) {
   watchdog_counter++; // increment volatile
 }

I don't remember where I got it. I'll add proper attribution when I find out who provided the code... soon.

I hope this helps.


message:
Controlling ESC with Arduino

I want to control these motors: [hexTronik DT750 Brushless Outrunner 750kv][1] with this battery: [Turnigy 2200mAh 3S 25C Lipo Pack][2] and these ESCs: [TURNIGY Plush 18amp Speed Controller][3].

I am new to this field of driving brush-less motors. Can someone tell me if I need anything else? Will this set-up work without anything getting destroyed?

  [1]: http://www.hobbyking.com/hobbyking/store/uh_viewitem.asp?idproduct=6247&aff=61689
  [2]: http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=8934&aff=61689
  [3]: http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=4312&Product_Name=TURNIGY_Plush_18amp_Speed_Controller&aff=61689

body:
I 've been working on an autonomous arduino quadcopter for about 7 months now and I have a few tips for you.

1) your setup seems fine as long as your motors aren't going to draw more amps than your ESC can supply, but It is always a good idea to buy ESCs with a higher "max amps" than your motors draws. I would choose 25 amp max ESCs or higher.

2) In order to control the motors via PWM, I use the Servo library because you get a resolution from 700-2000 as opposed to "analogWrite" which gives a default resolution of 0-255.

3) your ESC probably has a minimum pulse width value before it will start. I would recommend writing a program that gives you the ability to plug in values from 700-2000, and use the program to slowlly find that arming pulse width value. Mine is 1110 for reference.

If you have anymore questions, I will glady answer them.

May I ask, what is your project?


message:
Maxbotixs LV-EZ4 analog read question

I am using an external 5 volt power supply to power my Sonar, and I am using a Teensy 3.1
to read in analog signal  from the sonar. my question is since the teensy is only 3.3v tolerant with analog in, is it safe to use with the maxbotix sonar?

body:
*Converted Gerben's comment to an answer*

---

That is not safe. Maximum voltage on the analog pins is 3.3v, according to the datasheet. But why don't you power it from 3.3v? Minimal voltage for that unit is 2.5v. And it uses only 2mA.


message:
ATMega328P not running sketch in standalone (works in Uno R3 Board though)

I bought an ATMega328P-PU and burned OptiBoot onto it using a second *Arduino Uno R3* with great success.

I then put the microcontroller back on the (empty) Uno R3 (DIP) Board for programming, connected USB and uploaded the blink sketch successfully.

Now to the weird stuff:

`Blink` works on the Arduino Board itself, but if I pull it out and stick it into my breadboard, the program seems to not start. Here are some facts:

- happens with or without external crystal `16.000` *(Pin 9-10)*
- happens with or without the 22pF capacitors from `crystal` to `GND` *(9-GND, 10-GND)*
- happens with Fuses set to internal OSC or to external clock *(Uno default)*
- happens with or without the `ADC VCC` _(Pin 20)_ and `REFERENCE` _(Pin 21)_ Pins @ 5V
- happens on 5V and on 3V3
- happens with or without external Pullup on `RESET` Pin (1)
- Most of the output Pins sit at `0.8 V`

body:
I found the solution by accident.
---------------------------------

While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.

What did I measure?
---

Actually I was just measuring one of the `crystal` pins _(Pin 9 or 10)_. The sketch went running for a few seconds and very different speeds and then stopped.

This small change in voltage gave the ATMega the `clock` signal it needs to step through the program.

Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.

The perfect solution
-------

As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.


message:
Car dome light fading with arduino nano

So I'm working on my car and now I've got my sights on the electrical system. I've installed a keyless entry system and a pulse timer for the dome light. Now, I'd like to give the dome light the fade effect all the modern cars have. After looking around, it seems an Arduino would be the most reliable.

I currently own an board similar to the Arduino Nano, specifically the SainSmart Nano. So I've determined that I'd power the board with a constant 12V, use pin 7 as input, and use pin 9 as output.

My code:

    int domeLightIn = 7;
    int domeLightOut = 9;
    int brightness = 0;
    int fadeAmount = 5;

    void setup() {
      pinMode(domeLightOut, OUTPUT);
      pinMode(domeLightIn, INPUT);
      digitalRead(domeLightIn);

    }

    void loop() {
      // Case 1: State of Door: Open/Closed
      // Case 2: State of Switch: On/Off
      // Case 3: State of KES: Active/Inactive

      //Case 1: If door is closed and led is off, brightness remains 0;
      //Case 2: If switch is off and led is off, brightness remains 0;
      //Case 3: If KES is inactive and led is off, brightness remains 0;
      if (digitalRead(domeLightIn) == LOW && brightness != 255){
        brightness = 0;
      }

      //Case 1: If door is open and led is off, brightness will fade in;
      //Case 2: If switch is on and led is off, brightness will fade in;
      //Case 3: If KES is active and led is off, brightness will fade in;
      if (digitalRead(domeLightIn) == HIGH && brightness != 255) {
        for (brightness = 0; brightness < 255; brightness = brightness + fadeAmount) {
          analogWrite(domeLightOut, brightness);
          delay(35);
        }
      }

      //Case 1: If door is closed and led is on, brightness will fade out;
      //Case 2: If switch is off and led is on, brightness will fade out;
      //Case 3: If KES is inactive and led is on, brightness will fade out;
      if (digitalRead(domeLightIn) == LOW && brightness == 255) {
        for (brightness = 255; brightness > 0; brightness = brightness - fadeAmount) {
          analogWrite(domeLightOut, brightness);
          delay (35);
        }
      }
    }

I am unsure whether I am using digitalRead() correctly along with wiring the input. So, am I doing this right? or perhaps there is a better way?

body:
You're not using digitalWrite properly. You should do:

    if (digitalRead(domeLightIn) == LOW && brightness != 255){

Just a sidequestion. What is pin7 connected to? If it's a 12v signal, you'd have to convert it down to 5v somehow.

Also, the 12v in the car can be up-to 14v, and can have some huge spikes. Not sure if the sainsmart's regulator can handle those spikes. It might die prematurely. It's also just wasting 60% (generating heat!), turning 12v to 5v. I would suggest adding one of those cheap car-phone-chargers.


body:
You should consider bringing the voltage down to 5v thats very important, when a car is running as stated above the voltage will increase because the battery is no longer running the electronics, the alternator powers everything and charges the battery.

Instead of trying to control this strait from the Arduino, use a transistor such as the TIP 120 darlington in order to control the existing light or you can put in a new one if you want.  This gives you the ability to add more powerful lights or add more lights to the circuit, which the Arduino would not be able to power via pwm.


message:
Why does an Arduino MEGA 2560 have different PORTS

I'm currently looking at my Arduino MEGA 2560 board and was just wondering why there are different ports to it e.g. ANALOG IN, DIGITAL, Communication? in fact I've only seen this in some microcontrollers. Not many microcontrollers have ports dedicated to certain things. Is anyone able to give me an answer as to why there is different ports to the microcontroller? is it making it easier for the chip to handle etc. A detailed but not too detailed answer would be great!

body:
Thats because Arduino has configured the Mega to do so. In microcontrollers you need to select what use will each pin have based on the availability. To make user interface easy arduino has done this based on what is commonly used by everyone. Even then some functions are still not disabled.

For example 50,51,52,53 are SPI pins on mega which use Pin change interrupt for working. Thus it not necessary we use them for SPI we can also use them for Pin change interrupt.

Similar is the case for pins 10,11,12,13. These PWM pins can also be used for Pin change interrupt but other PWM pins cannot.


message:
How to eliminate noise from PWM controlled 12V fan at low speed

I am trying to build a simple fan controller (single fan). So far I have successfully created a circuit which powers the fan with an external 12v DC adapter and added a transistor (NPN) to switch it on and off. The transistor is connected to a PWM port on the Arduino.

When putting `HIGH` on the port the fan works perfectly at high speed, but when I want to lower the speed (say `analogWrite(fanPin, 150)`) it starts to make a humming noise. I believe this is caused by the use of PWM.

What is the best way to control the speed of the fan without (too much) noise?

ps. The fan is a Cooler Master 3-wire PC fan. Transistor is a P2N2222A.

**Update**: Here is the schema I am using:

![schema][1]

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

body:
**coment** add circuit to know what you have done

Does your circuit looks similar like:

Do you use resistor for transistor? Diode for fan?

![enter image description here][1]

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

I suspect that you do not have diode.

The purpose of the diode is to allow current that is flowing in the motor coil to continue to flow in the same direction when the transistor turns off. When the transistor turns off, the voltage at the transistor collector will **rise** as it was flowing out of the motor. From **Vce(SAT)** it will rise above the power supply voltage and stop only when the transistor breaks down (or when it starts to ring with parasitic capacitance). By putting a diode from the transistor collector to the +12V rail, you prevent the voltage across the transistor from exceeding 12V and and allow the motor current to continue to flow.


body:
Try using pin 3 (or 11) and lower the prescaler of timer 2 using the following code in your `setup`;

    //move from /64 prescaler to /32 prescaler
    TCCR2B |= _BV(CS20);//set bit (remove this line for a /8 prescaler)
    TCCR2B |= _BV(CS21);//set bit
    TCCR2B &= ~_BV(CS22);//clear bit

Halving the prescaler will double the frequency.


body:
It might help to use a capacitor to smooth your PWM signal.

See http://ww1.microchip.com/downloads/en/AppNotes/00771b.pdf


body: I had the same problem with a 5V fan.  Something simple worked for me: To **decrease** the PWM frequency.  You probably want to do this using pin 9 or 10 (for the Uno) as changing the frequencies of other PWM pins messes up the delay and millis functions.  Details on how to do it and a very convenient function are provided in http://playground.arduino.cc/Code/PwmFrequency.  In my case, using the lowest frequency possible (31250/1024 = 31Hz), I completely eliminated the hum for higher speeds and significantly reduced it for lower speeds.  And by the way, I used the PWM pin to drive a MOSFET since the current of my fan was 140 mA, much higher than the 20 mA Arduino pins can safely provide.


body: There is also the possibility adding a capacitor bypassing the transistor. But you have to be careful, if the capacity is to big you could damage your transistor.


body:
SAS is correct - lowering the PWM to 31Hz works great. Tested using a 12v fan.  Before lowering the PWM, the sound from the fan was a loud "WHEEEEEeeeeeeeee" sound at any speed other than full speed.  Low speed made the sound worse.

After lowering the PWM frequency, the noise is inaudible at higher speeds.  At lower speeds you might hear a light "clicking" noise.  The sound reminds me of the faint "clicking" noise you hear as the valves on a car engine open and close.


body:
I can also confirm that SAS answer ist correct. I tested it with a 5V DC fan. I hear a very high noise at lower speed, but you have to listen closely, and a very fast clicking noise at higher speeds.

All in all i would say lowering the PWM to the suggested 31Hz did it for me but it is not a perfect solution.


body: I get that this post is 4 year old, but I successfully removed all fan noise with simple electrolytic cap and one ceramic on output, after adding caps you need to bias RPM. You can still get some relay low squeak coming from mosfet but only on low RPM


body: 25kHz power PWM solved this problem for my 3-pin fan. Diode had no effect on noise, it fixes another problem (EMI).


message:
Detecting grass, pavement, gravel

I think about building my own robotic mower, therefore I would like to detect if the surface the mower in moving on is grass, pavement, gravel ... etc.

Which sensors would be the best choice in order to achieve this?

The benefits:

 - no parimeter wire to bury
 - possible lawn edge detection (here most mowers fail to do a good job)

body:
You may need to use a combination of sensors. I can't think of any single sensor that can reliably detect the different surfaces.

An IR sensor could detect the difference between grass (cooler) and pavement/gravel (warmer).

An ultrasonic ranging sensor could detect the difference in heights between the grass and pavement/gravel.

A photoelectric sensor could detect the difference in reflectivity between the grass and gravel/pavement.

A visual camera could be used with image processing to detect color differences, although this may be too processing intensive for an Arduino.

A final possibility would be measuring the resistance to movement of the wheels. The robot will travel easier over the hard surface of pavement/gravel.

I would think that a combination of the above sensors would provide the most reliability and accuracy. However, it will still likely be limited to one location without recalibration. The weather will even cause a change in some of the sensors (photoelectric for example on a sunny vs. cloudy day).


body:
![Sensors in lawn mover][1]

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

You could try to use a force sensitive sensor to detect when grass blades touch it.


body:
A combination of colour sensors as the predominant one and proximity sensors as the secondary one should work fine. Around $10 so definitely worth trying out. Also, the code should be relatively easy.

Here are links as samples. I hope this helps :)

[$6 colorvsensor][1]

[1]: http://www.dx.com/p/tcs230-color-sensor-detector-module-for-arduino-148739?tc=AUD&gclid=Cj0KEQjwtvihBRCd8fyrtfHRlJEBEiQAQcubtEsIYEj3sI86-P4W3tnviua5B44ZwO722gmYXFFSQogaAt2T8P8HAQ#.VD7aD1ZdbCQ

[$4 Proximity  sensor][2]

  [2]: http://m.miniinthebox.com/ultrasonic-module-hc-sr04-distance-measuring-transducer-sensor-for-arduino-201211270080054_p478889.html?currency=AUD&litb_from=paid_adwords_shopping&gclid=Cj0KEQjwtvihBRCd8fyrtfHRlJEBEiQAQcubtGOvddT9LtfF7yBDOkZ4PbQyYhWMWjHNbTYx3EB8_BwaAvE-8P8HAQ


body:
I have found this DIY mower page (where they apparently already implemented a grass sensor). [Grass sensor][1]. Other useful info can also be found (mixed in english and german).

They are measuring the capacity of the underground in about 2cm (1inch) height.

On gravel or other hard material this is near 0 (as the sensor is in the air). On grass the value is higher.

Haven't though of this solution, should be the way to go.

  [1]: http://www.ardumower.de/index.php/en/ardumower-topics/sensors/lawn-sensor


message:
Cant's code against Yun Wireless Section

Just got my Yun today.  Successfully connected to my home wireless, installed YunSysUpgrade_v1.5.1,
and divied up my Micro SD card for Linino and Windows file system with YunDiskSpaceExpander,
and got files serving on the native file server from the SD card.

But I can't seem to touch the wireless section from a sketch.

I'm running a mod of the example ScanNetworks sketch - here's the relevant part:

    void loop() {
      delay(1000);
      String fv = WiFi.firmwareVersion();
      Serial.println("Version: ");
      Serial.println( fv );
      Serial.println("Status: ");
      Serial.println( WiFi.status() );
      // scan for existing networks:
      Serial.println("Scanning available networks...");
      listNetworks();
    }

Here is the ouptut: no version and a status of 255 (which I cannot find documentation on....)

> Version:
>
> Status:
255
>Scanning available networks...
> ** Scan Networks **
>number of available networks:0

I looked at installing wifi_dnld.elf, but could not find jumper 3 on my Yun, so assumed it was for the 'true shield'.

What am I doing wrong, or do I need to return this to amazon?

body:
`WiFi` library won't work with the Yun: it's meant to work only with the WiFi shield.

On the Yun, everything but the pins is connected to the linux cpu. For the microcontroller to use all the devices available to linux, including wifi, you need to use the `Bridge` library. Try running example `WifiStatus` (Examples -> Bridge -> WifiStatus)

A drop in replacement (almost) of both Ethernet and WiFi libraries is the `YunClient`/`YunServer` pair, part of the `Bridge` library. Check out the docs at http://arduino.cc/en/Reference/YunBridgeLibrary.


message:
Can arduino create a file in its memory?

I am an arduino enthusiast and i am new to it.just wanted to know weather the micro processor itself could create a file in its memory while its is running. I know that it is possible to read a write from a file in c++ but is it possible to do so in an arduino (while it's running).

body:
To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller.

However, if it's feasible highly depends on the controller architecture and its peripherals.

Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.

Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)

And others don't allow Flash accesses from application at all.

Anyway:

The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...).

Therefore, the SD card approach is surely a very good suggestion.


message:
How do voltage and resistance work for two 5v servos when using an external 12v power supply?

I have a 12v/1.5 amp barrel plug power supply on my Arduino Uno. I have two servos that say they are rated for 4.8v to 6v, but no amps are specified. When my circuit is configured as it is in this image, it appears to work fine. (In my test sketch, I'm constantly and simultaneously rotating them from 0 - 180 degrees and then in reverse.)

But I don't understand why it works. I assumed the 5v pin can only supply 5v of total power to the whole configuration. Is it instead supplying a regulated 5v at as needed between both servos from a total pool of 12v (presumably up to 10v at once)? Do I need voltage regulation? Shouldn't I have to know the amps for the servo(s) and use some sort of resistance?

Thanks for any information and advice you can share on learning about the concepts underlying a situation like this.

![Running two servos from one 12v power supply][1]

Update: I ultimately modified my approach based on the feedback received here by wiring a separate 5v/2a power supply to the breadboard for the two servos, and wiring the rest of the circuit appropriately (using a common ground, etc.).

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

body:
Because the supplies of both servos are connected in parallel, they both see the same voltage. Hence there is no "pool", both are being supplied the same 5V.

There is a regulator on the Arduino which reduces the 12V input down to 5V. It does so by burning off the other [7V times however much current is being used] as heat. Since you are supplying it with 1.5A, the most it can supply is in turn 1.5A.


body:
Addition to Ignacio. Explanation from real life.

Gregir, look at your home devices like TV, micro wave, fridge and so on. They all need 220-230 V AC and you can plug all them to one socket. As Ignacio said voltage doesn't plus. The current does plus, for ex. you have 2 servos connected in parralel, both 5V, no load current 0.1A. So to run them with no load you will have to supply 5V and 0.1+0.1=0.2A.

I tried to explain at very basic level ;)


message:
Arduino Uno suddenly not recognized in Windows 8.1 (code 43)

I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately.

I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage.

Any idea? Any fix?

body:
Something is shorted out.

When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.

When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.

You can think of power supplies as having a very small internal resistance (R_p), and the board as being a resistive load (R_b). This forms a voltage divider, but because R_b >> R_p the voltage seen by the board is basically the same as that of the power supply. With a short, R_b is often < R_p, and thus the voltage seen by the board is much lower than the power supply voltage.

The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. *Note: The component will get hot enough to burn your finger after a few seconds.* One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.

If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.

Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.


body:
I've been dealing with the same issue, and have resolved it in a manner similar to random approach described above.

Drivers will get corrupted as we all know. But if you want to get past that Code 43 error, you need to have the arduino unplugged from the USB when reinstalling. Otherwise windows will bind the USB.inf generic driver to the device, which prevents the install of the CH341SER driver.

So unplug USB, delete the unknown device via Device mgr, run the CH341SER, *then plug in the USB cable. So I think that random approach worked not because the 9v reset was done unplugged, but because that was first chance (unplugged) that the CH341SER driver had to install without resources bound to generic USB.inf driver.


message:
SD Card shield and TCRT5000 sensor aren't working together on arduino uno

I need to work with SD card and `TCRT5000 sensor` (Reflective Optical Sensor with Transistor Output) and save data from sensor to file. So I select `Arduino Uno` and added to it a SD card shield(from LC STUDIO) and a `TCRT5000 sensor` but it isn't working.
My circuit and code is here:
![enter image description here][1]

<!-- language: c -->

    #include <SPI.h>
    #include <SD.h>

    const int chipSelect = 10;

    void setup() {
      Serial.begin(9600);
      pinMode(chipSelect, OUTPUT);
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        while(true);
      }
      Serial.println("card initialized.");
      File dataFile = SD.open("test.txt", FILE_WRITE);
      dataFile.close();
      dataFile = SD.open("test.txt", FILE_WRITE);
      if(dataFile){
        dataFile.println("Start:");
      }else{
        Serial.println("Error in creating file.");
        while(true);
      }
    }

    void loop() {
      float value = analogRead(A3);
      File dataFile = SD.open("test.txt", FILE_WRITE);
      if (dataFile) {
        dataFile.println(value);
        Serial.println(value);
        dataFile.close();
      }else{
        Serial.println("Error in opening file.");
      }
      delay(5);
    }

When `TCRT5000` isn't connected SD card working without any problem.
I think it is related to current and supply current. Any idea?

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

body: Did you figure this out yet? If not, you have the +5 volts going to the GND on the breadboard, causing a short.


message:
Is it possible to sample sound with arduino?

I have the arduino duemilanove with atMega328.
The frequency is 16Mhz.

I want to sample and record from the audio jack.
I searched and i found if i want to record "everything - so to speak", i have to sample at 44100Hz.

That means this is unfeasible with my arduino, since my frequency is only 16MHz?

body:
For the AtMega328's ADC the datasheet says

> • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

So, sampling two channels at 10bit resolution and 44.1kHz is not possible.

If 8bit resolution is enough, and if there's only one channel to sample, it should be able to do the job.

Edit:

To answer Connor's comment:

Of course, this does only apply when using the internal ADC. Connecting an external ADC (via SPI or whatever) makes it possible to sample data at the desired speed.

But anyway, the next question is: Is 16MHz fast enough to process the sampled data (which are received every (22.6/channels) microseconds? ;-)


message:
Wireless Sensor (IMU) to Arduino

I was doing some research about this subject and I only have more questions than answers.

I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.

The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.

What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.

My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.

As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.

body:
You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.

**Radio:** Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.

You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill.

**IMU:** Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.

You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50.


message:
problem using std::map. Are there known obstructing macros?

I have a header file, where I try to collect global variable declarations. When trying to typedef a map I get the following error:

    n file included from Dis0_10.ino:7:
    /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build8295701509021940161.tmp/globals.h:23: error: expected initializer before '<' token

relevant code snippets from global.h are:

    #ifndef GLOBALS
    #define GLOBALS
    #include <map>
...

    typedef std::map<uint8_t,uint8_t> memmap_t;

I have no clue, why this statement should fail. I consider it rather straight forward. So I think there must be some problems of [this kind here][1]. Or am I missing another include?

  [1]: https://stackoverflow.com/questions/6558697/c-map-expected-initializer-before-token

body:
The C++ standard library is not available for arduino.

Some implementations of similar containers or certain functions exist on the web, but for the most part the standard library is impractical on a device with such small amounts of both RAM and program memory.

An implementation of SGI STL for AVR has been documented here: http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/

map is mentioned as being particularly impractical for anything less than an arduino mega(1280). An example of maps working is included on the page so it seems like a good lead if you really must use one, but I've never done this myself so I cant guarantee it still works.


message:
Use Arduino Mega to program Arduino Duemilanove

I hava an Arduino Duemilanove but I think that its FTDI chip is crashed.

I have an Arduino Mega too, so can I use it to program my Duemilanove?

body:
Yes, this is not an uncommon activity.  This is called using an Arduino as an In-System Programmer (ISP)

This page has the information and Arduino program you need.  You'll need to adjust for the Arduino Mega pin differences, but that's fairly easy.
http://arduino.cc/en/Tutorial/ArduinoISP

Where the ArduinoISP page references pin 13, on the Mega it's pin 52.
Where the ArduinoISP page references pin 12, on the Mega it's pin 50.
Where the ArduinoISP page references pin 11, on the Mega it's pin 51.
Where the ArduinoISP page references pin 10, on the Mega it's pin 53.

Otherwise you should be able to connect the Mega to the patient in the same way as described, load the ArduinoISP sketch into the Mega, preferably from the GitHub repository linked in the article (https://github.com/rsbohn/arduinoisp).


message:
Controlling EL wire or panels with arduino

I understand that el wire and paper needs a special power source known as an inverter to light it up.

If I wanted to control it from an arduino, what point would I connect the arduino to the light or inverter?

body:
You could connect the Arduino to the light using a relay or any electronic switches (transistors and etc) that can take around 10 to 15mA per meter (so its distance dependent). You could use this link [https://learn.adafruit.com/el-wire/soldering-to-el-wire][1] to find out where to solder the switch connections to

  [1]: https://learn.adafruit.com/el-wire/soldering-to-el-wire


body:
upstream slow blinking
----------------------

The simplest approach:
Use a relay to turn the lights on and off. Control that relay with an Arduino.
("How to turn a relay on and off with an Arduino?" is a separate question).

Cut either one of the wires feeding power into the EL inverter ("upstream of the inverter"),
and connect the 2 cut ends of the (formerly) one wire to the contacts of the relay.

    power source ---- (relay contacts) ---- EL inverter ---- (EL wire)
               +--------------------------------+    +---------+

downstream slow blinking
------------------------

Alternative approach:
Use at least 2 pieces of EL wire.
Wire one always-on;
use a relay to connect or disconnect the other wire ("downstream of the inverter"). (The relay and controlled wire can be either directly connected to the inverter, or end-to-end connected to the always-on wire -- it doesn't matter for this application).

                                       always on
    power source ---- EL inverter ---- (EL wire) ---- (relay contacts) ---- (EL wire)
               +----------+    +---------+   +-------------------------------+

Control that relay to [control the EL wire with an Arduino][3], same as before.

dimming and PWM
---------------

Many low-cost relays are rated for only about 10,000 operations, so if you use them to blink for a long or short part of each second, they're only guaranteed to last for about 3 hours.
If you want to blink faster than that (and most people dim EL lights by blinking them *much* faster than that), you'll have to use something other than a relay.

Also, most people seem to want to do the switching "downstream" of the inverter, so they can "share" a single EL inverter and use it to power lots of independently controlled pieces of EL wire.

Perhaps the simplest approach is to use an off-the-shelf zero-crossing solid-state relay (SSR).
(["How to wire a SSR to an Arduino?"][4] is a separate question).

    power source ---- EL inverter
              +-----------+   | |
                              +----- EL wire (always on)
                              | +-----+
                              | |
                              +----(SSR)-- EL wire
                              | +-----------+
                              | |
                              +----(SSR)-- EL wire
                              | +-----------+
                              | |
                              +----(SSR)-- EL wire
                              | +-----------+
                              | |
                              +----(SSR)-- EL wire
                              | +-----------+
                              | |
                              ... etc.

Because most SSRs are overkill for this application -- most of them have heatsinks bonded to high-power triacs designed to handle far more current than we need to light up a EL wire --
some people save a few dollars by assembling their own SSRs out of zero-crossing optocouplers, triacs, etc.
(A lower-cost, low-power triac is more than adequate for controlling EL wire, even without a heatsink).

The SparkFun EL Escudo Dos Arduino shield for controlling electroluminescent wire[(c)][5][(d)][6];
Diana's SparkFun EL Sequencer[(e)][7][(f)][8][(g)][9];
the seeedstudio EL Shield[(h)][10][(i)][11][(j)][12][(k)][13];
Tully Gehan's Cool Neon Arduino Shield[(m)][14]
etc.
uses such zero-crossing optocouplers, triacs, etc.
(requires a separate EL inverter).

According to some people on the Arduino forums talking about EL wire[(n)][15][(p)][16],
some people save a few pennies by using normal optocouplers rather than zero-crossing optocouplers. Non-zero-crossing optocouplers seem to work fine for short pieces of EL wire but seems to destroy the triacs (failing "always on") with a few dozen feet of EL wire.

Some people save a few more pennies by skipping the optocoupler,
wiring the Arduino directly to the control gate of the triac, and the VCC pin of the Arduino directly to the MT1 pin of the triac.
[(q)][17] [(r)][18] [(s)][19] [(t)][20]
If there were some way to only turn the triac on near the zero-crossing, this could work great; but without zero-crossing control, this has the same problems as the above normal non-zero-crossing optocouplers.

always-on
---------

The "extra" always-on bit of EL wire is because some people say
"never run the inverter without at least 1 foot of EL attached"[(a)][1] because running some EL inverters with no load "can damage the inverter"[(b)][2].

  [1]: https://learn.adafruit.com/el-wire
  [2]: https://learn.adafruit.com/el-wire/using-el-wire
  [3]: http://www.instructables.com/id/Control-EL-Wire-with-an-Arduino/
  [4]: https://arduino.stackexchange.com/questions/4545/how-do-you-wire-a-ssr-relay-to-a-arduino-nano
  [5]: https://www.sparkfun.com/products/10878
  [6]: http://rylaangimby.com/holographic-fortune-teller-arduino-el-wire-unity/
  [7]: https://www.sparkfun.com/products/11323
  [8]: http://makezine.com/2010/04/27/programming-el-wire-fashion/
  [9]: http://www.kobakant.at/DIY/?p=2992
  [10]: http://www.seeedstudio.com/depot/EL-Shield-p-1287.html
  [11]: http://www.seeedstudio.com/wiki/EL_Shield
  [12]: http://www.bajdi.com/trying-out-the-new-seeedstudio-el-shield/
  [13]: http://www.robotshop.com/en/el-shield-arduino.html
  [14]: http://shopping.netsuite.com/s.nl/c.ACCT88394/it.A/id.1071/.f?sc=2&category=1678
  [15]: http://forum.arduino.cc/index.php?topic=50534.0
  [16]: http://dorkbotpdx.org/blog/paul/sparkfun_el_sequencer_trouble
  [17]: https://kavasmlikon.wordpress.com/2011/11/21/how-to-make-el-wire-blink/
  [18]: https://electronics.stackexchange.com/questions/25295/arduino-triggering-a-triac-for-el-wire-no-optoisolator
  [19]: http://celestialaudio.com/catchall/
  [20]: http://www.opencircuits.com/Russ_Hensel's_EL_Wire_Project


body:
For a simpler option, there are Arduino shields for controlling El Wire.  Sparkfun makes a couple and they have some sample code and projects.

https://www.sparkfun.com/products/10878


message:
Sense Whether Circuit is Closed

How can you sense a closed circuit? I want to have 4 pins with disconnected wires and when touched with a fifth wire play a specific note on a piezo buzzer until disconnected again.

[This project][1] loops through several keys and checks whether they are being touched using the [Capactive Sensor library][2]. I want to do something similar, but not with capacitive sensing. Alternatively, it may work to have the buzzer always trying to play a note, but only sounds when one of the 4 circuits is close. I'm just not sure how that would work in the code.

Here is their code that uses capactive sensing:

    #include <CapacitiveSensor.h>
    #include "pitches.h"

    #define COMMON_PIN      2    // The common 'send' pin for all keys
    #define BUZZER_PIN      A4   // The output pin for the piezo buzzer
    #define NUM_OF_SAMPLES  10   // Higher number whens more delay but more consistent readings
    #define CAP_THRESHOLD   150  // Capactive reading that triggers a note (adjust to fit your needs)
    #define NUM_OF_KEYS     8    // Number of keys that are on the keyboard

    // This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
    #define CS(Y) CapacitiveSensor(2, Y)

    // Each key corresponds to a note, which are defined here. Uncomment the scale that you want to use:
    int notes[]={NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5}; // C-Major scale

    // Defines the pins that the keys are connected to:
    CapacitiveSensor keys[] = {CS(3), CS(4), CS(5), CS(6), CS(7), CS(8), CS(9), CS(10)};

    void setup() {
      // Turn off autocalibrate on all channels:
      for(int i=0; i<8; ++i) {
        keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
      }
      // Set the buzzer as an output:
      pinMode(BUZZER_PIN, OUTPUT);
    }

    void loop() {
      // Loop through each key:
      for (int i = 0; i < 8; ++i) {
        // If the capacitance reading is greater than the threshold, play a note:
        if(keys[i].capacitiveSensor(NUM_OF_SAMPLES) > CAP_THRESHOLD) {
          tone(BUZZER_PIN, notes[i]); // Plays the note corresponding to the key pressed
        }
      }
    }

  [1]: http://www.instructables.com/id/Capacitive-Touch-Arduino-Keyboard-Piano/?ALLSTEPS
  [2]: http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

body: Connect your fifth wire to ground. Set the four inputs to `INPUT_PULLUP`. The four inputs will default `HIGH`, and be pulled `LOW` when connected to the ground wire.


message:
USB D+ D- to Arduino Mega RX TX

Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?

body: No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.


message:
Unusual LCD behaviour

Can someone please tell me what's going on with my LCD screen and how I can fix this issues below?

I have the following:

 - Arduino Uno R3 w/ ATMEGA 328P-PU
 - 16x2 LCD
 - TowerPro MicroServo SG90
 - DPDT Slide Switch w/ 120 ohm resistor

**Objective:**
Read the sensor value (If switch is on or off), and move a servo accordingly while displaying switch state on LCD.

**Issue:**
LCD display seems to receive random data during program run (see image). All starts up well, and as soon as a few seconds have lapsed in the void loop(), the screen becomes garbled. Also, the switch value (while debugging) gets a zero reading while HIGH, acting accordingly as if the switch was off. The servo motor runs as it should, but gets random pulses every now and again where it starts to buzz, but doesn't turn.

**Images:**
Three images below.

![Outcome 1][1]
![Outcome 2][2]
![Garbled Data Received][3]

**Schematic:**
![Schema][4]

**Coding:**

    #include <LiquidCrystal.h>
    #include <Servo.h>

    const int sensorPin = A0;    // select the input pin for the potentiometer
    int ledPin = 13;      // select the pin for the LED
    int sensorValue = 0;  // variable to store the value coming from the sensor
    int oldPos = 0;
    int pos = 0;
    int oldStat = 0;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    Servo servo;

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
      lcd.setCursor (0, 0);
      lcd.print("Starting up FSS!");
      delay(700);
      lcd.clear();
      lcd.print("Init SERVO...");
      delay(500);
      servo.attach(9);
      lcd.clear();
      lcd.print("SERVO Success!");
      delay(400);
      lcd.clear();
      lcd.print("Testing SERVO...");
      servo.write(0);
      delay(200);
      servo.write(90);
      delay(200);
      servo.write(45);
      delay(300);
      lcd.clear();
      lcd.print("SERVO Running!");
      lcd.clear();
      lcd.print("Select AUX Source");
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      lcd.clear();
      lcd.setCursor (0, 0);
      lcd.print("Select AUX Src");
      lcd.setCursor(0, 1);

      sensorValue = analogRead(sensorPin);
      Serial.print("Sensor: ");
      Serial.println(sensorValue);

      if(sensorValue == 0){
        //if(sensorValue = oldStat){
          oldStat = sensorValue;
          digitalWrite(ledPin, LOW);
          lcd.print("Switch is OFF");
          pos = 45;

          Serial.println("Switch is OFF");
        //}
      } else{
        digitalWrite(ledPin, HIGH);
        lcd.print("Switch is ON");
        pos = 120;
        Serial.println("Switch is ON");
      }

      if (pos != oldPos){
        servo.write(pos);
      }

      oldPos = pos;

      delay (700);
    }

  [1]: https://i.stack.imgur.com/uP7ZR.jpg
  [2]: https://i.stack.imgur.com/wTFLb.jpg
  [3]: https://i.stack.imgur.com/upDjK.jpg
  [4]: https://i.stack.imgur.com/89tdw.png

body: Insufficient decoupling. Put a 100nF cap on the supply lines at the LCD and a 100uF cap on the supply lines at the servo.


message:
Controll LED Strip with Arduino BLE

I'm working on this project where I have interfaced a LED strip (a two wire LED strip) with [this][1] Arduino (its not an Uno). I have setup every thing correctly according to [this][2] instructable. I'm able to make a simple blinky pattern and I turn it on/off with an Android app I made to communicate with the Arduino using Bluetooth on my phone. Cool.

What I cannot understand is, since the strip is two wired, how should I address individual LEDs on the strip to make more complex patterns? Can I use bit shifts? Reading an article from Makezine (insufficient reps to post more than 2 links), it says that I should connect the strup directly to the output pin. IMO, this will fry the Arduino or in a less virulent sway, not light up the strip in any way.

  [1]: http://redbearlab.com/blendmicro/
  [2]: http://www.instructables.com/id/PWM-an-RGB-LED-Strip-with-Arduino/
  [3]: http://makezine.com/projects/make-36-boards/android-arduino-led-strip-lights/

body:
Addressing individual LEDS on a simple strip with LEDs in series and/or parallel connection is just not possible. <br>
Connecting the strip directly to an output pin is completely nonsense. Forget it.

You need a strip with digital LED controllers populated, as described (for instance) in another link mentioned in your second link: http://www.adafruit.com/products/306

Have a look at this, then I'm sure you will come back with more detailed questions ;-)


message:
RS-485 with Arduino

I have two Arduinos on a RS-485 line, one acting as a Master and the other as a Slave.  The Master simply transmits information to the Slave, which parses it.

They work fine when the Master is turned on first and then the Slave is turned on.  However, I'd like to  make it so that the Slave can be disconnected and reconnected to the line and re-discover the connection (ideally without resetting either Arduino).

Here's the code from the Slave's loop

      void loop()
         {

           if (RS485Serial.available() >0 )  //Look for data from other Arduino
           {
            char byteSend = RS485Serial.read();    // Read received byte
            String str = String(byteSend);
             if (str == "<")  {      //  beginning of the transmission
           // does stuff here
          }
       }

}

Here is the relevant section of Master's loop:

      output_value ="<1,1,1,1,1,1,1>";
     RS485Serial.print(output_value);
     delay(250);
     RS485Serial.flush();

Any advice is appreciated...

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

        char byteSend = RS485Serial.read();    // Read received byte
        String str = String(byteSend);
         if (str == "<")  {      //  beginning of the transmission
       // does stuff here
      }

This is an extremely inefficient way of testing for one character. Much better would be:

        char byteSend = RS485Serial.read();    // Read received byte
        if (byteSend == '<')  {      //  beginning of the transmission
       // does stuff here
      }

---

> However, I'd like to make it so that the Slave can be disconnected and reconnected to the line and re-discover the connection (ideally without resetting either Arduino).

I know I'm not supposed to ask questions here, but what is stopping you?


message:
Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment

Is there a way to connect and read the output of a long stem thermometer like this one to an Arduino?

![enter image description here][1]

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

body:
Interfacing with a temperature sensor such as the DS18B20 (https://www.sparkfun.com/products/11050) would be much simpler than trying to interface with a thermometer with unknown internals.

Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.


message:
Where can I find beginner resources on using voltage regulators with Arduino circuits?

I'm trying to concurrently learn electronics and Arduino, and have recently moved from simply powering LEDs to servos. In all my attempts with servos and reading about them (especially multiple ones, and when using external power supply plugged into the board), experienced users often mention you use voltage regulators.

I've seen some Arduino schematics with servos and voltage regulators, most that include some capacitors, but I can't seem to find any tutorials or resources that explain why, when and how to use these parts when learning electronics & Arduino. (I'd like to go from there to transistors, mosfets, etc.)

body:
My understanding is that the capacitors smooth the signals. This helps the internal workings of the regulator not overshoot when compensating for a change in the input or the output. If the capacitors are not there then there is a chance of oscillation.

A search of google for Voltage Regulator Tutorial will give you quite a few results, here is one that I found (obviously this could change so if it does just do a search and go from there)

[regulator basics][1]

The link above is a good explanation that is not too in depth. But as stated in the comments look at the datasheet for specific values needed.

I also did a search for 'what are the capacitors for on a voltage regulator' and found some good info about why they are needed.

  [1]: http://www.baldengineer.com/tutorials/regulator-basics/


body:
In order to get a smooth signal to your power regulator you should use some capacitors before and after the voltage regulator. It will look something like this when you use the 7805 voltage regulator.

![7805 Voltage Regulator][1]

Note: This schematic is from a dutch website. Uin means Vin and Uuit means Vout. C2 and C3 are bipolar capacitors.

It's also smart to put a diode before the voltage regulator to make sure the voltage flows only to one direction. The values of C1, C2, C3 and C4 and pretty standard and coul be used for the other Voltage regulators as well.

The voltage Regulators come in different fixed values and tey have a minimum and maximum voltage they can handle. Here's a small table of the most common VR's with their minimum input voltages.

    Part Number  Output Voltage (V)  Minimum Input Voltage (V)
    7805   +5      7.3
    7806   +6      8.3
    7808   +8      10.5
 7809   +9      11.5
    7810   +10      12.5
    7812   +12      14.6
    7815   +15      17.7
    7818   +18      21.0
    7824   +24      27.1

Also note that the output currents of these Voltage Regulators listed above is max 1A. When they're called like 78S05 or 78S09 it'll be a 2A Voltage Regulator.

Another thing that could be important when you're using the minimum input voltages. If you put a diode before the Voltage Regulator there will be a small voltage drop. For a 1N4007 the voltage drop will be around the 0.5V. The voltage drop will only occur before the voltage regulator though, so when you don't use the minimal input values you don't have to mind about it.

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


message:
Basics with DHT11

I just bought the sensor [DHT11][1] and trying to test it with the library code provided by the IDE, but I always get the same error on `.read()` . Code -2

    /*####################################################################
    FILE: dht11_functions.pde - DHT11 Usage Demo.
    VERSION: 2S0A

    PURPOSE: Measure and return temperature & Humidity. Additionally provides conversions.

    LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
    GET UPDATES: https://www.virtuabotix.com/

      --##--##--##--##--##--##--##--##--##--##--
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
      ##  ##  ##  ## DHT11 SENSOR ##  ##  ##  ##
      ##  ##  ##  ##  ##FRONT ##  ##  ##  ##  ##
      | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
      --##--##--##--##--##--##--##--##--##--##--
          ||       ||          || (Not    ||
          ||       ||          || Used)   ||
        VDD(5V)   Readout(I/O)          Ground

    HISTORY:
    Joseph Dattilo (Virtuabotix LLC) - Version 2S0A (27 May 12)
    -Rewritten to with more powerful Versalino functionality
    Joseph Dattilo (Virtuabotix LLC) - Version 0.4.5 (11/11/11)
    -Made Library Arduino 1.0 Compatible
    Joseph Dattilo (Virtuabotix LLC) - Version 0.4.0 (06/11/11)
    -Fixed bugs (squish)
    Mod by Rob Tillaart - Version 0.3 (28/03/2011)
    Mod by SimKard - Version 0.2 (24/11/2010)
    George Hadjikyriacou - Original version (??)
    #######################################################################*/

    #include <dht11.h>

    dht11 DHT11;

    void setup()
    {
        DHT11.attach(2);
        Serial.begin(9600);
        Serial.println("DHT11 TEST PROGRAM ");
        Serial.print("LIBRARY VERSION: ");
        Serial.println(DHT11LIB_VERSION);
    }

    void loop()
    {
        Serial.println("\n");

        int chk = DHT11.read();

        Serial.print("Read sensor: ");
        switch (chk)
        {
            case 0: Serial.println("OK"); break;
            case -1: Serial.println("Checksum error"); break;
            case -2: Serial.println("Time out error"); break;
            default: Serial.println("Unknown error"); break;
        }

        Serial.print("Humidity (%): ");
        Serial.println((float)DHT11.humidity, DEC);

        Serial.print("Temperature (°C): ");
        Serial.println((float)DHT11.temperature, DEC);

        Serial.print("Temperature (°F): ");
        Serial.println(DHT11.fahrenheit(), DEC);

        Serial.print("Temperature (°K): ");
        Serial.println(DHT11.kelvin(), DEC);

        Serial.print("Dew Point (°C): ");
        Serial.println(DHT11.dewPoint(), DEC);

        Serial.print("Dew PointFast (°C): ");
        Serial.println(DHT11.dewPointFast(), DEC);

        delay(2000);
    }

And this is my ouput:

    DHT11 TEST PROGRAM
    LIBRARY VERSION: 2S0A

    Read sensor: Time out error
    Humidity (%): 0.0000000000
    Temperature (Â°C): 0.0000000000
    Temperature (Â°F): 32.0000000000
    Temperature (Â°K): 273.1499938964
    Dew Point (Â°C): nan
    Dew PointFast (Â°C): nan

    Read sensor: Time out error
    Humidity (%): 0.0000000000
    Temperature (Â°C): 0.0000000000
    Temperature (Â°F): 32.0000000000
    Temperature (Â°K): 273.1499938964
    Dew Point (Â°C): nan
    Dew PointFast (Â°C): nan

The wiring:

-left pin: 5v

-right pin: gnd

-middle pin: 5v - digital2 - through 10kO resistor

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

**UPDATED:**
I found a [library][4] that works. I also changed the wiring because I found out the sainsmart dht11 switches the pins:

-left: signal with 10kO and to 5v

-middle: 5v

-right: GND

Now just a question.
What is the difference between these two dht11 sensors.
[Dht11 basic][5]
[dht11 with board][6]

The one from sainsmart has a piece of circuit I don't know what it is.(I have a lack on electronics I try to fix step by step...)

**It is a resitor, capacitor?** it says 103.

How does this affect to the wiring?

  [1]: http://www.sainsmart.com/sainsmart-dht11-temperature-and-relative-humidity-sensor-module-for-arduino.html
  [2]: https://i.stack.imgur.com/hQQf0.jpg
  [3]: https://i.stack.imgur.com/HqhAN.jpg
  [4]: http://playground.arduino.cc/Main/DHT11Lib
  [5]: http://www.exp-tech.de/Sensoren/DHT11-Feuchte-Temperatur-Sensor.html
  [6]: http://www.sainsmart.com/sainsmart-dht11-temperature-and-relative-humidity-sensor-module-for-arduino.html

body:
It seems you wiring is ok, although I think you already have pull-up resistor on breakout board (look for a small 103 resistor).

Maybe you can try another library for DHT?
I have used one made by adafruit (https://github.com/adafruit/DHT-sensor-library) and everything worked just fine.

Regards,
Ian


body:
The DHT11 sensor is available as-is and integrated on a break-out board. The break-out board shows following differences:

- the order of PINs is changed, e.g. in one version: 1 -> signal, 2 -> `+`, 3 -> GND (left-to-right, pins down, looking at the front)
- the unused pin is not connected
- the board already has a 10 KOhm pull-up resistor connected

Thus, when you have a DHT11 on a break-out board you have to adjust schematics that use it as-is - e.g. in this [example][1] you have to remove the external pull-up resistor and connect the pins in the correct order.

Be aware that there may be different versions of DHT11 breakout boards available - i.e. ones where the order of pins is different. You can look out for PIN markings like `S` (-> signal) and `-` (-> GND). Also, you can look at both sides of the breakout board to trace the connections.

The resistor usually comes as SMD on such a board - and if it has a marking it uses a special code. For example, `103` means `10 * 10^3` Ohm, i.e. 10 KOhm.

The [adafruit DHT library][2] comes with an example sketch that prints the sensor values over serial.

[1]: https://learn.adafruit.com/dht/connecting-to-a-dhtxx-sensor
[2]: https://github.com/adafruit/DHT-sensor-library


message:
Using PROGMEM to save RAM

I am successful putting and retrieving a char array into Arduino flash memory using [PROGMEM][1] char arrays.

I am building my application using header files with a class definition / implementation and would like to keep the strings in the same header file.

If I define another PROGMEM char array neither one can be executed. In other words, these PROGMEM are global arrays as far as the Arduino compiler is concerned. They compile, but they won't show up.

Here is my test code:

      lcd.clear();
      lcd.print(*strFlashDebug[0]);  // in CDebug
      lcd.setCursor(0,1);
      lcd.print(*strFlashTrack[0]);  // in CTrack

If I put both definitions in the same header file, it only works with only one *lcd.print* enabled, not commented out.

It appears that multiple PROGMEM arrays can be defined and compiled, but only one is actually usable. What is the explanation?

  [1]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/

body:
A PROGMEM variable definition (i.e., declaration) allocates memory in FLASH. You need use an *extern* clause in the header file and a physical declaration in the C code which is linked in your code. It's pays also for potential static class properties.

Also check if *lcd.print()* accepts a PROGMEM array, i.e., if the overloaded procedure is defined and called.

Just note I recommend using much more effective string formatting via file streams (FILE) and *fprintf_P()*.


body:
The important thing to know for PROGMEM is that [the AVR chip][1] you’re using does not have a single flat address space. I.e., it does not use a [von Neumann architecture][2]; instead, it uses a specific version of what is known as a [Harvard architecture][3]: it has separate address spaces for RAM, program memory, and EEPROM. All of them start at 0. Which means that while dereferencing a null pointer is technically still undefined behavior in C++, it can be (and often is) perfectly valid in Arduino code.

The short version is: If you have a PROGMEM pointer, whatever function you pass it to must work on PROGMEM pointers. `lcd.print` does not, and as far as I can tell there isn't any way the function could possibly detect this is not a RAM pointer. You have to call a different function, assuming there is one in the first place.

See *[PROGMEM][4]* (Arduino reference) for examples on how to use PROGMEM data.

  [1]: https://en.wikipedia.org/wiki/ATmega328#Family
  [2]: https://en.wikipedia.org/wiki/Von_Neumann_architecture
  [3]: https://en.wikipedia.org/wiki/Harvard_architecture
  [4]: http://arduino.cc/en/Reference/PROGMEM


message:
Debugging a RadioShack Arduino motor/sensor shield

I bought a cheap "Make" kit at RadioShack, which includes some sort of proprietary Arduino Uno compatible motor/sensor shield. Naturally, the documentation is pretty bad. The documentation and Arduino code for the kit is here:

https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit

It includes [a circuit schematic][1] (2770168-CorePCB_schematic.pdf), but I'm still having trouble mapping the pins to the Arduino's pins. Can anyone help me make sense of this?

What I've made out so far is the shield's screw terminals appear to be connected to quadruple h-bridges. However, there are several other pin headers that I can't quite make out. I think it also directly exposes 4 of the Uno's ADC pins and 4 DIO pins. There are four pins for dual IR line sensors, but there's a lot of circuitry between these and any Arduino pins. Almost everything feeds into a DC6688F2SCN chip, but I can't find a datasheet anywhere, so I have no idea what it does.

The manual says jumpers on J16 need to be removed in order to connect to the Uno over USB, so it looks like I can't use the shield with the board and debug via USB at the same time. Is this board worth investigating or should I trash it?

  [1]: https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit/raw/master/Schematics/2770168-CorePCB_schematic.pdf

body:
There is a bit of info on the DC6688F2SCN here: [Chip Selection Guide](http://www.dragonchip.com/TechDoc/Selection Guide/DC6688F Selection Guide 130301.pdf), but Chris is 100%. Without the firmware, all you can do is look at the source code for the Arduino side.

If you look closely at the top of the board, you can see that one side of J16 goes to pins 2 & 3 and the other to 0 & 1. On the schematic, there are some other components hooked in there as well. The serial is definitely going using 0 & 1. I'm not sure why they have them wired to 2 & 3. It's probably a good idea not to put anything on any of these four pins.

That's pretty good though. Compare it to the SainSmart L293D shield, which is significantly cheaper but eats up eight digital pins when driving four motors. Also, the L293Ds can only put out 600 mA per channel while the [Bs](http://www.cs.uml.edu/~fredm/cher/people/rsargent/rec/datasheets/l293/) can do a full Amp.

The documentation isn't very good and the supporting code also has some issues; but, overall, this is a pretty decent package. It comes with the erector set pieces as well. You also get three IR sensor channels.


message:
Resistance in Switch (negative vs positive logic)

![Positive Negative Logic connection of Switch](https://upload.wikimedia.org/wikipedia/commons/6/6f/Positive_Negative_Logic_connection_of_Switch_with_Microcontroller_pin.png)

I tried in my Arduino the negative logic to get a digital input from a switch (with 10 KΩ resistance). If I want to use the positive logic what kind of resitance I have to use? For me seems that 10KOhm it to big and probably a smaller resistor should be used. How do we compute the value of the resistor? The schemes of Negative and Positive Logic from [Valvano's notes/ebook - University of Texas](http://users.ece.utexas.edu/~valvano/Volume1/E-Book/C8_SwitchLED.htm) gives 10 kΩ in both cases. Is it correct?

body:
From a pure electronics viewpoint, there is no real difference between both circuits, the difference will be handled by your code running on the MCU, as a close switch will either be `HIGH` or `LOW` depending on the logic you used to wire your switch.

The resistor must be present for 2 reasons:

- to avoid producing a shortcut between `+5V` and `GND` when the switch is closed, without it the shortcut would probably damage your power supply circuitry (if both pins are directly taken from Arduino, that would mean damaging Arduino supply circuits)
- to make the voltage pin attached to the pin the "*winner*" of both voltage pins when the switch is closed, ie that pin will provide the level to Arduino input pin

The value of the resistor should  be:

- high enough to limit the current between `+5V` and `GND` when the switch is closed, preventing damage and limiting overall power consumption of your circuit
- not too high to allow providing a voltage level to the input pin

Using 10k means that, applying Ohm's law, when closing the switch, a 0.5mA current would flow from `+5V` to `GND`, which is generally acceptable in terms of consumption and cwill not damage your power supply.

Note that the input pin is "**high impedance**" which means it has no voltage level if not connected to anything, and it does not supply or sink any current (or more accurqtely a negligible current only).

Finally, it is good to know that Arduino MCU offers the `INPUT_PULLUP` mode for digital pins, where an internal resistor pulls up the pin input to 5V.  This enables you to directly connect your switch between the pin and `GND`. So you just have to code:

    pinMode(XXX, INPUT_PULLUP);

instead of:

    pinMode(XXX, INPUT);

For information, according to ATmega328P datasheet (the MCU of Arduino UNO), those internal pullup resistors have a value between 20k and 50k.


message:
Why can't I connect more than one Arduino Uno + Ethernet Shield to my network?

I'm using 3 Arduino Uno boards with Ethernet shields. Each is connected to my home Internet switch with an Ethernet cable.  I assigned a different local IP address to each Arduino and gave each board a different MAC Address.

Each Uno is collecting temperature/humidity for a bedroom in my house.  The data is sent to a MySQL Database using PHP/HTML.

They work fine for a while (5 minutes) and then they conflict each other.  If I use one Arduino at a time it works fine, but I can't get them to work together.

Any idea how to solve the problem?

body:
It would be most helpful to see the code you're using and to know more about the configuration of your network and the symptoms of the conflict – for example where is the web site running?

Some things to try:

 - Simplify your network. Eliminate everything but the Arduinos and the web server. See if that changes anything.

 - Run the command `arp -a` (assuming you've got a machine running something UNIXish). It will show you the MAC and IP addresses of hosts on your network. Look to see if the Arudinos are still there and if there are any devices that conflict with them.

 - Try to `ping` the Arudinos. Do they respond?

 - Use `WireShark` or `tcpdump` to monitor traffic on the network. Look for traffic to or from the Arudinos (by IP addresses and by MAC addresses).

 - Add some debug code to the Arduino sketch so that you can watch what they are doing (send it out the serial monitor). See if what goes on the wire matches what you expect (monitoring with `tcpdump`).


message:
How do i wire a switch to control Leds on a arduino nano

I am wiring some LED's with buttons to trigger them but i don't know if i have the wiring right?

![enter image description here][1]

Code

        /* switch
     *
     * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
     * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
     * a minimum delay between toggles to debounce the circuit (i.e. to ignore
     * noise).
     *
     * David A. Mellis
     * 21 November 2006
     */

    int inPin = 2;         // the number of the input pin
    int outPin = 13;       // the number of the output pin

    int state = HIGH;      // the current state of the output pin
    int reading;           // the current reading from the input pin
    int previous = LOW;    // the previous reading from the input pin

    // the follow variables are long's because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long time = 0;         // the last time the output pin was toggled
    long debounce = 200;   // the debounce time, increase if the output flickers

    void setup()
    {
      pinMode(inPin, INPUT);
      pinMode(outPin, OUTPUT);
    }

    void loop()
    {
      reading = digitalRead(inPin);

      // if the input just went from LOW and HIGH and we've waited long enough
      // to ignore any noise on the circuit, toggle the output pin and remember
      // the time
      if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        if (state == HIGH)
          state = LOW;
        else
          state = HIGH;

        time = millis();
      }

      digitalWrite(outPin, state);

      previous = reading;
    }

>note
The code is not set to the pins yet.

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

body:
The wiring is correct, but `inPin` in your code is set to `2`, which is [`D4` on the Nano][1], while you have your signal wires going to `D7` and `D6` in your schematic.

Similarly, `outPin` is set to `13` in your code, which is `D9` on the Nano, but your schematic shows the LEDs connected to `D5` and `D4`.

I would also put the resistor going from the other pin on the switch to 5V, having the digital input connected directly to GND, but I'm not sure if that will affect power consumption, so it's probably more just a matter of personal preference.

  [1]: http://arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf


message:
Controlling bigger motors with an arduino board

i am german and my english is not the best, anyway i hope you will understand my problem.
At the moment i construct a little car with some friends. We have still completed the frame and now we think about controlling it in a electronic way. For example with a controller of a playstation or with our smartphones, however, it should be electronic, so i think about to do this with an arduino board.

We have two motors. One for the direction and the other one for the movement.
The first has about 8 ampere and about 12 volt, the other has 800 watt, so around 40 ampere and 24 volt.

My question is, whether it is possible and if so how to control them (or one them) with an arduino board and what do i need in addition?

It would be great if you could help us :)

body:
DC motors are typically driven with some sort of BJT/MOSFET solution that will be able to sink enough current to drive the motor because a microcontroller pin can only usually provide a few mA of power.  See [this link][1] for info on basic microcontroller DC motor control.  If slow response is acceptable and only one level of power is required (i.e. no PWM) even power relays could be used to turn on off the motor.  Some applications could use this.  However, for your application, it sounds like you will want more responsive control over the motor and need a particularly high power MOSFET to properly drive your application as your motor is very high power.  Such FETS such as [these][2] could be used to properly control such a motor using the microcontroller.  Do note additional protection circuitry will be necessary and is probably the topic of another feed, but this would be a place to start if you wanted to build it from scratch.  Otherwise go with an over the shelf driver board which will probably have something like the link above used on it.

  [1]: http://www.dummies.com/how-to/content/how-to-spin-a-dc-motor-with-the-arduino.html
  [2]: http://www.digikey.com/product-highlights/us/en/ixys-gigamos-power-mosfets/332


body:
One of the best ways to controll a motor is to look in to the motor shields from the arduino. You can buy seperate motor controllers with different throughput, some advanced with breaking and some without.

But motorshield is about the best way to get started.


message:
How do functions outside of void loop work?

I am used to Arduino sketches with a `void setup()` part that runs once, and a `void loop()` part that keeps looping. What happens when you have void functions outside of the main `void loop()`? Will these all keep looping in parallel or do they run one after the other? Or do certain void functions only run once certain criteria has been met (like a while loop)?

For example in the code below, when will the `void receiveData(int byteCount)` and the `void sendData()` functions run?

    //I2C_test

    //This code demonstrates communication via an I2C bus between a raspberry pi and an arduino.
    //When the Raspberry pi (master) sends data to the Arduino (slave), the Arduino uses this
    //data to control a motor. After the Arduino has recieved data from the master, it then collects
    //data from the external environment via a sensor and sends this data back to the Raspberry pi.

    #include <Wire.h>
    int number = 0; //Declare variables
    int val = 0;

    void setup() {
      //Anything between the curly brackets runs once when the arduino is turned on or reset
      pinMode(0, INPUT);
      //Set pin 0 as input and 3 as output
      pinMode(3, OUTPUT);
      Serial.begin(9600);
      //Set the data rate for serial transmission at 9600bps
      Wire.begin(0x04);
      //Initiate the Wire library, join the Arduino as a slave, and specify its 7 bit slave address
      Wire.onReceive(receiveData);
      //Define callbacks for i2c communication
      Wire.onRequest(sendData);
    }

    void loop() {
      //The code between the curly brackets keeps repeating
      delay(100);
    }

    void receiveData(int byteCount) {
      while(Wire.available()) {
        number = Wire.read();
        //Set the variable "number" to the data sent by the master
        analogWrite(3, number);
        //Write this number to pin 3 (PWM). This controls the motor speed
      }
      val = analogRead(0);
      //Read the voltage on pin 0 (connected to the sensor). Map input voltages between 0 and 5 volts into integer values between 0 and 1023
    }

    void sendData() {
      Wire.write(val);
      //Send the data read from the sensor to the master.
    }

body: It works as normal function, it must be called to make sense. loop()/setup() are called from a main() function which is compiled from Arduino directory and linked in. receiveData/sendData are to called from your program which root is in loop/setup functions.


body:
The `setup()` and `loop()` functions are unusual because they are called automatically for you by the Arduino code. No other functions behave this way.

Generally speaking, a function will never run unless you explicitly call it yourself (e.g. from within `setup()` or `loop()`), or instruct another part of the program to call it. (There are other ways to execute functions, but that usually involves some very advanced tinkering which is best avoided.)

For example, `pinMode()` is a function just like any other. It only runs when you actually put something like `pinMode(3, INPUT)` in your code. At that point, it runs once, finishes, and then the calling function carries on from where it left off (they never run in parallel).

The example code you've posted is quite interesting. Look at these lines in `setup()`:

    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

These lines are telling the `Wire` object to call `receiveData()` and `sendData()` in response to I2C events. It does this by passing function pointers which are stored and used by `Wire`.

I'd recommend searching for information about **C/C++ function pointers** online if you want to learn more about this. You may also be interested to explore Arduino's [`attachInterrupt()`][1] function.

  [1]: http://arduino.cc/en/Reference/AttachInterrupt


body:
Is it not that case that `setup()` is called once and `loop()` is called repeatedly?
i.e. that there is an **unseen** `main()` which might look like this:

    void main(){
      setup();
      while(True){
        loop();
      }
    }

Apologies as I'm just looking into the Arduino and have almost no C/C++ experience; I'm trying to get a handle on this `loop()` situation myself.


body:
I can't comment on Dee's response. The actual code that is executed in the main loop is [here][1]:

        int main(void) {
     init();
     initVariant();

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }
     return 0;
    }

And yes, `setup()` gets called once and `loop()` is being called repeatedly (together with some serial stuff).

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp


message:
Extract arduino collected data periodically

I'd like to extract data collected by a battery powered arduino for example once a day without stopping it and not using SD card.

It's posible, when I want to extract the collected data, to connect a laptop through the USB and then get data because Arduino is, at regulat time intervals, calling 'Serial.println(...)'?

body: Yes, you can do it. Depends how much data to have enough storage space. You also need consider potential memory endurance. E.g. external I2C ferromagnetic memory is good option. Of course it's not on Arduino board, you implement extension.


body:
This is a bit crude, but I think you could use an FTDI cable (which is a USB to UART converter) to have a program in your laptop talk to the Arduino using its UART (serial) interface.

To do it, you could plug the USB side of a FTDI serial cable to your laptop. The other end of the cable has a plug with 6 pins, 2 of which are the TX and RX serial signals. You could plug those two signals to pins D0 and D1 (RX & TX) of your Arduino using male-to-male jumpers.

In terms of software, you could code the Arduino sketch to listen on the serial port for a command from your laptop. When the command arrives, it would output the stored data (could be comma separated values with CR+LF as end of line). Your laptop would then listen for the answer and retrieve the data.


message:
Is my Arduino UNO fried?

The title sums it all up. While testing  the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened.

Thanks in advance,

afroraydude

body:
It's hard to tell without further testing. Do the following:

1. Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.
2. Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)
3. Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.
4. Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?

Report your findings by updating your question.