text:
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 ?

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”.

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.

I thought the arduino due can send digital data at each time clock... I have to find another way.
Thank you for your answer

The Due uses an ARM core.  The ARM core is RISC.  To, for example, get a byte from memory and place it on a port register takes minimum 4 instructions (load address, load data from address, load address, write data to address) and each instruction (load or store instruction) takes 1 clock cycle. That's in assembly. In C it becomes more, and as soon as you start looping you get even longer - condition tests, branches, incrementing values, etc - it may take upwards of 10 instructions with maybe 15 clock cycles for each access of the port. That would make about 5.6MHz maximum output.

DMA might be able to do a bit better than the ARM core, but still the design seems farfetched.  This is territory for an FPGA, or a very, very carefully chosen MCU.  The pi is probably not a fit - the core may be fast, but that does not mean there is necessarily a suitable fast I/O interface.

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.

Right, it is possible to have lower sampling rate by using the envelope of the signal (few Msps is enougth).
We are doing both actually, we sample only the envelope or the complete signal to compare. But we don't use an arduino anymore.


text:
digitalWrite queued signals?
I have this simple code who send a signal to a android phone when I press a button:
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?

Hi, and welcome to the Arduno Stack Exchange.  Unfortunately you appear to have only posted a small portion of your code (known as a "snippet") which is lacking the most important portion - the portion that is doing the communication (and thus the "queuing") with the Android device.  Without that information we will not be able to help you.  Please help us to help you by posting your entire program.

The code below is closer to what you seem to be asking about:
// 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()) so I'll use those. You can read about interrupts on my page about 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

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:

You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
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.
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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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

Just send the GFX commands (and arguments) as text using serial, and have the UNO parse this text and call the appropriate GFX function. But why would you need two micro controllers? Can't you have the Mega do the TFT stuff too?

Sending code over serial is what the bootloader does. However this is a once-off for a given moment. It doesn't interactively execute code. You could send commands over serial to a device with a LCD display on it (eg. display "Hello, world").

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.

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.
Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno.  Firmata might be of use here.

Thanks for your help, that helps out a lot!  Theres not to many functions in the Adafruit GFX library, so I could probably create a protocol to do all of what I'm looking for... Don't know why I didn't think of that.
Thanks so much for your help!
-Will

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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.

Did you ever get this resolved? I'm struggling with the same problem right now. I've tried pullup resistors which didn't fix things.

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.

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 ? Thanks

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 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, an analog.com article.  For overviews, see Star Grounding at lh-electric.net, or at wikipedia, Ground Noise, Ground Bounce, and 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.

Thanks for your clarification,Which i will definitely try on this week just a little concern about "hey 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 as necessary.".Do you mean my ground from the l298N driver should not be connected to arduino ??.If this is right how will the motors driver be grounded then ?Because my 12V input is connected to the motor driver from the battery and ground is connected to arduino

@Salah, see edit

Hi,Thanks for all the support guys ,Unfortunately i am still getting the same results in which the sensor still freezes and the motors continue working normally.I have added pull up resistors of 3.3k on SDA and SCL pins of the MPU6050 and still same results .I wonder if anyone has any other suggestions or if anyone knows any perfect Gyroscope sensor that i can use without facing such difficulties again .Help and support will be very much appreciated guys thanks

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

You can change the CPU clock prescaler in software, so you can make the CPU run at 1MHz most of of the time, but increase it to 16MHz during measurements.

the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) - however it takes longer to do whatever-it-is you are doing. I have a page about minimizing power usage which you may find helpful.

Actually your page is what I used when doing my power optimizations. But the reason I switched to 1MHz is because I do a lot of slow UART with long delays, so I think instead of wasting 16MHz on no-op i will put it into saving energy.

Also the multi-meter I have (FLUKE 179) is not good enough to measure low values in mA and for some unknown reason it damaged two atmega328p chip when i tried to program them using USBasp while the ammeter was connected in series with the power! I didn't think it was the cause at first, but after the second one died in the same way I started to believe!

I haven't confirmed this on the Atmel processor but most processor have a decrement and jump if zero/not zero machine code instructions. This will typically be much faster than an increment, compare and jump if greater than/less than. I suspect this is why your optimization worked.

