message:
Multiway Relay Dimmer

I am looking for something like a **multiway "relay dimmer"**.
Which lets me dim a light using an Arduino and a manual dimmer.
[![Schematic][1]][1]

(The manual dimmer should work without any computer!)

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

body:
You could use a rotary encoder for that purpose!

Basically the rotary encoder is a knob that, for every "tick" you give it, it returns a different value to your Arduino. With a bit of programming you can sense the direction of the turn, if it is positive then you lighten up the LED, and vice versa.

I used that to control a RGB led, it works very well! [here](http://playground.arduino.cc/Main/RotaryEncoders) some more information on the rotary encoder and the code needed to use it.


sender: user

sender: assistant

body:
I add another answer because I think I found something. After a few days searching on various sites that sell arduino stuff I found this http://www.dx.com/p/8-channel-5v-relay-module-extension-board-for-arduino-avr-arm-51-140703 that might be what you're looking for. One of the customers in the review states it can be used even without Arduino.

I know it's a relay, not a dimmer, but maybe you could add something to your circuit...


message:
Is Roboteq motor driver compatible with Arduino?

I'm planning use Roboteq motor driver for 24V brushed DC motor but I can't be sure that it's true or wrong. You know, Roboteq controller is too expensive and I don't want to spend money in vain. Have you any experience this controller? Are they compatible with Arduino?

http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail  Roboteq Controller Link

I also think, Pololu RoboClaw driver. https://www.pololu.com/product/1499 I don't know is it enough for wheelchair. Because, I already have used Pololu VNH5019 and it is not enough. (synchronicity and noise problems etc.)

If you have any ideas, I will be glad. Thank you.

body: It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.


message:
Connecting high sampling rate DAC and ADC to arduino DUE, timer consideration

I'm in the echopen association, our goal is to create a low cost, open source echographic probe. In order to do that, we use an arduino due for the first step. For doing acoustic imaging, we use ultrasonic transducer wich works at high frequency, typically 5 MHz. So, for our purpose we need to send and receive analogic signal at high frequencies.
We want to connect a 80 Msps DAC and a 80 Msps ADC to the arduino due so we can generate and mesure analog signal up to 42 MHz. I have found here (http://www.instructables.com/id/Arduino-Timer-Interrupts/#step0) how to use arduino timer interrupts in order to send and receive data at 84 MHz. I haven't connect my converters for the moment, but I have preliminary questions.
First, is the definition of the timer is the same for the arduino due (i.e. timer1 is a 16 bits timer) ? Morever, my ADC and DAC are 14 bits converters, can I tell to the arduino to sent only 14 bits digital signal ?
Secondly, as we work at high frequencies we will have to send a lot of data from the microcontroller to a computer via the serial port. I have make a test and at 250000 bauds it takes nearly 0.5 second to transfer 4300*8 bits datas. It is to slow for our purpose, how can I do it faster ?

body:
I'm sorry, but by your description you are doomed to failure from the start.

The Arduino Due runs at 84MHz.  That doesn't mean that it can communicate at 84MHz, only that it can process its instructions at around 84 million per second.

In order for you to transmit or receive 80 million samples per second you have to be able to a) transmit sample words (14 bits) 80 million times per second, and b) process the information between each sample.

That means you are going to require a processor that operates considerably faster than 84MHz.