@linhartr22 that is true, I found that info in a website about avr assembly optimization.

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
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.
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 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):

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

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:

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.

Nice! Given the level of accuracy this approach could potentially shoot for, I'd also suggest measuring the actual resistance of Rc, R1, R2 rather than using the nominal values

Thank you Nick, I just leaned about the analog comparator from you. If I want to monitor 2 caps (1 is used as reference to tackle changes in temp and other effects) and by looking at the datasheet it seems that I can use the analog inputs instead of AIN1 by changing ADEN and ADMUX, will that work? any side effects?

I'd also suggest measuring the actual resistance of Rc, R1, R2 rather than using the nominal values - I'll amend that just to make sure readers realize that should be done.

it seems that I can use the analog inputs instead of AIN1 - that should work. Make sure you turn the ADC off as mentioned in the datasheet. I don't see what could go wrong. :)

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?

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? the datasheet didn't explain: "The comparator’s output can be set to trigger the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate interrupt, exclusive to the Analog Comparator."

See amended reply.

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
}


text:
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

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 on how to do this

It's anemometer. It usually works just as a generator, a low power one but still.

If you watch the video on the adafruit link, she mentions that its probably got a hall effect sensor in it, the power you are supplying is to power the sensor on board. So yes, it does consume power.


text:
problem with using String()

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
  }
}

When you say 'hangs it up', is there no error output? Have you tried printing String(test1) to see what happens? From what you've said I guess 'oops check' printed out but 'sanity check' didn't?

when I say it hangs up the touch screen stops responding and the serial output stops with "oops check" being last thing printed. when this happens have to reboot processor. no I have not tried printing String(test1) will see if I can do that now.

just tried printing (test1) and (str) both will print but it still locks up when it goes to execute the  line str = String(test1); I can't figure why. the way the screen acts it's like the program corrupts. I'm getting stray lines and shapes on the screen at times.

just tried removing all serial prints from the program and even removed str.toCharArray(b,5); and test1++ and it still fragments. which I find odd. if I set test1=20 it locks up. am I still running out of ram? it just doesn't seem right. I know I'm over looking something. guess I will go back to trying to get the drawnumber to work again.

Hmm weird. Have you tried commenting it all out then uncommenting it bit by bit? Then you can pin point exactly which line is causing problems. It is a problem with stuff that is happening before the while loop starts by the sounds of it, although considering you are using library functions for the stuff other than initialisations, I have no idea why it doesn't work. Do you have the correct library versions for the hardware you are using?

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.

I agree with this solution, too. Although I find it curious that it runs out of memory during the first iteration. Printing using flash memory strings is something that I do most of the time now with my Uno/Mega, although if you're using a small micro-c there may be limited flash space to use (you probably wouldn't be printing anything then anyway as smaller devices often don't have serial ports).

I agree it is running out of ram and fragmenting. as far as the Serial.println and all the other serial stuff I do not need. the reason for the String stuff is this. the device I'm trying to make I wanted the screen orientated so it is wider than it is tall. I can get the characters to display in the correct orientation but when I try to Tft.drawNumber(1024, 0, 0, 1, RED); the numbers are turned the right way but reads from bottom to top not left to right. can't get it to do right. this was my work around.  I used to use avrgcc but been years.  any suggestions?

Thanks for the responses I'm still learning and trying to remember.


text:
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

Please post your code (edit the question to do this).

When does the value "just go down" ?
Have you checked for a dodgy ground connection?
Why have you tied pin2 to ground?
(Your code looks good)

While you may well have circuit problems, before investing in it realize that ADC samples from an Uno reported textually over serial won't be a very meaningful representation of audio.

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.

This schematic 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.


text:
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?

There are firmware versions for the ESP8266 that will try to connect to wifi. And if it can't it will create an access point for any wifi device to connect to. After that you can load a webpage on the ESP that enables you to change the WiFi settings. (I think something like this  one)

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.

I had no idea that I could use the ESP8266 as an access point. I'll give that a try, but the backup idea works quite well for this project, thanks.


text:
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?