For instance, assuming you are using high speed synchronous serial communication (say, SPI) to transfer the data.  For 16 bits of data (you won't get it to do just 14 bits using hardware and software would be way too slow) would require a transmission clock of (80000000 * 16) 1.28GHz.

If you're using a 16-bit parallel interface then you would only need an 80MHz communication clock to move the data around, but receiving that data and storing it somewhere and also processing it would require many many more instructions between each clock.  Far more than the Due could perform.  Certainly it's way way outside the scope of a timer interrupt.

I would suggest instead investigating systems that run in the high hundreds of Megahertz or even Gigahertz range.  Maybe one of the newer "version 2" Raspberry Pi embedded computers may be suitable.


body:
If I'm interpreting the datasheet correctly, you might be able to use the Static Memory Controller (SMC) capability of the Cortex M3 Sam3X to attach some 128K x 8 SRAM devices to your Due.  If your ADC and DAC support tri-state outputs then they could be attached the same way as memories (but ignoring address lines as irrelevant), allowing memory-to-memory DMA transfers.  Ie one could either input and store batches of ADC results at 42 MSPS, or could output batches of data to DAC at 42 MSPS, or could do simultaneous I/O at 21 MSPS.  I haven't read the DMA section closely enough to verify that this will work with the M3.

See Figure 25-2 in Section 25.6.2 of the datasheet regarding memory controllers, and Section 26, “Peripheral DMA Controller (PDC)”, regarding DMA.  Also see the eevblog.com page, “[Looking for Cortex M3 or M4 with DMA to GPIO capability](http://www.eevblog.com/forum/microcontrollers/looking-for-cortex-m3-or-m4-with-dma-to-gpio-capability/)”.


body:
May I suggest you decorrelate the acoustic frequency with the sampling frequency ?

While you need the high frequencies to get spatial resolution, what you are interested in is only the signal return amplitude (not the exact waveform), which you could sample at a much lower rate using appropriate analog front end.


message:
digitalWrite queued signals?

I have this simple code who send a signal to a android phone when I press a button:

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

    const int botonPinD = 8;
    const int relayPin =  12;
    int retardo = 100;
    int finBoton=1000;

    void setup() {
      pinMode(relayPin, OUTPUT);

      pinMode(botonPinA, INPUT);
      pinMode(botonPinB, INPUT);
      pinMode(botonPinC, INPUT);
      pinMode(botonPinD, INPUT);
    }
    void loop(){
        botonD = digitalRead(botonPinD);
        if (botonD == HIGH){
       // for simplicity remove botonA, botonB and botonC code, but it's the same with a few digitalWrite
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            delay(finBoton);
          }
          else{
            digitalWrite(relayPin, LOW);
          }
    }

But if I press the button fast (maybe a half a second between clicks) I only receive once the signal.

I'm not very sure about what's happened here (I'm an Arduino newbie). The first signal, has it locked the channel? Can signals be queued? Can I control the way that they are queued?

body:
The main problem I guess you are suffering from is the good old `delay()` blockage.

`delay()` is a terrible function and should be avoided at all costs.  Nothing at all can happen while you are running `delay()` - that means you can't be reading the state of your button - until all your `delay()` calls have finished.

If you want to queue the pressed of the button you will need to do three things:

1. You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
2. You will have to queue that button press somewhere. The simplest way is to maintain a count of how many times the button has been pressed.
3. You will have to process any pending button presses ("while the count > 0") by triggering your output with the right timing without using `delay()`, which means using `millis()` and maintaining state information.


body:
The code below is closer to what you seem to be asking about:

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

    // For Mega2560

    const int BUTTONS = 4;
    const int FIRST_SWITCH = 18;
    const int FIRST_RELAY =  41;
    const int CLICKS = 5;
    const unsigned long DEBOUNCE_TIME = 20;  // ms

    int retardo  = 300;
    int finBoton = 1000;

    volatile byte counts [BUTTONS];
    unsigned long lastPress [BUTTONS];

    void doInterrupts (const int which)
     {
     // debounce
     if (millis () - lastPress [which] < DEBOUNCE_TIME)
       return;

     lastPress [which] = millis ();
     counts [which]++;
     }  // end of doInterrupts

    void pin18Pressed ()
      {
      doInterrupts (0);
      }  // end of pin18Pressed

    void pin19Pressed ()
      {
      doInterrupts (1);
      }  // end of pin19Pressed

    void pin20Pressed ()
      {
      doInterrupts (2);
      }  // end of pin20Pressed

    void pin21Pressed ()
      {
      doInterrupts (3);
      }  // end of pin21Pressed

    void setup()
      {
      // configure inputs / outputs
      for (int i = 0; i < BUTTONS; i++)
        {
        pinMode (FIRST_SWITCH + i, INPUT_PULLUP);
        pinMode (FIRST_RELAY + i, OUTPUT);
        }

      attachInterrupt (5, pin18Pressed, FALLING);
      attachInterrupt (4, pin19Pressed, FALLING);
      attachInterrupt (3, pin20Pressed, FALLING);
      attachInterrupt (2, pin21Pressed, FALLING);

      } // end of setup

    // turn relay on for a particular switch
    void handleSwitchPress (const int which)
      {
      for (int i = 0; i < CLICKS; i++)
      {
        digitalWrite(FIRST_RELAY + which, HIGH);
        delay(retardo);
        digitalWrite(FIRST_RELAY + which, LOW);
        delay(retardo);
      }
      delay(finBoton);
      } // end of handleSwitchPress

    // main loop
    void loop()
      {
     for (int i = 0; i < BUTTONS; i++)
       if (counts [i] > 0)
         {
         handleSwitchPress (i);
         counts [i]--;
         }
      }  // end of loop

---

I'll explain parts of it from above:

### Interrupts

To queue up switch presses we can use an interrupt. The Mega has quite a few external interrupts (See: [attachInterrupt()](https://www.arduino.cc/en/Reference/AttachInterrupt)) so I'll use those. You can read about interrupts on [my page about interrupts](http:/www.gammon.com.au/interrupts).

This code attaches four interrupts handlers:

      attachInterrupt (5, pin18Pressed, FALLING);
      attachInterrupt (4, pin19Pressed, FALLING);
      attachInterrupt (3, pin20Pressed, FALLING);
      attachInterrupt (2, pin21Pressed, FALLING);

Because of the way the hardware works we have to use pins 18, 19, 20 and 21 (there are a couple more but these are in sequence).

I set the switches to be INPUT_PULLUP so that they are normally HIGH when not pressed, and go LOW when you press them. Hence the interrupts are looking for a FALLING edge.

---

### Handle one interrupt

An interrupt handler is like this:

    void pin18Pressed ()
      {
      doInterrupts (0);
      }  // end of pin18Pressed

Since they all do much the same thing I put all of the switch management into one function and used an array of switches, like this:

    volatile byte counts [BUTTONS];
    unsigned long lastPress [BUTTONS];

    void doInterrupts (const int which)
     {
     // debounce
     if (millis () - lastPress [which] < DEBOUNCE_TIME)
       return;

     lastPress [which] = millis ();
     counts [which]++;
     }  // end of doInterrupts

In order to "queue" presses the interrupt handler adds one to a counter, for that array item. (So, pin 18 is position 0, pin 19 is position 1 and so on).

---

### Debouncing

Debouncing of the switches is done by ignoring multiple presses in quick succession:

     // debounce
     if (millis () - lastPress [which] < DEBOUNCE_TIME)
       return;

     lastPress [which] = millis ();

---

### Handling a queued press

Now in the main loop we just check if the counter has gone up, for each switch:

     for (int i = 0; i < BUTTONS; i++)
       if (counts [i] > 0)
         {
         handleSwitchPress (i);
         counts [i]--;
         }

If so, we call `handleSwitchPress` which toggles the relay for the desired number of times.

---

### Code for Uno

If you are using a Uno instead of a Mega2560 you don't have four external interrupts. The alternative version below uses *pin change interrupts* instead of external interrupts.

Pin change interrupts work on all pins of the Uno, however they are in batches of three: Pins A0 to A5, pins D0 to D7 and pins D8 to D13. In the code below I use pins 2, 3, 4 and 5 which are in the batch D0 to D7.

With a pin-change interrupt you only get notification of a *change* to the pin, so the code has to detect whether the pin changed from high to low or low to high.

    // For Atmega328 (eg. Uno)

    const int BUTTONS = 4;
    const int FIRST_BUTTON = 2;
    const int FIRST_RELAY =  8;
    const int CLICKS = 5;
    const unsigned long DEBOUNCE_TIME = 20;  // ms

    int retardo  = 300;
    int finBoton = 1000;

    volatile bool oldState [BUTTONS];
    volatile byte counts [BUTTONS];
    unsigned long lastPress;

    // handle pin change interrupt for D0 to D7 here
    ISR (PCINT2_vect)
     {

     // debounce
     if (millis () - lastPress < DEBOUNCE_TIME)
       return;

     lastPress = millis ();

     // check each switch
     for (int i = 0; i < BUTTONS; i++)
       {
       byte state = digitalRead (FIRST_BUTTON + i);
       if (state != oldState [i])
         {
         oldState [i] = state;  // detect state changes
         if (state == LOW)
           counts [i]++;
         }   // end of state change
       }  // end of for each button

     }  // end of PCINT2_vect

    void setup()
      {

      // configure inputs / outputs
      for (int i = 0; i < BUTTONS; i++)
        {
        pinMode (FIRST_BUTTON + i, INPUT_PULLUP);
        oldState [i] = HIGH;
        pinMode (FIRST_RELAY + i, OUTPUT);
        }

      // pin change interrupt (example for D9)
      PCMSK2 |= bit (PCINT18) | bit (PCINT19) | bit (PCINT20) | bit (PCINT21);  // want pins 2, 3, 4, 5
      PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
      PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7
      } // end of setup

    // turn relay on for a particular switch
    void handleSwitchPress (const int which)
      {
      for (int i = 0; i < CLICKS; i++)
      {
        digitalWrite(FIRST_RELAY + which, HIGH);
        delay(retardo);
        digitalWrite(FIRST_RELAY + which, LOW);
        delay(retardo);
      }
      delay(finBoton);
      } // end of handleSwitchPress

    // main loop
    void loop()
      {
     for (int i = 0; i < BUTTONS; i++)
       if (counts [i] > 0)
         {
         handleSwitchPress (i);
         counts [i]--;
         }
      }  // end of loop


message:
Execute Code sent over Serial

I was wondering if its possible to send code to the Arduino, and then have it execute this code.

What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library.  I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.

Sorry I'm really new at this so if its not possible at all let me know!
Thanks in advance,

-Will

body:
No, it's not possible as you describe it.

The Arduino's main chip, the ATMega328p, is what is known as *Harvard Architecture*.  This means that the Flash memory and RAM both occupy completely separate memory address spaces.  The CPU in the chip is only able to fetch its instructions from the memory space the Flash is connected to (the *Instruction Bus*) and not the memory space the RAM is connected to (the *Data Bus*).  This means it can only run instructions that are in Flash and not RAM.

It is possible to re-program the flash on the fly - after all, that's what the bootloader does, and while the actual act of reprogramming flash is fairly trivial, generating the instructions in the right way is far from trivial.

There are other options though.

1. Use an interpreted language.  I believe there are versions of BASIC available for the Arduino that would allow you to upload a program through the serial port and execute it.
2. Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno.  Firmata might be of use here.


message:
Student Project Inquiry(Building a Self Balancing robot)

I am currently building a self balancing robot using an L298N motors driver,and MPU6050 using an arduino microcontroller.

I managed to control my motors movements with no issues. After I extracted the data from my MPU6050 which was easy by using MPU6050 library I faced a problem: When linking the motors movement according to MPU6050 readings, the sensor freezes and stops showing its data on the serial monitor after giving couple of readings, the motors keep moving. I even have capacitors soldered into my motors to filter the noise. I am definitely sure my sensor works perfectly because it was tested before implemented into the motors drivers circuit and code.

If anyone can give me any hints why does the MPU sensor stop giving readings please.

Thanks.

body:
The MPU6050 is an I2C device.  By default the Arduino uses the internal pullup resistors in the IO pins for the pullups on the I2C bus.

This is bad - it makes the I2C bus *very* susceptible to noise, and motors are *very* noisy devices.

You need to make sure you have appropriate pullup resistors on the I2C bus (3.3KΩ is good) and keep the I2C wires as short as you reasonably can.

Also keeping power sources as separate as possible is essential.  Don't be tempted to use the 5V power from the Arduino to power your motors - you must use an external power source, or the motors will cause havoc with the microcontroller circuitry and communications.


body:
This answer addresses the additional questions in Salah's comment:
>I am using a 12V battery to power my motors and the ground of the battery is linked to the ground of my motor driver then mounted onto the arduino. So you mean i must use 3.3K resistors and connect them to the SDA and SCL pins on the MPU6050??to prevent any oscillations affecting the sensor is that right ?

The MPU-6050 will work ok with Vdd = 3.3 V.  More specifically, page 14 of the 1788002.pdf datasheet for MPU-6000/MPU-6050 products shows
>VDD = 2.375V-3.46V, VLOGIC (MPU-6050 only) = 1.8V±5% or VDD, TA = 25°C

The wiring diagram on page 39 shows SDA and SCL being pulled up to VLOGIC (which is either 1.8 V or VDD, say 3.3 V).

One suitable choice would be to operate an 8 MHz Mega and the 6050 at 3.3 V and pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors.

Another choice would be to operate a 16 MHz Mega at 5 V, operate the 6050 at 3.3 V, pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors, and use 3.3V/5V level translations on SDA and SCL into the Mega.

Built-in pullups for I/O pins on Mega2560 and similar devices are spec'd at 20 KΩ min, 50 KΩ max, so will provide less restoring current when a device releases a pin, than will a 3.3 KΩ resistor, and thus may be less noise-resistant or operate less speedily.

The important issues for your power wiring are these:

1, Isolate the motor drive and logic drives.  They can use the same ground point but motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050.  And use [decoupling capacitors](https://en.wikipedia.org/wiki/Decoupling_capacitor) as necessary.

2, Power the MPU-6050 with 3.3 V or less; pull up SDA and SCL to that level via 3.3 KΩ resistors; use level translators if the Mega operates at a different voltage than the MPU-6050.

*Edit: About Grounding –* For a detailed discussion, see [Staying Well Grounded](http://www.analog.com/library/analogDialogue/archives/46-06/staying_well_grounded.html), an analog.com article.  For overviews, see [Star Grounding](http://web.archive.org/web/20141030161947/http://www.lh-electric.net/tutorials/gnd_loop.html) at lh-electric.net, or at wikipedia, [Ground Noise](https://en.wikipedia.org/wiki/Ground_noise), [Ground Bounce](https://en.wikipedia.org/wiki/Ground_bounce), and [Ground (electricity) Electronics](https://en.wikipedia.org/wiki/Ground_(electricity)#Electronics).  By “motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050” I refer to the use of separate wires for conducting ground current.  Typically, this will matter only if your motor current is high or noisy.  The idea is to have a heavy wire from the ground post of the battery to the motors, and a separate wire from the ground post of the battery to the Arduino and the MPU-6050.  Voltage across a wire changes as current in the wire changes.  Using separate ground wires, the Arduino and the MPU-6050 are less affected by ground wire voltage changes caused by motor current.


message:
Optimizing an Arduino code

I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:

    int counter = 0;

    // Charge the capacitor
    digitalWrite(8,HIGH);

    while (digitalRead(7) == LOW) {
        counter = counter +1;
        if (counter > 250) {
            break; // CHARGING FAILED!
        }
    }
The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged).

However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.

So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:

    byte counter = 0;

    // Charge the capacitor
    digitalWrite(8,HIGH);

    while ((PIND & (1<<PD7)) == 0) {
        counter = counter +1;
        if (counter > 250) {
            break; // CHARGING FAILED!
        }
    }
Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.

Is there any further optimizations?

Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?

Is there a more clever and faster way to do this loop?

-----------------------
* Update:

I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.

Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.

body:
Get rid of the loop altogether. Instead of twiddling and checking bits manually, use timer 1 to trigger the output and capture the input.

If you perform the output on pin 10 and the input on pin 8 then you can use timer 1's output compare to send the pulse out and its input capture to detect when the capacitor has charged.

Untested:

    #include <avr/interrupt.h>

    void setup(void)
    {
      cli();
      DDRB |= _BV(PB2); // Configure OC1B as output
      TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop timer 1
      TCNT1 = 0; // Initialize timer count
      OCR1A = 0xffff; // Reset the timer at this count
      OCR1B = 0xf000; // Upper limit of the timed value, plenty of time before timer reset
      ICR1 = 0xff00; // Set to an invalid initial value
      TCCR1A = _BV(COM1B1); // Trigger output at 0, clear at upper limit
      TCCR1B = _BV(ICES1); // Capture on leading edge
      TCCR1B |= _BV(WGM13) | _BV(WGM12); // High bits for 16-bit fast PWM
      TCCR1A |= _BV(WGM11) | _BV(WGM10); // Low bits for 16-bit fast PWM
      TIMSK = _BV(ICIE1) | _BV(OCIE1B); // Enable input capture and limit interrupts
      sei();
      TCCR1B |= _BV(CS10); // Start the timer at its highest clock speed
    }

    ISR(TIMER1_CAPT_vect)
    {
      TIMSK &= ~(_BV(ICIE1) | _BV(OCIE1B)); // Disable input and limit interrupts
      TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop the timer
      PORTB &= ~_BV(PB2); // Kill the charging output
      // Check ICR1 for the captured value
    }

    ISR(TIMER1_COMPB_vect)
    {
      if (ICR1 == 0xff00)
      {
        // WELL CRAP, charging is taking too long
        // Maybe try with a slower clock?
      }
    }

    void loop()
    {
      // Do other stuff
    }


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

It looks like Ignacio Vazquez-Abrams and I have been doing similar things. :)

I have a page about making a capacitor tester:

[Turn your Arduino into a capacitor tester](http://www.gammon.com.au/forum/?id=12075)

However since link-only replies are frowned on (the link might go down) I'll summarize it here.

The simple approach is to charge the capacitor until it reaches 63.2% of the charging voltage.

That is because:

    1 - e^(-1) = 0.63212

See [RC Time constant - Wikipedia](http://en.wikipedia.org/wiki/RC_time_constant).

We can use the Analog Comparator to trigger an interrupt when the voltage reaches that level.

We need the capacitor to be on pin D6 on the Uno and a reference voltage on pin D7.

See [Using the Arduino Analog Comparator](http://www.gammon.com.au/forum/?id=11916) for more details about the Analog Comparator.

This is much faster than using analogRead, because it triggers on an exact voltage.

Your basic objective is to find how long it takes to reach 63.2% of the supplied voltage (in the example being 1 volt):

[![Capacitor tester 1][1]][1]

In this particular example it took 47 µs for a 47 nF capacitor:

[![Capacitor tester 2][2]][2]

Instead of using an exact reference voltage (ie. 63.2% of 5 volts) you can do some fancy maths instead. Here is my test circuit:

[![Capacitor test circuit][3]][3]

*DUT = Device Under Test*

We plug the values of the resistors into the code like this:

    const float Rc = 10000;    // charging resistor
    const float R1 = 1000;     // between ground and D7
    const float R2 = 1800;     // between +5V and D7
    const float clockRate_us = 16;  // 16 MHz
    const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

**Note**: For high accuracy you should use the *measured* resistance values, not just the nominal ones.

---

Now with some fairly simple code we can use the constant **k** to work out the capacitance:

    /*
    Capacitance meter

    Author: Nick Gammon
    Date:   2 July 2013

    Pulse pin (D2): Connect to capacitor via 10K resistor (Rc)

    Reference voltage connected to D7 (AIN1) as per below.

    Measure pin (D6 - AIN0) connected to first leg of capacitor, other leg connected to Gnd.

    Like this:

    Capacitor to test:

    D2  ----> Rc ----> D6 ----> capacitor_under_test ----> Gnd

    Reference voltage:

    +5V ----> R2 ---> D7 ---> R1 ----> Gnd

    */

    const byte pulsePin = 2;   // the pin used to pulse the capacitor
    const float Rc = 10000;    // charging resistor
    const float R1 = 1000;     // between ground and D7
    const float R2 = 1800;     // between +5V and D7
    const float clockRate_us = 16;  // 16 MHz

    const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

    volatile boolean triggered;
    volatile boolean active;

    volatile unsigned long timerCounts;
    volatile unsigned long overflowCount;

    ISR (TIMER1_OVF_vect)
    {
      ++overflowCount;               // count number of Counter 1 overflows
    }  // end of TIMER1_OVF_vect

    ISR (TIMER1_CAPT_vect)
      {
      // grab counter value before it changes any more
      unsigned int timer1CounterValue;
      timer1CounterValue = ICR1;  // see datasheet, page 117 (accessing 16-bit registers)
      unsigned long overflowCopy = overflowCount;

      if (active)
        {
        // if just missed an overflow
        if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 0x7FFF)
          overflowCopy++;
        // calculate total count
        timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
        triggered = true;
        digitalWrite (pulsePin, LOW);  // start discharging capacitor
        TCCR1B = 0;    // stop the timer
        }  // end if active
      }  // end of TIMER1_CAPT_vect

    void setup ()
      {
      pinMode (pulsePin, OUTPUT);
      digitalWrite (pulsePin, LOW);

      Serial.begin (115200);
      Serial.println ("Started.");
      ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
      ACSR = bit (ACIC);    // Analog Comparator Input Capture Enable
      DIDR1 |= bit (AIN1D) | bit (AIN0D); // Disable digital buffer on comparator inputs
      PRR = 0;
      }  // end of setup

    void startTiming ()
      {
      active = true;
      triggered = false;
      noInterrupts ();

      // prepare timer
      overflowCount = 0;            // no overflows yet
      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;      // Counter to zero
      // Timer 1 - counts clock pulses
      TIMSK1 = bit (TOIE1) | bit (ICIE1);   // interrupt on Timer 1 overflow and input capture

      // get on with it
      digitalWrite (pulsePin, HIGH);  // start charging capacitor
      // start Timer 1, no prescaler
      TCCR1B =  bit (CS10) | bit (ICES1);  // plus Input Capture Edge Select
      interrupts ();

      } // end of startTiming

    void finishTiming ()
      {
      active = false;
      Serial.print ("Capacitance = ");
      float capacitance = (float) timerCounts * k;
      Serial.print (capacitance);
      Serial.println (" nF");
      triggered = false;
      delay (3000);
      }  // end of finishTiming

    void loop ()
      {
      // start another test?
      if (!active)
        startTiming ();

      // if the ISR noted the time interval is up, display results
      if (active && triggered)
        finishTiming ();

      }  // end of loop

---

For extra accuracy the code uses the Input Capture Unit, which is something that remembers the exact value in Timer 1 when the match occurs. This avoids the delay of 2 to 3 µs while the ISR kicks into action.

---

### Results

I measured a few values using a capacitance-substitution box. To check on the box I measured also with a high-precision multimeter. The value on the right is what the sketch gave (rounded).

*(All values in nF)*

    Nominal    Meter     Sketch
    Value      Measure   Measure

        40         42        42
       100         98       102
       200        202       201
       300        312       313
       400        389       391
      1000       1004      1010
      2000       2011      2012
      3000       2950      2953
      4000       4160      4170

The sketch output certainly seems to be close to the nominal and measured values.

---

> What about using the internal voltage reference (1.1v) instead of AIN0? which one will be better as the 2xAA batteries voltage drops over time?

The voltage doesn't matter as it is not in the equation. It is the **ratio** that matters, and that will scale with battery drop (ie. the ratio between the two resistors will always be the same).

You need to use Vcc because it is turned on and off at an output pin (to start charging the capacitor).

---

> Also what is the difference between TIMER1_CAPT_vect which you used here and ANALOG_COMP_vect which you used in the example in your site?

If you are **not** using the Input Capture Unit, then you need to get the Analog Comparator interrupt. However if you use the Input Capture Unit then you use the Timer1 Capture Event which is triggered when you get the capture.

  [1]: https://i.stack.imgur.com/3uMaN.png
  [2]: https://i.stack.imgur.com/K1r42.png
  [3]: https://i.stack.imgur.com/snZkL.png


message:
Does Anemometer consumes power?

I planning to add an anemometer to my small solar weather station.
I designed this system to run from a single 3.7v rechargeable battery and a solar panel so I have to calculate in more power drain.

What I don't really understand is do these anemometers consume any external power or just give out a voltage by themselves?

This one doesn't even have consumption specified:

https://www.adafruit.com/products/1733

For this Supply voltage : 5V - 24VDC:

http://www.ebay.com/itm/JL-FSX2-4-20MA-0-5V-Output-Wind-Speed-Sensor-Wind-Speed-Transmitter-Anemometer-/331521148973?hash=item4d3033482d

body:
If it runs on electricity it definitely consumes power, its only how much the real question is.

Since you are working with electronics I am going to assume that you have a multimeter, if you dont have one. Its about time you did, doesnt cost much and will save you a ton of time debugging.

Nearly every multimeter has an onboard ammeter (the accuracy will be mentioned in the instructions manual). You can use this to determine the current consumed, have a look at a tutorial from [sparkfun][1] on how to do this

  [1]: https://learn.sparkfun.com/tutorials/how-to-use-a-multimeter/measuring-current


message:
problem with using String()

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

I'm new to arduino and currently trying to build a small program with multiple screens and buttons and a counter. when I try to convert a int to a chararray it messes up the world. with out it what I have so far works any suggestions on what I'm doing wrong? with the code to convert the int to chararray it seems to lock up the program when I switch from main screen to options screen then back. I put some serial outs to narrow down where the flaw is.

My results are it is between

       test1++;  Serial.println("oops check");
       str = String(test1); Serial.println("sanity check");

Something hangs it up after it outputs "oops check" so I figure it is `str = String(test1);` I have been searching and trying every thing I can find. if someone can give me a kick in the right direction. I'm usin the tft seedstudio v2 display with the modified tft library for text direction.

       /*
      Title: TouchScreenButton Tutorial
      About: Example/tutorial file for how to create buttons with the TouchScreenButtons library
      Author: Richard Kirkpatrick
      Date: 20 July 2014
    */

    // Libraries
    #include <stdint.h>
    #include <SeeedTouchScreen.h>  // Library for the Seeed Studio TFT Touch Shield
    #include <TFTv2.h>      // Library for the Seeed Studio TFT Touch Shield
    #include <TouchScreenGeometry.h> // Library for drawing geometric shapes for the touch screen
    #include <TouchScreenStrings.h> // Library for drawing strings for the touch screen
    #include <TouchScreenButtons.h> // Library for creating buttons for the keypad
    #include <SPI.h>

    //Measured ADC values for (0,0) and (210-1,320-1)
    //TS_MINX corresponds to ADC value when X = 0
    //TS_MINY corresponds to ADC value when Y = 0
    //TS_MAXX corresponds to ADC value when X = 240 -1
    //TS_MAXY corresponds to ADC value when Y = 320 -1
    #define TS_MINX 890*2
    #define TS_MAXX 116*2
    #define TS_MINY 913*2
    #define TS_MAXY 83*2

    TouchScreen ts = TouchScreen(XP, YP, XM, YM);

    // Global variables
    String str;
    Button bigButton;
    Button buttons[12];
    Button reset;
    Button back;
    int screen = 1;
    int test;
    int test1 = 0;
    char b[5];

    void setup()
    {
      // Initializes the TFT library
       Tft.TFTinit();

      // Start the Serial port. Used to determine which button was pressed.
      Serial.begin(9600);
     screen = 1;

    }

    void loop()
    { test1++;  Serial.println("oops check");
      str = String(test1); Serial.println("sanity check");
      str.toCharArray(b,5);

      Serial.print("screen = "); Serial.print(screen );
      // A point objects holds x, y, and z coordinates
      Point p = ts.getPoint();
      p.x = map(p.x, TS_MINX, TS_MAXX, 240, 0);
      p.y = map(p.y, TS_MINY, TS_MAXY, 320, 0);

      // Determine which button was pressed
      int userInput = -1; // -1 means no button is pressed
      if (p.z > __PRESURE){
        userInput = getButtonNumber(p.x, p.y);
         Serial.print("X = "); Serial.print(p.x);
         Serial.print("\tY = "); Serial.print(p.y);
         Serial.print("\tPressure = "); Serial.println(p.z);
      }

       // Show which button was pressed on the Serial monitor

       if (userInput == 13) {
        Serial.println("Options button was pressed!");
        bigButton.buttonDisplay();
      }
       if (userInput == 15) {
        Serial.println("back button was pressed!");
        back.buttonDisplay();
      }
      else if (userInput == 14) {
        Serial.println("reset button was pressed!");
        reset.buttonDisplay();
      }

      delay(10);

    if (screen == 1)  {

    if (test == 1) {

        Tft.fillScreen();    }

      Serial.print("test1 =  "); Serial.println(b);      // prints "Hello String"

        // Draw reset button
       reset.setValues(75, 215, 35, 100);
      reset.draw();

     // Draw the big button
      bigButton.setValues(15, 185, 35, 130);
      bigButton.draw();
    Tft.drawRectangle(40, 15, 70, 120,BLUE);

    Tft.setDisplayDirect(UP2DOWN);

      Tft.drawString("Frays",100,20,2,RED);

       Tft.drawString(b,65,20, 2, BLUE);

      //Draw reset buttons text
      TouchScreenString resetText("RESET", 100, 230, 2, RED);
      resetText.drawText();
     Serial.println("a");      // prints "Hello String"

      // Draw the big button's text
      TouchScreenString bigButtonText("OPTIONS", 40, 197, 2, WHITE);
      bigButtonText.drawText();
    test = 0;

    }

    if (screen == 2)  {

      if (test == 0) {Tft.fillScreen();}
     // draw back button
      back.setValues(15, 15, 35, 85);
      back.draw();

    Tft.setDisplayDirect(UP2DOWN);

       // Draw the back button's text
      TouchScreenString backText("BACK", 40, 30, 2, WHITE);
      backText.drawText();
    test = 1;
    }}

    // Gets which button was pressed.  If no button is pressed, -1 is returned.
    int getButtonNumber(int xInput, int yInput)
    {

    if (screen == 1) {
      if (bigButton.isPressed(xInput, yInput)) {
        screen = 2;
        return 13; // Signifies big button was pressed
      } }
      if (screen ==2) {
      if (back.isPressed(xInput, yInput)) {
        screen = 1;
        return 15; // Signifies big button was pressed
      }}
      if (screen == 1) {
      if (reset.isPressed(xInput, yInput)) {
        test1 = 0;
        return 14; // Signifies reset button was pressed
      }}
      else {
      return -1; // Signifies no button was pressed
      }
    }

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

My guess is you are running out of RAM. Your various string constants alone take up 202 bytes. Then there is this:

      test1++;
      str = String(test1);
      str.toCharArray(b,5);

That is very likely to fragment memory, as `test1` gets larger and larger. So you are fragmenting RAM, of which you don't have much to start with.

Why are you even converting test1 into a String object? And then converting it back into an array?

The array `b` can only hold 4 digits as it needs one byte for the trailing null-terminator.

I suggest you stop doing that String stuff, and also use the `F()` macro like this ...

Change:

        Serial.println("Options button was pressed!");

to:

        Serial.println(F("Options button was pressed!"));

Ditto for all the other places you are displaying stuff.


message:
Microphone input into Arduino uno R3

I have an amplifier circuit for a microphone.The output of the circuit(the microphone signal amplified) is connected to the arduino A0 .Now the circuit works(I think ,the output voltage is 4.30 V) and the arduino serial monitor output 875 874... fluctuates with one or 1,2 or more points.The problem is that this value just goes down from 875....800.... .

 Is it a correct value?(circuit taken from here http://wiring.org.co/learning/basics/microphone.html)

EDIT: If I put my finger on it the values go up a bit like 792 ,794,800

body:
[This schematic][1] contains also the OpAmp stage for a microphone.
You could take it as reference against the design you are using.
The LM386 is basically a more integrated version, iirc.

  [1]: https://courses.edx.org/asset-v1:BerkeleyX+EE40LX+2T2015+type@asset+block/robot_schematic.pdf


body:
The amplifier circuit you refer to puts out 2.5 volts even without input from microphone. The LM386 has internal circuitry to make the output 1/2 of the +5 volts. Then, audio signal goes above and below the 2.5 volts.

The amplifier circuit will only be putting out the PEAK of your audio signal (because D1 and C2 is a peak detector)

So, when all is quiet, take that ADC value as meaning zero microphone input.


message:
How can I configure Arduino after programming it (for post upload wifi configuration)?

I would like to make a device that can take a photo, and send it to a website over wifi. I'm using an Arduino Uno, a ArduCam OV2640 module, and ESP8266 Serial WIFI module. Eventually I'd like to take it off the board as a stand alone project for permanent use.

The wifi works fine, but requires a serial communication to configure. I would like to make it so that I can plug the device into a computer (via something like micro usb), change the WIFI settings, and save those settings for future reboots.

If there anyway I can do this with an Arduino interface? If not, what could I use instead?

body:
I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface.  I've been dealing with the same question myself and this might be a workable solution.  The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.

Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield.  You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.


message:
How to measure nitrogen flow through a tube?

I am looking for a simple way to detect nitrogen gas flow through a tube. I don't even need any sort of precision, just really need to know if flow exists or not.

What are some options I could pursue to easily measure this with the arduino?

body: You can use a [pressure sensor](http://www.trossenrobotics.com/p/phidget-differential-gas-pressure-sensor.aspx?feed=Froogle&gclid=CjwKEAjwmZWvBRCCqrDK_8atgBUSJACnib3l5u8e1KI9v_tjJWO6weY6IH03922kPj8-jWhzubchsBoCtErw_wcB) for gas and measure the pressure differential between two points and if there is a large pressure differential then you know a flow exists.


body:
What you are looking for is a mass flow sensor[ (MAF)](https://en.wikipedia.org/wiki/Mass_flow_sensor), or something along those lines as you mention wanting to know if there is flow, this gives you the *'speed'* of the flow. There are various types available according to size, flow rate, type of element, and accuracy. Just search for mass flow sensor, you can even hack them off cars.

If you just want to detect only the presence of the N2 as you say then you can split your pipe somewhere,and then add a T-piece to that. You then put a gas sensor in the T part, and seal it off so there is no leaks. You would then hook that up to the Arduino board and interpret the signal.

Can't recommend any specific sensors though.

Here is an image for the idea:

![RSM_design][1]

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


message:
How to store IR data needed for AC controll in less space?

I'm trying to controll an AC unit but the issue is space - right now, I store the data like this:

    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp30[] = {233,636,17884,3032,8944,500,496,492,1496,524,472,548,452,544,448,552,444,552,444,548,444,552,444,552,1436,556,444,552,444,548,1440,552,472,524,472,520,1472,492,1496,520,1468,556,1436,552,1440,552,444,548,448,548,444,552,448,548,448,548,448,548,472,524,468,524,472,524,476,520,472,520,476,520,476,520,472,524,472,552,444,548,452,548,444,552,444,548,448,548,444,552,448,544,452,544,448,552,472,524,468,524,472,524,472,524,472,520,476,520,476,520,472,524,1468,552,1436,556,1436,556,1436,552,2944,3028,8920,548,1440,552,448,548,472,524,468,524,472,524,472,472,524,516,476,552,444,548,1444,552,444,548,448,552,440,556,440,556,1432,556,1440,548,452,544,1444,552,1464,524,1464,472,1520,524,1464,556,1436,552,1440,552,1436,556,440,552,448,548,444,552,1440,552,1440,552,1464,524,472,496,496,472,524,520,476,548,444,552,448,552,1440,548,1440,556,1432,556,1440,548,448,548,444,552,448,548,472,524,472,524,1464,472,524,472,524,516,476,552,444,552,444,552,1440,552,1440,552,1436,556,1436,552};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp29[] = {233,636,17896,3032,8916,552,468,524,1468,524,468,500,496,472,528,520,476,544,448,552,444,552,444,548,1440,556,440,552,448,548,1440,552,444,548,452,544,1444,548,1468,524,1464,472,1520,520,1468,552,444,552,448,548,444,552,444,548,448,548,444,552,444,556,444,548,448,548,444,552,448,544,472,524,472,524,472,524,472,468,528,520,476,544,448,552,444,552,444,548,444,556,440,556,444,548,448,548,444,552,444,552,444,548,452,544,476,524,472,524,468,524,472,492,1496,520,1472,548,1440,556,1440,548,2944,3032,8916,552,1436,552,444,552,444,548,452,544,448,548,476,524,468,524,472,524,472,492,1496,520,476,524,472,548,448,552,444,552,1440,548,1440,548,448,548,1440,556,1440,548,1440,552,1464,524,1464,500,1496,520,1468,552,1440,548,444,556,444,552,444,548,1440,552,1440,548,1444,544,476,524,472,524,472,524,468,524,472,492,1496,524,476,548,1444,548,1440,548,1444,552,444,552,444,548,448,548,444,552,448,544,1448,544,476,524,468,524,472,524,472,492,504,516,1472,548,1444,552,1440,548,1440,548};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp28[] = {233,636,17880,3056,8912,524,476,544,1444,552,444,548,448,552,440,556,440,556,444,552,444,548,444,552,1440,552,444,552,468,524,1468,524,468,472,524,520,1476,544,1444,548,1440,556,1432,556,1440,548,448,548,444,552,448,548,448,548,472,524,472,520,472,524,472,496,500,472,524,492,504,544,452,548,444,552,444,552,444,548,448,552,440,556,444,548,448,548,444,552,448,544,452,544,476,524,472,524,468,524,472,524,472,492,500,520,476,548,452,544,448,552,444,552,1440,548,1440,552,1440,552,1440,548,2944,3028,8924,544,1444,552,468,524,472,496,500,492,504,516,476,552,444,548,452,548,444,552,1440,548,444,552,444,552,1444,548,444,552,1440,548,1444,544,476,520,1472,492,1496,520,1468,552,1444,548,1440,552,1436,552,1440,552,1440,552,444,548,452,544,476,520,1468,524,1468,492,1496,520,480,544,448,548,448,552,444,548,444,552,444,548,452,548,1440,552,1436,552,1444,544,476,520,476,524,468,524,472,496,500,492,1496,524,476,544,452,548,444,552,444,548,448,548,1444,548,1440,552,1440,548,1444,520};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp27[] = {233,640,17892,3032,8916,552,448,548,1464,528,468,528,468,468,528,468,528,520,472,552,444,552,444,552,1440,548,448,548,444,556,1436,552,444,552,444,552,1436,552,1444,548,1468,492,1496,472,1516,552,448,548,448,548,448,548,444,552,444,552,444,552,440,556,444,552,444,548,444,552,448,548,448,548,472,524,472,524,468,468,528,472,524,520,472,524,472,552,448,548,448,548,444,552,444,548,448,548,444,556,440,552,448,548,444,552,444,552,448,544,472,524,472,528,1464,468,1520,520,1472,552,1436,556,2944,3028,8912,556,1440,548,448,548,444,552,448,548,448,548,444,552,472,520,472,524,472,524,1464,472,528,488,508,544,448,552,444,552,1436,556,1436,552,448,548,1440,548,1440,556,1440,548,1440,552,1464,524,1464,472,1524,544,1444,552,444,552,448,548,444,552,1440,548,1440,552,1444,548,444,552,448,544,472,524,472,524,468,500,1492,492,1500,548,452,544,1440,556,1436,552,444,552,444,552,444,548,448,548,448,548,1444,548,472,524,468,524,472,524,472,472,528,468,1520,520,1468,552,1440,552,1436,552};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp26[] = {233,640,17884,2980,8992,528,472,524,1464,472,524,520,476,548,444,556,440,556,444,548,444,552,444,552,1440,552,440,556,444,548,1440,552,444,552,468,524,1468,528,1460,472,1520,548,1444,548,1440,556,444,548,448,548,444,552,444,552,444,552,444,552,444,552,444,548,448,548,472,524,468,524,472,472,528,468,528,488,504,548,448,552,444,548,444,556,440,556,444,548,444,552,444,552,444,548,448,548,448,552,444,548,448,548,472,524,472,520,472,524,472,472,524,520,1468,548,1444,552,1440,552,1436,556,2944,3024,8920,552,1440,552,444,548,444,552,448,548,468,524,472,528,472,468,524,468,528,520,1472,548,444,556,444,548,1440,552,444,548,1440,556,1440,548,444,552,1440,548,1444,552,1464,492,1496,520,1472,548,1440,556,1440,548,1440,552,444,552,444,552,444,548,1440,552,1444,548,1440,548,472,524,472,472,524,472,520,520,480,544,452,548,1440,548,448,548,1440,552,1440,552,444,548,448,548,448,552,444,552,468,524,1464,524,472,472,528,468,524,468,528,544,452,548,1440,556,1436,552,1440,548,1440,556};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp25[] = {233,644,17892,3028,8916,552,444,548,1440,556,440,552,448,548,444,552,444,548,448,548,448,548,472,528,1464,468,528,520,472,548,1448,544,444,556,440,556,1440,548,1440,548,1440,556,1440,548,1440,552,448,544,472,528,472,524,468,468,528,468,528,544,448,552,444,552,444,552,444,552,444,552,444,552,444,548,444,552,444,552,444,552,448,548,444,552,468,524,472,524,472,524,468,472,524,472,528,520,476,544,448,552,444,548,448,548,444,556,440,556,444,548,444,552,1440,548,1440,556,1440,548,1468,548,2920,3052,8920,472,1516,548,452,548,444,552,444,548,448,548,444,556,440,556,444,548,448,548,1440,548,452,544,448,552,1440,548,472,524,1464,472,1516,552,448,544,1444,552,1444,548,1440,552,1436,552,1440,552,1440,552,1440,548,1464,528,472,496,500,468,524,520,1472,548,1440,556,1436,552,444,552,444,556,440,552,444,552,444,552,1436,552,448,544,452,548,1468,524,1464,468,528,520,472,552,448,548,448,548,448,548,1440,548,448,548,444,552,444,556,444,548,444,552,1440,548,1440,552,1464,500,1496,548};

The first item is the length of the array and the rest is data I can send with IRemote library with the raw send libray. I've mapped most of the buttons and now I'm at

    Sketch uses 95.286 bytes of program storage space

Is there a better encoding that could take less space? I'd like to add at least 3 times more commands to the Sketch, but I'm already at 37% on an Arduino Mega.

I know ideally I should generate the array, not store it, but I haven't gotten that far (yet, I'm working on it) and for me this is an interesting issue.

Thank you!

---
Edit 1: Code uploaded on GitHub - https://github.com/vladbabii/SamsungACIrControll/tree/master/AC_IrControll

body:
Do you need all of the data accessible at once? How about storing it on a file device or external memory? SDcards are slow but huge. [FRAM][1] devices a fast but not as huge and typically aren't formatted for a file system. They act more like an independent memory space accessed by a function. (The Adafruit product is one example; I'm sure there are more).

  [1]: https://www.adafruit.com/products/1895


body:
I have analysed your codes with a small Lua script:

<!-- language-all: lang-lua -->

    function pairsByKeys (t, f)
      local a = {}
      -- build temporary table of the keys
      for n in pairs (t) do
        table.insert (a, n)
      end
      table.sort (a, f)  -- sort using supplied function, if any
      local i = 0        -- iterator variable
      return function () -- iterator function
        i = i + 1
        return a[i], t[a[i]]
      end  -- iterator function
    end -- pairsByKeys

    nums = {233,636,17884,3032,8944,
    -- and so on ...
    548,444,552,444,556,444,548,444,552,1440,548,1440,552,1464,500,1496,548}

    uniq = { }

    for k, v in ipairs (nums) do
      if uniq [v] then
        uniq [v] = uniq [v] + 1
      else
        uniq [v] = 1
      end -- else
    end -- for

    count = 0

    for k, v in pairsByKeys (uniq) do
      print (string.format ("%8i = %3i", k, v))
      count = count + 1
    end

    print ("count = ", count)

---

Results:

         233 =   6
         440 =  18
         444 = 154
         448 =  86
         452 =  20
         468 =  42
         472 = 103
         476 =  27
         480 =   2
         488 =   2
         492 =  15
         496 =   8
         500 =  10
         504 =   4
         508 =   1
         516 =   4
         520 =  41
         524 =  97
         528 =  26
         544 =  39
         548 = 189
         552 = 196
         556 =  56
         636 =   3
         640 =   2
         644 =   1
        1432 =   3
        1436 =  24
        1440 =  91
        1444 =  26
        1448 =   2
        1460 =   1
        1464 =  21
        1468 =  16
        1472 =   8
        1476 =   1
        1492 =   1
        1496 =  12
        1500 =   1
        1516 =   3
        1520 =   5
        1524 =   1
        2920 =   1
        2944 =   5
        2980 =   1
        3024 =   1
        3028 =   4
        3032 =   4
        3052 =   1
        3056 =   1
        8912 =   2
        8916 =   4
        8920 =   3
        8924 =   1
        8944 =   1
        8992 =   1
       17880 =   1
       17884 =   2
       17892 =   2
       17896 =   1
    count =  60

---

Assuming there is some jitter I rounded them to the nearest 50:

    for k, v in ipairs (nums) do

      v = math.floor (v / 50)    -- <--- add this
      v = v * 50                 -- <--- add this
      if uniq [v] then
        uniq [v] = uniq [v] + 1
      else
        uniq [v] = 1
      end -- else
    end -- for

---

Results:

         200 =   6
         400 = 258
         450 = 219
         500 = 411
         550 = 252
         600 =   6
        1400 = 146
        1450 =  60
        1500 =  10
        2900 =   6
        2950 =   1
        3000 =   9
        3050 =   2
        8900 =  11
        8950 =   1
       17850 =   6
    count =  16

So, 16 different lengths.

---

So now you can use 4 bits per code (and a lookup table) rather than 16 bits.

Also see [TV-B-Gone design notes](https://learn.adafruit.com/tv-b-gone-kit/design-notes) for how they compressed the IR codes for lots of TV brands into a small table in an ATtiny85.


body:
Another form of storage is the EEPROM. There are between 512 bytes and 4K of EEPROM per Arduino, depending on the model of Arduino - see https://www.arduino.cc/en/Reference/EEPROM

EEPROM is persistent when the power gets cut, and MAY or may not be overwritten when the program is changed - I have not tried. If it is not overwritten, you can write a sketch just to set it, then overwrite it with your IR sketch; otherwise, you may have to set up some way to "upload" the data into your sketch (e.g. if you press a special button, it will listen on the serial port, any bytes it reads it will write to the EEPROM.

If you have an ISP (aka ICSP) programmer such as the USBasp (see google), which are very inexpensive, then you can read/write the EEPROM directly - all you need is 6 pins exposed. You can also use the USBasp to reprogram an AtMega/AtTiny which is not on an Arduino board (this also gives you a little extra program space, since it no longer requires a bootloader).


message:
Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock

Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock.  Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated.  The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running with Atmel Studio.

Thanks!

body:
If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose `Burn Bootloader` from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.


message:
Light communication from pc/app to arduino

I will like to implement a serial communication protocol, using javascript in a mobile browser to make the browser background blink (alternating the color from black to white) according to the bits, to communicate a few bytes to an Arduino using some kind of light sensor (photo diode or resistor) to parse. Electric Imp did something with https://electricimp.com/platform/blinkup/ .

Is there any library or implementation or where to start guide?, if not, how would you implement it?

I fear one of the problems of using a mobile browser with javascript to light-encode the bits will be timing issues, since setTimeInterval is not perfect, I could split the screen, one half blinking continuously (clock) and the other half the data, but that will require two light sensors.

body:
Doing bit stuffing can prevent timing problems when you are sending a lot of `0`s or `1`s in an row. Alternatively use Manchester encoding (slower).

On the browser side, I'd suggest using `<Canvas>`. Combine this with `requestAnimationFrame` which gives you a very accurate timestamp as an argument. Though you have to check for support as older browsers don't support that.


body:
You should investigate communication protocols and encoding techniques that embed the clock signal into the same data stream as the data signal.

One common method is called *[Manchester Coding][1]*.  This entails splitting each bit into two halves.  A 1 sends light followed by dark, and a 0 sends a dark followed by a light.  It's then up to you to work out which transitions are which and where in a bit they occur (is a high transition the start of a 1 or mid-way through a 0?)

Another popular method (used in things like Ethernet) is called 8b/10b.  That involves sending 10 bits to represent every 8 - more efficient than manchester coding (that could be considered 8b/16b) and can be read about here: https://en.wikipedia.org/wiki/8b/10b_encoding It's somewhat harder to implement than Manchester Code, so although it's less efficient I'd recommend the simplicity of Manchester Code.

  [1]: https://en.wikipedia.org/wiki/Manchester_code


message:
Can anyone identify why this incrementer is losing count?

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

I am working on a project where the end result is to count the number of cycles of a moving piece of metal using an inductive sensor.

For now I am using an Arduino Uno and have created a breadboard version for testing. The sensor has been replaced by a momentary push button. To check the count data I am viewing the number using Serial Monitor

All the elements of this set-up are working, apart from one major issue. When pressing the button the incrementer (++) occasionally adds 2 instead of 1 from only one button press. As a rough guide to the error frequency, it seems to count 11 for every 10 button presses. The error has never presented as not counting enough.

I am new to software, as such I cannot seem to see the error

Any help and guidance would be greatly appreciated

Here is the code I have written so far:

    //Libraries
    #include <EEPROM.h>

    //Constants
    const int counterPin = 2;   //Input from counter (looking for HIGH as external pulldown resistor is used)
    const int EEPROMadress = 3; //holds the EEPROM address

    //Variables
    int counterState = 0;       //current button state
    int counterStatePrv = 0;    //previous button state
    int storedValue;
    int presetCount = 100;

    unsigned long countNumber;      //unsigned 32bit variable

    void setup() {

     for (int i = 0; i < 255; i++) {
      // this performs as EEPROM.write(i, i)
      EEPROM.update(i, i);
     }
     for (int i = 0; i < 255; i++) {
      // write "presetCount" value to cell "EEPROMaddress" only the first time
      // will not write the cell the remaining 254 times
      EEPROM.update(EEPROMadress, presetCount);
     }

     pinMode(counterState, INPUT);
     Serial.begin(9600);

     countNumber = EEPROM.read(3); //Start the counter at the presetCount value
    }

    void loop() {

     counterState = digitalRead(counterPin);   //Read the status of the counter input
     storedValue = EEPROM.read(EEPROMadress);

     if (counterState != counterStatePrv) {      //check that pulse went off
      if (counterState == HIGH) {             //check for pulse
       countNumber++;      //increment (add 1) to the stored count value
       delay(10);
       Serial.print("Count  Value: ");
       Serial.println(countNumber);

       Serial.print("Stored Value: ");
       Serial.println(storedValue);
       Serial.println();

      }
     }
     counterStatePrv = counterState;

    }

body:
Buttons bounce (at least they appear to, electrically), meaning that if you're fast enough, you can detect multiple pulses per button-press. Usually we don't count the button as being pressed until we read the same value {n} times in a row or for {m} mSec, or some similar technique.

Because you call `EEPROM.read()` immediately after testing the button, perhaps most times the bouncing will have ceased when the call returns, but once in a while one last bounce slips through.

Nick Gammon, a regular contributer here, has a good discussion of [de-bouncing][1] on his web site. Have a look at that and pick a technique that's compatible with what you're trying to do.

  [1]: http://www.gammon.com.au/switches


message:
'Simple' problem. Delay not working?

Servo goes to one end, and immediately travels back without a 2s delay inbetween. After it travels back there is a 2s delay before it loops. Why isn't there a 2s delay before the travel back?

    Servo testservo;

    void setup() {
        testservo.attach(9);
    }

    void loop() {
        testservo.writeMicroseconds(700);
        delay(2000);
        testservo.writeMicroseconds(2300);
        delay(2000);
    }

body:
Your description (“Servo goes to one end, and immediately travels back without a 2s delay... After it travels back there is a 2s delay before it loops”) implies an overall cycle time of 2 seconds, which appears to be inconsistent with the overall 4-second cycle implied by the code shown.

Here are things you can do to debug the problem:

1. Turn on an LED before one `writeMicroseconds()` call, and turn it off before the other.  For example, add `pinMode(13, OUTPUT);` in `setup()`, and revise `loop()` as follows:

void loop() {
    testservo.writeMicroseconds(700);
    digitalWrite(13, HIGH);
    delay(2000);
    testservo.writeMicroseconds(2300);
    digitalWrite(13, LOW);
    delay(2000);
}

This may allow you to find out which end the servo is going to.

2.  Besides adding LED signals, try slightly-less extreme times in the `writeMicroseconds()` calls; eg 1000 and 2000 microseconds rather than 700 and 2300.

3.  See if a neutral servo setting works, eg via code like the following.

enum { LEDpin=13, dtime=2000}
void stest(angletime, tHi, tLo) {
    testservo.writeMicroseconds(angletime);
    digitalWrite(LEDpin, HIGH);
    delay(tHi);
    digitalWrite(LEDpin, LOW);
    delay(tLo);
}
void loop() {
    stest(1000, dtime-50, 50); // Go CCW
    stest(1500, 50, dtime-50); // Middle
    stest(2000, 50, dtime-50); // Go CW
}

When this code runs, the LED should stay on about 2 seconds with the servo fully (or nearly so) counterclockwise.  Then the LED should blip and the servo should move to center position and stay there about 2 seconds.  Then the LED should blip and the servo should stay fully clockwise about 2 seconds.  This three-part cycle should repeat every six seconds.  If it works ok, then try modifying it, eg by changing 1000 us to 700, 2000 to 2300, etc, or by decreasing the `dtime` value to see how quickly the servo can respond, etc.


message:
Assigning value inside structure array outside setup and loop functions

I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't.

The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks

    void setup()
    {
    }

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    } trap_game_details[2];

    trap_game_details[0].random_min = 1;

    void loop()
    {

    }

src/sketch.ino:13:5: error: ‘trap_game_details’ does not name a type
     trap_game_details[0].random_min = 1;
     ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed

body:
You can't access array contents in the global scope like that.  You have to assign the entire block of data in one go:

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    };

    struct trap_game_details trap_game_details[2] = {
        { 10, 5, 1, 100, 4 },
        { 8, 23, 5, 95, 8 }
    };

Items in the *global scope* aren't executed - only things in functions are executed.  Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.


body:
> Assigning a value to an int or char array works completely fine but this doesn't.

It only works fine if you do it on the declaration.

eg.

This works:

    int foo = 42;  < ---- declare and define with initial value

This doesn't:

    int foo;   // < ---- declare and define

    foo = 42;  // < ---- assignment statement

Your code was like the second example.

---

Majenko has shown one way. He split the declaration into two parts. The first part declared the **type** trap_game_detail, and the second part is an **instance** of that type, like this:

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    };

    struct trap_game_details trap_game_details[2] = {
        { 10, 5, 1, 100, 4 },
        { 8, 23, 5, 95, 8 }
    };

---

Alternatively, and a bit closer to what you were doing, just keep going with the initialization values after you define the structure, like this:

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    } trap_game_details[2] =
      {
        { 10, 5, 1, 100, 4 },
        { 8, 23, 5, 95, 8 }
      };


message:
Can't get values of max232 with loopback

I didn't find answers which solves my problem with the max232 yet.
I connected it like this to my Arduino uno, so my Arduino provides the +5V VCC and the ground:
[max232 connection][1]
[![Connection on board][2]][2]

The only thing what is differences are that I do a loopback at the RS232 side and I use 1µF for every capacitor even for the bypass one. I did a loopback so I can see if the max232 works. I don't get anything out of it when I send some data to it.
I measure +8.7V on pin2 and -8.15V on pin 6.

My Arduino code:

    /*
      Software serial multiple serial test

     Receives from the hardware serial, sends to software serial.
     Receives from software serial, sends to hardware serial.

     The circuit:
     * RX is digital pin 10 (connect to TX of other device)
     * TX is digital pin 11 (connect to RX of other device)

     created back in the mists of time
     modified 25 May 2012
     by Tom Igoe
     based on Mikal Hart's example

     This example code is in the public domain.

     */
    #include <SoftwareSerial.h>

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

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

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
    }

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

What did I do wrong or is my max232 broken?

**EDIT**

I think the serial monitor (same baudrate) doesn't write to the ports so I rewrite some code.

loop code:

    int i = 0;
    void loop() // run over and over
    {
      if(i == 10)
        i = 0;

      mySerial.write(i);
      Serial.print(mySerial.read());
      i++;
      delay(3000);
    }

In serial monitor I get strange values back for a cascade counter.

Values:
-1 45 49 52 53 52 57 53 ...

These numbers aren't ascii code for ectual numbers I think.

**EDIT 2**

Now the loopback works thanks to the answer below.
Now I replaced the loopback with the module FUM DCF-U.
The loop code has changed to this:

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

The problem is that the result is '000000000000000000000000000000000...' in a fast rate and not every second.

The module gets its 3.3V and is connected to the same GND as the MAX232.

Pin connections:

Arduino - MAX232

11 - 11

0 - 12

MAX232 - FUM DCF-U

14 - 3

13 - 4

Thanks in advance

  [1]: https://www.google.be/search?q=max232&biw=2144&bih=1127&tbm=isch&imgil=fyy0lqGALI9HtM%3A%3BcH09mn8Z6FvbpM%3Bhttp%253A%252F%252Fsodoityourself.com%252Fmax232-serial-level-converter%252F&source=iu&pf=m&fir=fyy0lqGALI9HtM%3A%2CcH09mn8Z6FvbpM%2C_&dpr=0.9&usg=__KByygPTJOBdI1tDfqv3X0dFdvZ4=&ved=0CDEQyjdqFQoTCOG0i8i32McCFYtVPgodYpMMFg&ei=pfbmVaHODour-QHiprKwAQ#imgrc=fyy0lqGALI9HtM:&usg=__KByygPTJOBdI1tDfqv3X0dFdvZ4=
  [2]: https://i.stack.imgur.com/B2iBp.jpg

body:
SoftwareSerial cannot both send and receive at the same time, as it does receiving inside an ISR, and turns interrupts off when sending. Thus this will never work properly.

I suggest you switch to HardwareSerial. Or, if you want to see the results, send using SoftwareSerial and receive using HardwareSerial. For example:

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

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial (10, 11); // RX, TX

    void setup ()
      {
      Serial.begin (115200);
      mySerial.begin (115200);
      }  // end of setup

    unsigned long lastSend;
    char c = ' ';
    void loop ()
      {
      // time for another test send?
      if (millis () - lastSend >= 500)
        {
        mySerial.print (c++);
        if (c > 'z')
          {
          c = ' ';
          Serial.println ();
          }
        lastSend = millis ();
        }

      // check for response
      if (Serial.available ())
        Serial.print (char (Serial.read ()));
      }  // end of loop

I tested that as a simple loopback and it worked fine. Connect pin 11 (Tx) to pin 0 (Rx). Disconnect the wire to pin 0 whilst uploading.


message:
Arduino Command Line Interface - How to change boardsmanager.additional.urls

I am building a Travis CI job to test my Arduino Library and it needs to install external board definitions.

Is there a way that I can set the boardsmanager.additional.urls from the command prompt like it would have been done in the Preferences window?

Or should I create preferences.txt file? (If so where does that live in a Linux environment)

body:
Found the solution:

    arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json"


message:
what is the importance of the resistors that connect to push buttons ? can i replace them by wires?

[![arduino][1]][1]
Please, iam a junior in arduino and i want to know what is the importance of the resistors that connect to push buttons? can i replace them by wires?
thanks in advance.

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

body:
They are what is known as Pull-Up resistors.  The circuit will not work if you replace them with wires.  Not only that but you will short circuit the power supply when you press a button.

Why don't you want to use resistors?

The value is not important - you could use the same value as you are using for the LED if you don't have the 10k resistors shown in the drawing.

Having said that an alternative is to leave them out and instead activate the internal pull-ups within the processor on the Arduino:

    pinMode(pin, INPUT);           // set pin to input
    digitalWrite(pin, HIGH);       // turn on pullup resistors


message:
Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock

Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock.  Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated.  The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running Atmel Studio.

Thanks!

EDIT:  Sorry for double posting, I posted in electronics before I noticed there was an Arduino specific section.


message:
Replacing atmega8 with atmega328 on Arduino Single-Sided Serial Board

i want to know that if i use atmega328-pu instead of atmega8 on this design provided by "https://www.arduino.cc/en/Main/ArduinoBoardSerialSingleSided3", will it works fine on this design or i have to use only atmega8 ?

[![ArduiniBoardSerialSingleSided][1]][1]

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

body:
Yes and no. It will work on this board, but won't get programmed by arduino IDE directly.

ATmega328 and ATmega8 are fully pin compatible. ATmega328 is like bigger and powerful in terms of onchip resources. However, if you want to program ATmega328 on the arduino board, you must install bootloader. Otherwise you will have to program it everytime using ISP programmers such as USBASP. This will connect to the ICSP socket shown on the above board.

Refer to: http://tutorial.cytron.com.my/2011/09/30/how-to-program-arduino-by-using-avr-usbasp-programmer/


message:
I'm looking for a way to serially communicate with a multi mesh Arduino slave network

I have one PC running Visual Studio and a program that will be sending commands to Arduinos via serial COM Ports. So, in 11 Nano MCUs, I will have motor drivers L293D/L298N ICs, while in other Nanos I will have sensors.

What I would like to do is have a program in Visual Studio which sends commands via serial to actuate motors to each and every MCU on board. This is a robotic application and everything I mentioned above will be enclosed within the Humanoid.

Here are some examples of what I'm thinking of doing:

    char data = Serial.read();
    if (data == 'A')
    {
      digitalWrite(13, HIGH);
    }

Or something like this:

    servodata = Serial.read();
    if (servodata == '1') // Single Quote! This is a character.
    {
      SERVO.write(pos);
    }

As you can see, Arduinos will have something like this running and waiting for Visual Studio to send commands via serial to one or multiple MCUs simultaneously. I'm thinking 30 char dividing/spiting that number across each Rx Arduino.

body:
It's not obvious what the exact query is but answering the subject line question:

You can easily multidrop connect multiple serial / RS232 COM ports by having all slave RX inputs and the master TX output on one line, and all slave TX outputs connected by an OR network to a single line to the master's RX input.   The master 'talks' to all slaves at once. Each slave talks to only the master. Only one slave can usefully talk at once. Message destination assignment and slave-talking arbitration is carried out in software.

As shown below, the OR network at each slave can be as simple as a diode with cathode (bar side) to TX line and anode to common line to master RX.  A single pullup resistor (or an internal pullup in the master on the RX line) pulls the line high when all slave TX lines are high.

This diagram shows how simple multidrop communications can be.
**NB - As shown the diodes polarity is for true RS232 with logical 1 = low = negative.**
**When connecting directly between UART TTL lvel (5V/0V) outputs reverse the diodes.**

Also, add a pullup from +5V to the Blue RX line to the master - 10k to 5V is probably OK.

[![Multidrop network for RS232][1]][1]
From here - [**Multidrop network for RS232**](http://cool-emerald.blogspot.co.nz/2009/10/multidrop-network-for-rs232.html).

When a slave TX pin is high its diode is "blocked" and it does not affect the common slave to master level. When any slave TX line goes low the common line is pulled low via its diode and the master sees the low. Normal RS232 COMs can occur between slave and master.

When the master sends all slaves see the transmission at once. A basic protocol must be established to allow messages to be handled by the intended recipient. This could consist of, e.g. sending an address word + command word or words. You can have a single slave act on a message or all slaves or a sunset, based on your addressing system.

The slave to master direction allows only one slave to send at one and you must ensure either that only one slave ever sends at a time and/or that collisions are able to be resolved.

Despite the obvious limitations of such a system it can work very well and is cheap and simple to implement. If there are many slaves the loadings should be checked so that e.g. the master TX is able to drive all slave RXs at once. As the circuit is unidirectional it is easy to add a basic buffer.

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


body:
[RS-485](https://en.wikipedia.org/wiki/RS-485) or [RS-422](https://en.wikipedia.org/wiki/RS-422) are the normal industrial ways of having one serial port talk to many devices, especially in noisy environments with lots of motors.  It requires a driver chip for each device to get the right electrical interface.

RS-485 provides bi-directional communication if you want to receive data back from your remote nodes, and RS-422 provides "simplex" or uni-directional communication if you just want to blindly send commands with no feedback.

As for software, my [ICSC library](http://github.com/MajenkoLibraries/ICSC) would probably be the easiest route to take - it allows you to address individual devices on an RS422 or RS485 bus and send commands to them.


message:
How can I stop my Arduino UNO rev 3 from briefly turning on digital output pins on startup or reset?

I am using my Arduino UNO rev 3 to control other devices via the digital output pins. On startup or reset, I find that these pins are all briefly turned on (perhaps as part of a self test). This interferes with my application. How can I suppress this?

body:
Digital pin 13 will be turned on briefly as part of the bootloading process (it flashes a few times). Thus this is not a good choice of pin for a device like a motor to be connected to. Also if you are uploading a new sketch the Tx pin (digital pin 1) will be turned on and off.

You can change the processor fuses to not use the bootloader, which would avoid these issues, however then you have to change them back to upload a new sketch - unless you upload using ICSP instead of the bootloader.

As Gerben and Majenko have pointed out, any other issues could be from "floating" pins which some devices might interpret as having a HIGH on them, possibly. Pull-down resistors could help there (or pull-up if that is more appropriate).

The ideal thing could be to structure your system in such a way that the two pins (1 and 13) which come on during the bootloading process are connected to something "harmless" (eg. an LED) rather than "harmful" (eg. a motor).


message:
Stepper Motor Power Supply

Just a quick question. Picking up some stepper motors, but confused at what voltage/current things are running off.

Ordering:
2 x [Stepper Motor][1]
2 x [EasyDriver][2]

An article says

> You need some 12V source to the EasyDriver (the motor in this article
> is 12V) - This will be powering the stepper - Im using a 12V adapter -
> similar to the one in the illustration. Just make sure it is rated at
> least 750ma - A higher rating is better, and just means it wont burn
> out.

So does that mean if I got a plug which is regulated 12V 1A and powered the Arduino from that I could power a rail with VIN pin and that would safely supply the EasyDrivers? And I could then use the 5V pin to power everything else?

Just don't want to break anything! Thanks

  [1]: https://www.sparkfun.com/products/9238
  [2]: https://www.sparkfun.com/products/12779

body:
As generic rule: avoid powering one device through another.
It can cause strain on the middle-man device and it _will_ be inefficient.
The only few cases where this might make sense are when it's topologically inconvenient to connect everything to the centralized power supply.
Or if the cascaded device requires a voltage that is not available from the power supply.

In your case you can power both the easy driver and the Arduino from the regulated 12v.

And you won't risk drawing too much current through the Arduino.


body:
The Vin pin is after the M7 protection diode, so you won't get quite 12 V out of Vin. Also, depending on the load, the diode might get warm.

I've also found that powering an Arduino from 12 V input (the maximum recommended) tends to get the voltage regulator hot.

Your other issue is that the motor power will be going through the Arduino board, to an extent (in the plug, through the diode, and out Vin) so any noise generated by the motor will be close to the processor.

I don't think your idea would *break* anything, it just might not be particularly reliable.


body:
Stepper Motor Control - one step at a time

This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.

The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.

Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.

<!-- language: lang-cpp -->

    #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor
    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
    int stepCount = 0;         // number of steps the motor has taken

    void setup() {
        // initialize the serial port:
        Serial.begin(9600);
    }

    void loop() {
        // step one step:
        myStepper.step(1);
        Serial.print("steps:");
        Serial.println(stepCount);
        stepCount++;
        delay(500);
    }


message:
How can I get a unique address for all my Arduino boards while in RS485?

My attempt is to know how to identify the board I'll be sending parameters to in a serial connection like rs485.  I'm asking because I will have about 11 or so mcu's as "Rx slaves" while my pc is the Master "Tx". I want to know how my code block is being sent to a specific board will be received by just that board and not all the other boards connected to that Rx port COM?

If I send 'LT2|LP3|LM5|LR4|LI6' and I want that to be for one specific Arduino, I don't want all the other 10 arduinos to take those parameters in this serial Rx line.

@Federico Fissore you mentioned in another post "Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says"

    [16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

how and where can i find this info?

body:
Just assign every node a variable like "const int ID = 5" and so on and then before sending the instructions send a line terminator, the ID, line terminator and the data you need to send to the nodes. Every device listens but they all wait their ID to accept the commands. For example:

    Serial.write('\n');
    Serial.print(ID);
    Serial.write('\n');
    Serial.print(|LT2|LP3|LM5|LR4|LI6);
    Serial.write('\n');

NOTE: This is the easiest way. Most likely not the most reliable or optimized.


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

> I dont think that could have sounded more advanced for me then anything thus far. Any links on how to go about that?

First, run a sketch like this for each board:

    #include <EEPROM.h>

    const int SERIAL_NUMBER_ADDRESS = 1023;
    const byte SERIAL_NUMBER = 42;
    void setup ()
      {
      // don't do it if it has been done before
      if (EEPROM.read(SERIAL_NUMBER_ADDRESS) != SERIAL_NUMBER)
        EEPROM.write(SERIAL_NUMBER_ADDRESS, SERIAL_NUMBER);
      }  // end of setup

    void loop () { }

The serial number **address** can be any address in range for that chip - a Uno has 1024 bytes. I chose 1023 to leave the other addresses free, but it could be 0. Anything you don't need for any other purpose.

Then write a different serial number to each board (eg. 42, 43, 44, 45). Obviously you change the sketch each time you upload to a different board.

---

Once you have done this (once per board) now each board "knows" its serial number. You can detect this in your main sketch:

    #include <EEPROM.h>

    const int SERIAL_NUMBER_ADDRESS = 1023;
    byte serialNumber;
    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      serialNumber = EEPROM.read(SERIAL_NUMBER_ADDRESS);
      Serial.print (F("Serial number of this board is: "));
      Serial.println (int (serialNumber));
      }  // end of setup

    void loop () { }

<!-- language-all: lang-none -->

Output for me in this case was:

    Serial number of this board is: 42

---

Also I have a post about [RS485](http://www.gammon.com.au/forum/?id=11428) on my forum.


message:
Are there any Analog pins on the mega that can not be used as Digital?

I am using both Arduino nano and Arduino mega boards in my projects.  I got a nasty surprise the other day when I learned that, on the nano, Analog pins 6 and 7 can not be used as digital pins.

Are there any Analog pins on the mega that can not be used as Digital?

body:
On <https://www.arduino.cc/en/Main/ArduinoBoardNano> it says:

>  Analog pins 6 and 7 cannot be used as digital pins.

There is no such corresponding statement on <https://www.arduino.cc/en/Main/ArduinoBoardMega2560> and judging by the datasheet all of the analog pins can be used as digital pins.


body:
No, the ATmegaXXX0 has no analog pins without GPIO capability.

Additionally, the ATmegaXX8P**B** *adds* GPIO capability to the other analog pins plus a couple of the supply pins, so if you can convince someone to slip one of those on instead then you will gain two GPIOs (a respin will be required to access the ones on supply pins). Note that the core will also need to be modified, but it's only a couple of quick changes.


message:
Running both sensor and addressable LED strips at a same time?

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

I'm trying to obtain the sensors' readings as well as making the LED strips to light up at this particular pattern, if the sensor readings reaches certain values. But since both of these codes are inside the void `loop()`, there will be a problem. How can I do this correctly?

    void loop()
    {
        currentSensorReading = analogRead(sensorPin);
        Serial.println(currentSensorReading );

        if(currentSensorReading is in range of certain values){
            rainbowCycle(20);
        } else { turn LEDs off }
    }

    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
        for(i=0; i< strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

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

Rewrite without using `delay()`. Or alternatively, do the test inside the `for` loop as well, eg.

    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
        for(i=0; i< strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        strip.show();
        delay(wait);

        // ----------- ADD THESE THREE LINES ---------------
        currentSensorReading = analogRead(sensorPin);
        if(currentSensorReading is NOT in range of certain values)
            return;

      }
    }


message:
Arduino reads bogus from serial

Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as `ð`, `à` and `ÿ` and such.

Here is an excerpt of the Python code I'm using:

    import sys, glob, serial, time, re

    class interface:

      timeout = 2 # 10 second time-out

     def __init__(self):
      port = "/dev/ttyACM0"
      self.connect(port)
      pass

     def connect(self, port="/dev/ttyACM0"):
      global arduino
      arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1) # Establishing connection
      time.sleep(3) # Allowing the connection to settle
      arduino.flush()
      print "Connection established..."

     def ping(self):
            arduino.flush()
            arduino.write("ping")
            msg = self.listen_arduino()
            print msg
            if msg == "ping_ok":
                print "pinged"
                return True
      return False

        def listen_arduino(self):
      timeout = self.timeout
      matcher = re.compile("\n")
      buff = ""
      t0 = time.time()
      buff += arduino.read(128)

      while (time.time() - t0) < timeout and (not matcher.search(buff)):
       buff += arduino.read(128)
      return buff.strip()

And here is the Arduino C code:

    String readString;

    void setup() {
        Serial.begin(115200); // use the same baud-rate as the python side
    }

    void loop() {
        readString = listen(); // listen for any commands
        if (readString.length() > 0) {

            Serial.println(readString); // print the command

            if(readString == "ping") {
              Serial.write("ping_ok");
            }
        }
    }

    String listen() {
        String readString;
        while (!Serial.available());
        while (Serial.available()) {
            delay(1); // Allow the buffer to fill
            if (Serial.available() > 0) {
                char c = Serial.read();
                readString += c;
            }
        }
        return readString;
    }

I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.

Thanks

body: I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.


message:
How to use a grove speaker without using delayMicroseconds?

is there another way to replace **delayMicroseconds(BassTab[note_index])** as I cannot have delays in my loop due to the need of having multi-tasking in my sketch.

Grove speaker: http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html

    /*macro definition of Speaker pin*/
    #define SPEAKER 8

    int BassTab[]={1911,1702,1516,1431,1275,1136,1012};//bass 1~7

    void setup()
    {
      pinMode(SPEAKER,OUTPUT);
      digitalWrite(SPEAKER,LOW);
    }
    void loop()
    {
        sound(5);
        delay(5000); //Wait 5second and play the sound again
    }

    void sound(uint8_t note_index)
    {
      for(int i=0;i<100;i++)
      {
        digitalWrite(SPEAKER,HIGH);
        delayMicroseconds(BassTab[note_index]);
        digitalWrite(SPEAKER,LOW);
        delayMicroseconds(BassTab[note_index]);
      }
    }

body:
It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.

Instead of doing the audio generation manually like that I would suggest using the `tone()` function which will generate an audio tone at a desired frequency in the background.

* https://www.arduino.cc/en/Reference/Tone


message:
How to blink a series of LED alternately only one at a time

I am very much new to Arduino. I recently bought an adruino uno. i can blink an LED alternately. Such as, 1st blink red, then blink green, then blue like that. once only one LED should blink.

I have provided the code blinking an LED. How to modify this to blink multiple LED one after another.

    void setup() {

      pinMode(13, OUTPUT);

    }

    void loop() {

      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(13, LOW);
      delay(1000);
    }

body:
Have you considered connecting another LED and turning one on and the other off sequentially?

    void setup() {

      pinMode(13, OUTPUT);
      pinmode(NewLEDPin, OUTPUT);

    }

    void loop() {
      digitalWrite(NewLEDPin,LOW);
      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(NewLEDPin,HIGH);
      digitalWrite(13, LOW);
      delay(1000);
    }


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

You could always copy and paste:

    void setup() {

      pinMode(11, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(13, OUTPUT);

    }

    void loop() {

      digitalWrite(11, HIGH);
      delay(1000);
      digitalWrite(11, LOW);
      delay(1000);

      digitalWrite(12, HIGH);
      delay(1000);
      digitalWrite(12, LOW);
      delay(1000);

      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(13, LOW);
      delay(1000);
    }

---

A bit better would be to learn about functions:

    void setup() {

      pinMode(11, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(13, OUTPUT);

    }

    void blink (const byte which)
      {
      digitalWrite(which, HIGH);
      delay(1000);
      digitalWrite(which, LOW);
      delay(1000);
      }  // end of blink

    void loop() {
      blink (11);
      blink (12);
      blink (13);
    }

---

And you could learn about loops:

    void setup() {
      for (int i = 11; i <= 13; i++)
        pinMode(i, OUTPUT);
    }

    void blink (const byte which)
      {
      digitalWrite(which, HIGH);
      delay(1000);
      digitalWrite(which, LOW);
      delay(1000);
      }  // end of blink

    void loop() {
      for (int i = 11; i <= 13; i++)
         blink (i);
    }

---

There is a whole world of stuff to learn. Enjoy the process!


message:
Speaker not producing the right sound after a led strip was introduced

- Grove speaker:
   http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html
 - ws2812-led strip

Hi, I have been working to produce tones on a speaker and it works with the following code

        int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};
        ...
        ...
        tone(pin, melody[pitch]);
After I included my addressable LED strip sketch codes, the speaker does not produce the same tone as normally it does. It sounded distorted this time round.

    void loop()
    {
      strip.Update(); //NeoPatterns strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800, &StripComplete);
    }

Class:

    // NeoPattern Class - derived from the Adafruit_NeoPixel class
    class NeoPatterns : public Adafruit_NeoPixel
    {
      public:

    // Member Variables:
        ...
        ...

    void (*OnComplete)();  // Callback on completion of pattern

    // Constructor - calls base-class constructor to initialize strip
    NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
      : Adafruit_NeoPixel(pixels, pin, type)
    {
      OnComplete = callback;
    }

    // Update the pattern
    void Update()
    {
      if ((millis() - lastUpdate) > Interval) // time to update
      {
        lastUpdate = millis();
        switch (ActivePattern)
        {
          case RAINBOW_CYCLE:
            RainbowCycleUpdate();
            break;
          default:
            break;
        }
      }
    }

    // Initialize for a RainbowCycle
    void RainbowCycle(uint8_t interval, direction dir = FORWARD)
    {
      ActivePattern = RAINBOW_CYCLE;
      Interval = interval;
      TotalSteps = 255;
      Index = 0;
      Direction = dir;
    }

    // Update the Rainbow Cycle Pattern
        void RainbowCycleUpdate()
        {
          for (int i = 0; i < numPixels(); i++)
          {
            setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
          }
          show(); // When I comment this line, the speaker will work properly. What is happening?
          Increment();
        }

body:
The `tone()` command is interrupt driven.

To get the tight timing needed by the LED strips interrupts are disabled while sending the data.

That means the tone() command stops while you're updating the LED strips and starts again afterwards.

The end result will be the sound is corrupted - maybe sounding like it's bubbly or underwater or just "rough".

The two basically can't work together and I'm not sure what to suggest to make them work together on a low-end MCU like the AVR.