Something like this might work. Though it is made for liquids, so might not work great for gasses. Especially if there isn't a lot of gas flow.

@Gerben I've seen a lot of that on Google as well, but I'm afraid that they won't work at all for gases. But for my purposes, as long as I get any indication of flow, its good. Maybe if I find a water flowmeter with enough flow rate?

You can use a pressure sensor for gas and measure the pressure differential between two points and if there is a large pressure differential then you know a flow exists.

What you are looking for is a mass flow sensor (MAF), 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:


text:
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

What do the numbers represent?

The sequence of 0 and 1 time-encoded that make up an IR transmission to set something. The lines in the post are for heat mode, and temperature 25 to 30. I read the data with an IR sensor from the AC remote, and resend it to control the AC. In this case I am using IRemote library, but there is also IRLib. There are alot of tutorials and demos on youtube if you want to see how it works, but if you want I can post more code.

I thought so.  So the times don't have to be 100% accurate then I guess - you just have a set number of "ballpark" figures - around 500, around 1500, around 3000, etc. Do you really need to store the actual times in that case, or just a representation of the time?

It looks like there's a standard preamble of ~600, ~1800, ~3000, ~9000 and then a sequence of ~500 and ~!500 to represent 0 and 1, and that makes it even easier

So i should find sequences of numbers that appear often in the code and just save that as a number. The timings do not have to be 100% accurate, I did 10 reading of each value, stored to logs, then did the average with a script to get the current options. I could modify the script to search for patterns and find what numbers never appear anywhere and generate a map for that... Thank you for the idea!

If you take ~500 as a 0 and ~1500 as a 1 and ignore the preamble (hard code that separately) you could encode those binary 1 and 0 values as binary in just a handful of bytes.  For instance the first entry would encode to: 0x10, 0x00, 0x10, 0x41, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x74, 0x00, 0x01, 0x00, 0x51, 0x55, 0x54, 0x05, 0x40, 0x01, 0x54, 0x00, 0x40, 0x05, 0x50

I've uploaded the whole code to GitHub if you want to take a look. I will update the code again after I add your optimization to it.

I have analysed your codes with a small Lua script:
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 for how they compressed the IR codes for lots of TV brands into a small table in an ATtiny85.

I think you can safely replace all values with either 500 or 1400 (except for the preamble). So you can store them in 1 bit per code. Secondly the first 118 values seem to be identical, and after those values there seems to be another preamble (?). After this another 26 values are identical. So you could store the first part (146 values) only once. (Also try leaving it out completely and see if the AC unit still accepts it)

Good idea. We'll have it down to a few dozen bytes soon. :)

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 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).

It's a good idea to use FRAM or something simillar. Havent thought of that yet, I will look into it. I only need to be able to fetch one row at a time to send it over IR.

Then an external memory device should work well for you.

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).


text:
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!

Are you planning to run the ATmega32U4 at 8 MHz?

Yes I am.  I have both the RC version and the non-RC with an external 8MHz xtal.

Update: So I have tried several different methods, each with their own issues. The latest was to use the AVR ISP mkII on a Mac, as there are driver problems with Windows. It seems to have burnt the Lilypad USB bootloader on, but when I plug in the USB, nothing shows up on my PC. This is quite the rabit hole for something I thought was going to be trivial.

Where did you get this Lilypad USB bootloader? The Lilypad has an Atmega328V and no USB interface.

@NickGammon link The bootloader is in the Arduino folder hardware > arduino > avr > bootloaders > caterina-LilyPadUSB.

Further Update: for anyone reading with a similar issue, I was finally able to burn the bootloader using the AVR ISP mkII on a Mac OS. On windows, the mkII tries to install it's own USB driver that doesn't work with Arduino IDE.

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.


text:
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.

Doing bit stuffing can prevent timing problems when you are sending a lot of 0s or 1s 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.

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.  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.


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

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;

}

You need to debounce the button.

Are you sure you are not writing too much into the EEPROM?

How is it wired? Is there a pull-down resistor?

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 on his web site. Have a look at that and pick a technique that's compatible with what you're trying to do.

@Nick Gammon your website was very helpful. I have now added the debounce and the count is tracking correctly. Thanks all


text:
'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);
}

Because you have a slow servo that takes two seconds to go from one end to the other?  Try with a longer delay.

If that were true, I don't see why i'd be observing the servo 'stop' for 2s after the second position. I've tried longer delays. The effect is the same.

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:

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.

Besides adding LED signals, try slightly-less extreme times in the writeMicroseconds() calls; eg 1000 and 2000 microseconds rather than 700 and 2300.
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.

Something rather odd's that when i apply resistance to the servo with my fingers in the opposite direction of where it wants to go, the timing and all is fixed and it goes to every position as programmed. I'm clueless. Could the servo have a problem or something?

I just tried using another servo and everything's fine. What's wrong with the other servo? Am I able to fix it? :-(

I just tried powering my board not through my avr pocket programmer... Everything works fine now. Why is this so?

Insufficient power to the servo when powered like it was.


text:
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

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 }
  };

Ah I see. Thanks very much for the explanation Nick, that was really helpful.

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.


text:
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

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

Could you use an oscilloscope and look at both TX lines?

I don't have an oscilloscope ;)

Does loop back work without the MAX232?

Tried the loopback without the MAX232 and it doesn't work, even when I use the 0 and 1 pins. What is wrong with my arduino?

I've never used the Arduino/sketches but I don't see in your code where you have actually written anything to the port. Is that all of the code? You're checking if anything is available but there won't be until you've given it something to start with. Your if statements could be returning false each time in the loop and so you never write anything or print anything.

I use the serial monitor to check which data is coming in. With this monitor I can send some data but can it be that it doesn't write to the ports what I thought it did?

Okay, and the baud rate that you are using in the serial monitor matches (9600)?

Yes. I rewrite my code see EDIT in main question, I still get some strange input.

In setup() have you tried to write something to the monitor, e.g. Serial.println("Hello world");? Just to see if it's working correctly.

I get the "hello world!" in my monitor in Setup()

Tried it again and now it is: 89 13 92 35 11 18 61 89 ...

Well, it appears that the wiring/hardware is working anyway. Not sure what you're doing to get those numbers. See http://www.asciitable.com/.

It's just a cascade counter like my edited code shows.
These numbers is the result of the loopback which I find very strange. Especially with in mind that this is a test run to see if everything is working before I add it to an atomic clock receiver.

Now I tried to just send 'a' instead of an integer. The returned values are: 89 139 235 11 186 189 ...
I changed to other ports and now I get -1 -1 -1 -1 -1 ...

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:
#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.

My loopback works fine but now I added my atomic clock module the FUM DCF-U and changed the code so that only the last if-clause remains. This results in only '0' (without the char cast) in a fast rate instead of some data every second. Why does this happen?

Perhaps amend your question, and post this amended code. Neither my colleagues here, nor I, are good at debugging code where "I changed a few things but ...".

Editted the question.


text:
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)

The location of preferences.txt is shown near the bottom of the preferences page.  It takes two or three clicks to open it in gedit.

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

Note that since Arduino IDE 1.6.4 preferences set via --pref are only saved if you also use the --save-prefs option. See: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc#history


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

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.

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

I'd say that it's not "an alternative", it's the sane thing to do :-)
Why using additional components when there are integrated ones that are perfectly suitable for the purpose?
I think the situations that require using external pullups are really few and not too likely to happen to someone who's just starting to move the first steps.

Or use the single line pinMode(pin, INPUT_PULLUP);  (which in effect does the same thing, but is a bit shorter, and more intuative)

I'm having an issue with your comment about short circuiting the power supply but am likely just "splitting hairs".


text:
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.

LilyPad Arduino USB uses the ATmega32U4 on +3.3V and 8MHz oscillator.  So, you can use the LilyPad USB bootloader.  That worked for me without any modifications to the bootloader.

Thank you! Though I've been trying to do this with an AVRISP mkII as ISP in the Arduino IDE, but for some reason I get this error message: "avrdude: usbdev_open(): did not find any USB device "usb""

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.

Why can't the USB be used with the internal RC? Datasheet says that it's possible. I'm not doubting you, I'm just wondering the reason.

It is possible to use low speed USB if you have a way of keeping the oscillator calibrated. It is not accurate enough for high speed USB even if calibrated.


text:
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 ?

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/


text:
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.

Does my answer address what you wanted to know?

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.

From here - Multidrop network for RS232.
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.

kind of very vaguely for a noob to understand some of your tech talk but im trying here

@Frank'sDesig'Nature - Look at the circuit above. Reverse the diode directions as you are using 0V/5V and not true RS232. Add a 10k from Master RX (blue line) to =%V. Try it. When Master drives TX line all slave RXs see the data. When any slave transmits the master sees the data but no slave does.

is there a reason why i cant just use one of those USB 3.0 5GBPS extension port? i men i use 2 usb port as in now from a extension of 4 usb all connected to one usb in my tablet and from there i open 2 terminals when i debug Tx and Rx from 2 diff arduinos with no issues SO why do i have to use this format? and not the usb way ? seems like a work out just to tx/rx data when the ide already does this with out extra crap like we been talking about?

[link]http://www.ebay.com/itm/111717351068

RS-485 or 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 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.

@Russell McMahon thanks for your detail explanation despite the crazy typos i followed enough tho i think your under the impression that the slave arduino's will be tx anything back to the master "computer doing all the Tx" just want to be clear of this cuz you are talking a lot about slaves talking to anything when this will not be happening, the slave all they do is drive motors, thats is nothing else the have a sketch running that is looking for a parameter to be called serially using a long list of break/switch statements

this are the type of command i like to send to each Slave
Serial.println('LT2|LP3|LM5|LR4|LI6'); or 'LT2|LP3|LM5|LR4|LI6'
i want to send this type of block to each individual slave tho keep in mind that the above block is only to activate that slave and its speed, a additional block will follow with direction

like this guys ?

and if so i guess my next question would be if everything is tied common style how would the pc know who to send what to ?
if  send 'LT2|LP3|LM5|LR4|LI6' and i want that to be for one specific arduino i dont want all the arduinos to take those parameters
in this example block 'LT2|LP3|LM5|LR4|LI6' the LT2 go's as follow (L is the mcu while the T is = to the pin on that mcu (pin D7 ect..) and the 2 is speed aka delay(2); )
so as you can see will all the other arduino who aren't 'L' won't use this data in the serial port?
how would i addressing be done ?

The question about getting a particular Arduino to respond to a particular command is also asked by the OP here: How can I get a unique address for all my Arduino boards while in RS485?


text:
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?

Which pins specifically? By default most pins are set to INPUT not OUTPUT.

By default the pins are set to INPUT (except pins 1 which is used by the bootloader for programming). Inputs are however floating, so they don't have any fixed voltage during this stage. The the device attached to the pin might read a HIGH signal. To prevent this add a pull-down (or -up) resistor.

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).


text:
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
2 x EasyDriver
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

This is the article.

To clear things up also:
I was just trying to combine the project into one single power supply as it currently sends data wirelessly and this would mean I wouldn't need the USB to PC. Any suggestions as to what type of power supply I could use so I only have a single wall plug?

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.

If I had a 12V 1A plug like this cut off the 2.1mm plug, exposed the wires and applied power to a breadboard rail. Would it be sensible to then power the arduino using the VIN pin and then use the same rail to power the easyDrivers?

I'd rather use something like this http://www.ebay.com/itm/MB102-Breadboard-Power-Supply-Module-3-3V-5V-For-Solderless-Bread-Board-IN-/181803793177?hash=item2a5459bb19 where you can power the breadboard with a voltage that will not heat up the regulator in the Arduino and you cna still access the raw 9V from a pin header. But yes, what you propose will work too.

Where is the raw 9V pin on that board? I can only see the 5V and 3.3V jumper for each rail and the 5.5V/3.3V/GND pins?

Sorry, I mistook the component south of the switch for a pin header.
No, you would have to solder a pair of wires from the pins of the connector, on the bottom side of the board.

You should not run your stepper motor power through either the Arduino or (except for extremely small motors) a breadboard.

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.
#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);
}

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.