text:
Sanity check with potential project. IoT with a dishwasher
So sanity check for a potential project.
We have an old dishwasher at work, a GE QuietPower 3, and being a technology company, we want to connect it to our chat room to notify that the cycle is done, so someone can unload it.
The first iteration of the project we were just going to cover the "finished" indicator light with a photoresistor, so when it lights up, the microcontroller will know it is done.
However, that is not very nice looking, the second approach, after quickly looking at the technical maintenance manual. Is to literally solder the ground and + of the "finished" indicator light to a digital or analog pin, and the ground pin on the micro controller, so the results are more precise.
I suspect the LED is probably less than 12V, (will confirm with a multimeter). I will step it down to 5V.
Then it is just a matter of checking if the pin is high or not on the microcontroller, is this simple enough to solve the problem, or am I overlooking something obvious?

This is enough to solve half the problem - detection. The other half, communication isn't addressed yet (here, anyway) but since you haven't mentioned it I suspect you already have a handle on that part.

Communication was solved by using CC3000 wifi shield.

Use a resistor (10k or something) between the arduino and the diswasher led, in case the voltage is higher that the arduino. The arduino avr chip has internal clamping diode which will protect the chip from possible overvoltages. If the voltage on the led lead is too low (< 0.7*Vcc), you can search for the current limiting resistor that is connected to the led, and tap of the signal before this resistor.

If you want to see your Arduino alive again send $10....... I mean, if you want your Arduino to live, and the people using it to not die semi randomly, then read my answer carefully and consider carefully why you wouldn't do it. Optos cost maybe $1, maybe about free. Keep them away from burning PCBs (ask me how I know) and they will keep the AC mains and similar where it belongs. Non isolated connection to a "looks like it should be OK" device is an invitation to disaster.

If connecting to the wiring, using an opto-coupler will ensure that your Arduino's days will be long on the face of the land. If it is an LED indicator you may be able to connect the opto-coupler LED  input directly across the existing LED, but use of an appropriate series resistor would be wise. Optocoupler LEDs may have about 2 V forward operating voltage which is in the same range as a red LED. Some use lower forwards voltage LEDS (probably IR).
If your opto coupler has low input current requirements then connecting it via a series resistor across the existing LED will allow the indicator to still operate.
R series = (Vsource - V_opto_LED) / I_opto.
eg 12V source, 2V opto_LED (typical), 1 mA (should be enough for logiclevel signal.)
R = (12-2) / .001 A = 10/.001 = 10 k Ohm.
For direct connection across an existing red LED a 100 Ohm series resistor should avert disaster.
V drop in resistor at 1 mA:
V = IR = 0.001 x 100 = 0.1 V
= liable to be OK.
Ask if more information wanted.

More or less. LEDs are often around the 2.something volt range, which won't be enough to power an Arduino. In addition, if you set it to run in parallel with the LED, then the path of least resistance will get most of the current.
I would probably use the led power to turn on a transistor, then use the transistor to signal the Arduino. Be aware that if you want to power it off an external source, you may find that the ground on the washing machine is not the same as the ground on your power supply. If you're powering it off a battery, this won't matter, but otherwise power can flow from one "ground" to another. If you stick a resistor (maybe start with 1kOhm, if that's too much drop it down) between the washing machine led + and the transistor, and the same between the arduino and the transistor.

The Arduino will be powered via the USB port. I am planning to use a digital or analog pin plus ground on the Arduino in parallel with the indicator LEDs.

This is a perfect example of a situation where ground may be different. If you connect the two grounds together (USB ground and washing machine ground), and the grounds are at different levels, you will likely destroy the washing machine or the laptop. Even different USB ports on the same computer may have different ground levels.

Sorry, I should have been more clear, by ground, I meant the ground pin on the Arduino. The Arduino will be powered via a wallwart AC -> USB 1Amp charger.

@Bill seeing that it's an old dishwasher, I would add software denouncing as well.

And as @AMADANONInc. says, use a transistor to step down. It is easily the best way to do this, and if for some reason (bad grounding) the dishwasher misbehaves, the transistor will protect the micro controller, provided its on that supply!

@Bill the problem still applies - if a transformer steps down from 110 to 5, it could use the voltage from 5 to 0, or from 110 to 105 <- This is a gross oversimplification.

@RussellMcMahon's answer of using an opto-coupler would get around all these problems.  In this kind of situation opto-coupling is the normal (and recommended) method.


text:
How can I create a power rail on my Arduino shield?
I have an Arduino that has 4 devices within an enclosure.  Each of the 4 devices needs 5 V and GND.  I have a shield with lots of unused pins (see photo).  I'd like to "bridge" one row of the pins to create a power rail, and I'd like to bridge another row to create a ground rail.
I think most people are using an external breadboard for this.  Also, I see that there is a shield that has power rails, but I don't have room for it.  I'm looking for a female header, or another way to bridge these unused pins.
Note: I'm not asking about wiring voltage in parallel or amperage consumption.

Just use some bare copper wire, and solder it to a row of pads.

Just bridge them.  Wire in your +5V connections then join them together on the back with lots of solder.  Maybe with a strand of 0.6mm single core wire along it for extra ruggedness.

Have you considered "Conductive Silver Paint"? With this you can literally paint tracks to join any arrangement of holes you so desire.
Everybody from Maplins to Rapid Electronics sell it. There are many brands to choose from. Here is one at random: http://www.rapidonline.com/mechanical-fastenings-fixings/kemo-conductive-silver-paint-180423 ...I like Rapid because they have a helpful Q&A section for each product.

+1 : This method turns the proto-board style into stripboard-style, i.e. you end up with conductive 'tracks' while leaving the holes intact. As you're constructing power rails, I recommend painting both sides of the board for extra current-carrying capacity.

Would this method work even if you're pushing 12-24V through the conductive paint?

@clifgray I have repaired the rear-windscreen-heater in a car with silver paint, so it definitely handles 14V ...I would suspect your bigger concern is how many Amps you wish to carry ...If you want to carry a lot of current, I would NOT paint a line "as thin as a fuse wire"

@BlueChip I'm running pretty low current. Around 24V and maybe .5A.

source: Stack Exchange

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

sort: votes


text:
Manual Arduino Due Installation
Not sure if this is the right place to post this.
I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but it just says there is an error downloading the files.
Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

UPDATE
When I open the Boards Manager, I get :
Error downloading http://downloads.arduino.cc/packages/package_index.json
and when I try to install Due support, I get :
Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2
I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.
I have manually downloaded sam-1.6.4.tar.bz2 and extracted the contents to C:\Arduino\arduino-1.6.5\hardware\arduino\sam (I had to manually create the sam folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :
Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified
Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.

UPDATE 2
Question has been answered:
https://github.com/arduino/Arduino/issues/3358
Many thanks to Federico Fissore!

I just installed the Due fine using the board manager. What is the problem you are having?

If there is an error, you should report it to Arduino github https://github.com/arduino/Arduino/issues

@Majenko When I open the Boards Manager, I get :
"Error downloading http://downloads.arduino.cc/packages/package_index.json" , and when I try to install Due support, I get :
"Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2" . I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can change that.

@FedericoFissore I will try there as well, but if you have an answer, can't you just it here?

@Tom I don't have an answer, but if you are TheForeignMan on github, then we are already chatting :)

@FedericoFissore Haha yes! I'll update the question.

I have a repository that has the fix to the board issue with DUE.. here is the link...https://github.com/LadyLexi/arduino-platform-sam

I had the same problem described above.
Error downloading http://downloads.arduino.cc/packages/package_index.json
I solved the problem, just deleting the temporary file: "package_index.json.tmp"

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


text:
Increase PWM bit resolution
I would like to increase the PWM bit resolution of the Arduino Uno.
At this moment it is 8-bit which I consider too low.
Is this possible without losing the ability of interrupts and delays?
Koen
EDIT
This setup delivers a 16-bit resultion
void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS11);                    /* prescaler: clock / 8 */
    ICR1 = 0xffff;                      /* TOP counter value (freeing OCR1A*/
}
/* Comments about the setup
Changing ICR1 will effect the amount of bits of resolution.
ICR1 = 0xffff; (65535) 16-bit resolution
ICR1 = 0x7FFF; (32767) 15-bit resolution
ICR1 = 0x3FFF; (16383) 14-bit resolution etc....

Changing the prescaler will effect the frequency of the PWM signal.
Frequency[Hz}=CPU/(ICR1+1) where in this case CPU=16 MHz
16-bit PWM will be>>> (16000000/8)/(65535+1)=30.5175Hz
*/

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

The Arduino Uno is based on an ATmega382P microcontroller. This chip has
two 8-bit timers, driving two PWM channels each, and one 16-bit timer,
driving the last two channels.
You cannot increase the resolution of the 8-bit timers. You can,
however, put the 16-bit timer in 16-bit mode, instead of the 8-bit mode
used by the Arduino core library. This will give you two 16-bit PWM
channels, with a reduced frequency of 244 Hz (maximum). You will
probably have to configure the timer yourself, and will not benefit from
the easy to use analogWrite() function. For details, see the section
on Timer 1 in in the ATmega328P
datasheet.
Update: Here is an implementation of a 16-bit analogWrite(). It
only works on pins 9 and 10, as these are the only pins connected to the
16-bit timer.
/* Configure digital pins 9 and 10 as 16-bit PWM outputs. */
void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                    /* no prescaling */
    ICR1 = 0xffff;                      /* TOP counter value */
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

You may notice that the top of the counter sequence is configured
explicitly. You can change this to a smaller value to make the PWM
faster, at the cost of decreased resolution.
And here is an example sketch illustrating its use:
void setup() {
    setupPWM16();
}

/* Test: send very slow sawtooth waves. */
void loop() {
    static uint16_t i;
    analogWrite16(9, i);
    analogWrite16(10, 0xffff - i);
    i++;
    delay(1);
}

Wow thank you very much, this is exactly what I need. I want my PWM resultion to be the same as my Sensor Resolution. If I change your code to  would it be a 13-bit resultion? If so, what would the frequency be? I will be driving a DC motor with it so 244Hz will be a bit less I guess

@KoenR: No, the prescaler has no effect on the resolution, it's purpose is to slow down the counting. Setting the prescaler to 8 will give you a PWM frequency of 30.5 Hz. If you want 13 bit resolution, set ICR1 to 0x1fff, then your frequency will be 1953 Hz (F_CPU/(TOP+1)) with a prescaler at 1.

Thank you for the explanation. Edited my question so that it covers these mistakes. So other people can see it directly. Thank you!

Am I able to use this with a CAN-bus shield which CS is on port 9? If so, is it only changing this line of code: DDRB |= _BV(PB1) | _BV(PB2);

Remove _BV(PB1) and _BV(COM1A1) from setupPWM16(), then change change analogWrite16() so that it only works on pin 10.

Fantastic answer! But would this work with an ATmega32u4 - as seen on the Arduino Micro?

@FlorinAndrei: I do not know the 32u4, but according to the summary datasheet, it should work, as it has two 16-bit timers and “Four PWM Channels with Programmable Resolution from 2 to 16 Bits”.

@Edgar Bonet This is great, however I can't seem to fully turn off an LED. I'm using ICR1 = 0x03FF and at 0 I'm seeing a tiny pulse on the scope enough to light the led. Any ideas?

@davivid: Yes, you cannot have a zero duty cycle. analogWrite16(pin, val) gives a duty cycle of (val+1)/ICR1. As a workaround, Arduino's analogWrite() does if (val == 0) digitalWrite(pin, LOW); else if (val == 255) digitalWrite(pin, HIGH);. But then you cannot get a duty cycle of 1/ICR1...

@Edgar Bonet: Thanks for explaining that - the workaround works for me.

I'm trying to figure out if PWM resolution on an Atmega168P can be increased on three pins. From what I understand, the 16-bit timer only works with two pins. Is there maybe some way to use two full cycles of the 8-bit timer, using a variable that keeps track of if it is on cycle one or two? A 50% duty cycle would be on for one 8-bit cycle and off for the second.

@Dima: Probably, but that won't be simple.

With some calibration you could sum the outputs of two PWM channels with differing weighting resistors. At the extreme you could notionally use one output to provide 8 bits of resolution and scale the other to 1/256th the level and add them so the 2nd channel covers one bit of range and you (again notionally) get 16 bits of resolution. Without immense care and adjustment all you'd get would be a mess.
However by dividing the 2nd channel by 16 or 32 you could add several extra bits of PWM resolution. Just by adding 2 PWM channels analog filtered outputs you add an extra bit (as potential range is doubled for unchanged mV/bit).
Notionally (again) for every additional divide by 2  you get an extra bit of resolution, but this can only be carried out for maybe 4 or 5 or 6 extra bits, with increasing accuracy requirements of scaling resistors and more difficult calibration and proneness to errors.
Brief example.
If one PWM is scaled down to give say 0 - 255 mV in 1 mV step, then summing two PWMs with equal amplitude would give a 0 - 510 mV range in 1 mV steps.
If one PWM is scaled down by a factor of 32 then instead of adding 255 mV to the initial PWMs range it would add only 8 mV to the top end (0.256.32 = 8 mV, but resolution would be in 0.03125 (1/32nd) mV steps.
While this could perhaps be achieved purely with resistor summing and RC filtering, use of an op amp summer would greatly improve results.
Also PWM ripple could be filtered with a simple RC filter but use of one opamp as a buffer (or even just a single transistor as an emitter follower) would give you 3 or 5 poles of low pass filtering and much better chance of achieving extra PWM resolution. I have not inspected the "phase coherence" of the PWM outputs but expect that they move in relative lockstep so you don't get the smoothing advantage of adding two uncorrelated waveforms.
More comment can be made if needed. Ask if interested.

This is clever! Seems that the Mozzi sound synthesis library uses this trick for it's so called “HIFI” mode.

That is a great us of the PWM. But wouldn't this smooth out the waveform? I am asking this since you are using a RC filter. Haven't mentioned this in my question but I'm driving a DC motor with it . Thank you for the input!

@KoenR (fwiw: I don't see anything to be ashamed of.)  I don't know what frequency response/rate of change you want in your ADC output. Or why you want N bits or how big is enough. Motors will usually not be usefully controlled by more than 8 bits - depends on how precision an application you have. Motor acts as part of a smoothing  filter due to inductance. You need to say what sort of motor and how driven. And a circuit diagram is about essential. Unless motor is tiny you have a driver. A brushed motor fed PWM must have a a catch diode to pass motor current when PWM is off. Adding two ...

... PWMs here is entiely doable but circuit details need to be known.

Beware! In some cases, smoothing out PWM with a low pass RC is not desirable. E.g., if you plug the Arduino output into the gate of a MOSFET, the MOSFET will stay cold as long as it's driven by clean PWM. But if you smooth it out, the MOSFET will start dissipating much more heat. Sometimes that's not a good thing.

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


text:
Can't detect I2C displays with Arduino Nano
All cables tested and work:
SCL - A5
SDA - A4
VCC - 5V
GND - GND

I'm using an Arduino Nano board and an I2C display - I've tried everything to get it to work and I'm now convinced it's a hardware fault. Using the Arduino I2C address scanner, it is unable to find a device, even though it is wired correctly (I've checked multiple times).

This is the code I used, i2c_scanner, and this output:
Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

... is all I get.
Any suggestions, or is my board output fried?

To use i2c you normally need pullup resistors on sda and scl, except if the slave device has some. Add 2 pullup resistors to your circuit (you can use 10k, that should be ok).

You need to understand how I2C works first.

@ChetanBhargava what has he misunderstood?

You seem to have two issues here:

As already pointed out, you have the white wire connected to the wrong pin on the Arduino
Also, you need to solder the headers on the Arduino. There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers

Agreed absolutely. Shoving the header pins into the holes simply won't work. You must solder them.

Check the solder jumper on the display. Note the example code is for one address, but two addresses are supported. Try the other address in code, or solder the LCD address pads to select the address to match the code. I had the same problem, the printed address on the LCD solder pads is just the last address bits that make the difference.

I had the same problem, with a lot of time lost, I tried to give current from another source, (an Arduino one) is all works, I think these Nano clones have some bugs on output voltages, to be checked. Anyway, so it worked.

I am not sure if this is an answer, or a comment.

@Greenonline You could flag it as "not an answer", but it will probably be declined and you'll be told the reason is - flags should not be used to indicate technical inaccuracies, or an altogether wrong answer. In my opinion, if a person is going to answer a 3 year old question that the OP has abandoned, it better be a good answer. This answer does not address any of the issues that are clearly visible in the OP's picture, not does it point out the incorrect wiring. You could try flagging it as "very low quality" and see what happens.

@VE7JRO - Good point, I had flagged it as "Not an answer" but I have retracted it, for the reasons you state, although it would serve better as a comment. I'll leave it be, even though the obvious answer is that of Anonymous Penguin, as I don't want to earn any more declined flags :-). Also, I am not sure why there are two answers from the same user.

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


text:
How to slow ADC clock speed to 1MHz on Arduino Due?
I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)
The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)

You can change the prescaler (ADCSR register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.
Arduino sets the ADC clock to 125 KHz (prescaler of 128)
So to match Arduino, you should select a prescaler of 8 ( set bits ADPS1 and ADPS0)

Interesting. Where may I find the ADCSR register? Also, what's the highest prescaler possible? The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)

@Gerben Are you sure that holds true for the Due (ARM) or just for an Uno/Mega/Leonardo (AVR) as ADCSR sounds suspiciously like an AVR register name and not like an ARM one.

@David Look for system\libsam\include\adc.h, system\libsam\include\adc.c, and variants\arduino_due_x\variant.cpp in the IDE directory. I am not sure of the exact paths as I have 1.5.1, not 1.6.1 and they've probably changed since then. But the first two have all the access routines for the ARM ADCs. The final one shows how they have initialised it. You will notice they initialise it to ADC_FREQ_MAX which is defined in adc.h to be 20MHz.

@TomCarpenter you are right. This doesn't work on the Due. ATMega only.

The atod clock is set in the mode register. The clock is 42MHz/(PRESCAL#+1). One way of setting it is the use ADC->ADCMR = ADC_MR_PRESCAL(PRESCAL#), where PRESCAL# is some integer.  These symbols are defined in component_adc.h in the Arduino source code.
 In the AVR data sheet, the recommended clock is MIN=1MHz, MAX=20 MHZ, corresponding to numbers between 41 and 1. Look in the data sheet, section 43.

I cannot find where the PRESCAL value is defined by the Arduino framework, do you have the link somewhere? :)

Sorry,  think I found it: #define ADC_MR_PRESCAL(value) ((ADC_MR_PRESCAL_Msk & ((value) << ADC_MR_PRESCAL_Pos))) available here: https://android.googlesource.com/platform/external/arduino-ide/+/f876b2abdebd02acfa4ba21e607327be4f9668d4/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3n/include/component/component_adc.h#102 . But not very sure how this should be understood.


text:
Relationship between baud rate and the frequency of vibration read using ADXL
I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post  in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.
"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"
But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?
Thanks

Firstly, the datasheet for the accelerometer suggests using >=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.
Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.
So the Arduino and accelerometer can detect vibrations up to 1600Hz.
Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.
For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.
The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.

Thanks for your response. But I don't understand the line "the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz." Why is it 1600Hz when the sampling rate is 3200Hz. I am new to this. It would be helpful if you explain this. Thanks

According to the Nyquist Theorem, you need to sample twice as fast as the highest frequency you want to measure.  For Ex, if the signal you wish to measre is a 1MHz sine wave, you have to sample at AT LEAST 2 M Samples per second (MS/s) to ensure that the 1MHz frequency component of the signal is detected.
However, sampling at exactly 2 times the highest frequency is often unacceptable, especially where the shape of the signal is important.  When sampling a pure sine wave, I generally make sure to sample at at least 10 times the frequency of that sine wave to see the shape of the signal.

Typical serial encoding is more like 10 bit periods per byte, so 24 bits becomes 30 byte times.  But 3200 * 30 should just fit in 115200 baud, which is within the capability of a sound Arduino setup.  It will mean using binary encoding though, and with a divisible-by-three size, which is ugly.  I'd consider trying to pack the data to two bytes.


text:
Can I power a LilyPad with an iPhone lightning port?
I want to make a toy car that follows a black line on the ground by using two sensor on the left and right sides of the car both pointing down. The sensor converts the light into a voltage that I will use to make the car turn left or right. I know that I can use batteries, but I am still very curious to find out if I could use my iPhone to power an Arduino because I also want to make a case with different sensors in it, and it would be thinner if I didn't have to put a 9V battery in the case.

Mobile phones generally use lithium batteries. Have you considered using a thin battery, rather than a thin battery wrapped in a phone in a way that makes it difficult to get the power out of that battery? Adafruit lithium batteries; Sparkfun batteries; etc.

If the phone has an accessible battery you could conceivably use the battery terminals to power a device such as Arduino. However, I think current smartphone batteries have complex monitoring circuits so this wont work.
If it doesn't, you'd be looking at using the USB/charger port on the phone.If your phone supports USB On-The-Go, I know that it allows phones to act as USB hosts, and according to USB-OTG specifications, the host must be able to supply at least 8mA of current between 4.4V and 5.25V.
If that's enough for you it could work.

Would I need some sort of adapter that connects from the iPhone's lightning port to the Arduino? I have an LED case on my phone that draws power from the phone, so I wanted to do the same thing with an Arduino. I might be asking this in the wrong thread. Sorry if I am.

Try to look at the pinout of the lightning port and create your own breakout. Then you can try taking power from the iPhone.

For those coming here from Google.
The short answer is:
Yes you technically can, but it wont be dirt cheap or very pretty depending on your wallet and tastes/requirements.
Longer answer:
I was researching the same thing. The problem is that Lightning connector is fairly complicated, and before it will start giving you power it requires software authentication by a chip that is built into the cable. That said you can use the USB camera connection kit or you can buy one of the IK Multimedia mini usb cables:
http://www.ikmultimedia.com/products/cat-view.php?C=spareparts
I have had success trying to tap into their cable for iRig Pro cause I happen to have one, and it gives out solid 3.3V on one of the pins which is good enough for my Arduino Mini Pro. But I would vouch that their full blown mini usb cable should be supplying regular 5V.


text:
Connecting an Arduino to a telephone line?
I would like to connect my Arduino Uno to a telephone line in order to answer a call, record a sequence of DTMF tones, generate a DTMF tone in response, and hang up.
The telephone line uses a standard RJ11 connector. When a touch-tone phone is connected to the line, it receives one of two rings:

a standard ring, which signals an incoming call
a shorter "two-ring" sequence which signals a call from a local intercom

I would like my Arduino to listen for the "two-ring" sequence and only answer those calls.
How would I go about connecting my Arduino to the telephone line? Is there a shield designed for this purpose? I know I can use the tone() function to generate the DTMF tones, but I'm assuming I would need to perform some form of Discrete Fourier transformation in order to "read" the DMTF tones from the other end of the line.
Any suggestions would be appreciated.

Be careful when connecting directly to the phone line. There can be huge spike on the line (e.g. lightning strikes). If you've ever opened e.g. an ADSL modem, you'll see there are quite a few protection components on it (sparkgaps, movs, magnetics).

In the UK it is illegal to connect anything to the phone line that hasn't been certified. You might want to check your local regulations too.

You can interface arduino to telephone line using MT8870D chip. This IC can decode DTMF tones. Below is a reference schematic from the datasheet.

Another popular design floating on the internet is below:

There are pre-build modules available from futurelec :

You can use Holtek HT9200 IC to encode DTMF that can be interfaced with Arduino. Below is the reference schematic from its datasheet.

You'll need some hardware assistance for the DTMF detection and generation; I doubt many Arduinos (you didn't say which, but maybe ARM?) have the horsepower to run an FFT (and deliver the results while anyone still cares....)* tone()may not be precise enough in frequency for DTMF detection by the calling device; you'll have to check that out. A quick search finds a number of articles on building or buying tone detectors and generators.
Ringing pattern detection is a little easier but you'll still probably want to sense the ringing and convert it to a level in hardware, rather than tracking the instantaneous line voltage and trying to distinguish in software between noise, ringing, noisy ringing, and various degrees of quiet.
* But maybe this Hackaday project can give you some alternate and computationally feasible ideas.

Hmm... I guess I hadn't given enough thought to the amount of processing required for DFT/FFT. Although (as your link suggests) I'm only sampling for a very small set of frequencies.


text:
Can do I make an Arduino program that can decipher telephone touch tones?
I have an old land line phone that I want to connect to my Arduino.  Then I would like to write a program that can decipher the touch-tone button presses (which are a combination of two tones) so that the Arduino can react to specific key presses and numeric sequences.  My final goal is to make the Arduino play specific messages when the user enters in codes.  I am really not sure even where to begin.
Thanks for the hardwares fixes for this problem, but if possible, I am looking for a softwares solution.
This will be used to make a telephone (with an attached Arduino) that will play a series of conversations when specific codes are dialed.

possible duplicate of Connecting an Arduino to a telephone line?

Which connection are you trying to make? Are you trying to connect the arduino to a telephone line. Or simply connect the arduino to the "sound output" of a cellphone?

@GregHewgill - not, not a duplicate.  The question is really very different - this is not about electrical connection but about detecting combinations of two tones.

@ChrisStratton: Yes, that's also asked in the linked question. Perhaps the linked question is too broad.

cough cough ever tried googling? http://forum.arduino.cc/index.php?topic=121540.0

As John Taylor said, DTMF is not a single tone but two tones transmitted simultaneously, which select the digit from a two-dimensional grid. (Dual tone multi-frequency). This allow 16 possible combinations from only 8 distinct tones.
There are chips available specifically for the task of decoding DTMF, but it's always nice to try and find a one-chip solution.
There are two solutions that I can think of:

ArduinoFFT - a Fourier transform is an operation that splits a time-based signal into its frequency components. If you control the ADC directly instead of via the Arduino library, it is easily fast enough to sample a DTMF signal. Once you've done the FFT you just need to find the peaks in the output, which will tell you the tones that are present.
If you put the signal through the analog comparator and count the rate of zero-crossings (use an interrupt with a routine that increments a number, you may miss some if you just poll the pin), the rate of crossings should be unique for each tone combination. Counting for e.g. 10 ms and looking up the closest match from a table you've pre-measured should give reliable decoding, and is a slightly less brute-force approach than an FFT.

That said, you won't be able to beat a dedicated chip (although I personally think this way is much more fun.)
Happy hacking!

It is possible to decode DTMF tones with only a few common external components. The trick is to turn the analog audio into a digital signal, and then check the timing between the leading and trailing edges in order to figure out which tone is present.
First, create a 1.1V bias using a voltage divider. This bias will connect to both a capacitor that is coupling the audio, as well as one of the analog inputs. Note that phone lines have high voltages on them at times, and you must have both isolation and voltage clamping in place before connecting a device to one.
Second, enable the analog comparator in the MCU. See the "Analog Comparator" section of the MCU datasheet for details. Configure the non-inverting input to connect to the internal bandgap reference, the inverting input to connect to the analog input chosen earlier, and the output to connect to the input capture facility.
Third, configure the input capture facility in the MCU. See the "16-bit Timer/Counter1 with PWM" section of the datasheet, with particular emphasis on the "Input Capture Unit" subsection. Note that there is no way to trigger the input capture on "any" edge, therefore you will need to either flip the capture edge select bit each time, or you will need to detect the tone from only one set of edges. Also note that you will need to use the overflow interrupt to increment your explicit "high bytes" counter in case the edges to be detected appear on opposite sides of the overflow.
Now that all that is done, all that remains is to compare the timing detected by the input capture with your internal table of timings and select the appropriate tone from that. But that's the easy part.

http://www.seeedstudio.com/depot/DTMFDual-Tone-Multi-Frequency-Shield-p-1839.html
As an expansion to this answer: There are a lot of arduino shields made for this purpose. You should check on the search query: "Arduino  DTMF shield". Most of them work by inputting a 3.5mm jack. This would be easier as a phone line, as those can vary in voltage etc.

Alas, you are handwaving away what is by far the most difficult part - simply digitizing, and timing zero crossing intervals will not be an easy way to detect the combination of two simultaneous tones which may (at least by the time they get to you) be of different amplitudes.

@ChrisStratton: If it can be done in a PIC, it can be done in an Arduino.

DTMF is actually two non-harmonically related frequencies transmitted at the same time as opposed to a single frequency tone that can be measured with the above process, hence Dual-Tone-Multi-Frequency:

You can use the Rohm BU8872 series devices which decodes the 4 x 4 multi tone combinations directly into a 4 bit digital result per the grid above.  This also works the same way in the Mitel MT8870 series devices (I think they were bought by Microsemi).  These have digital filtering which pick out the two signals and some devices can even do single tone detection.


text:
Using Multiple Serial Ports with arduino nano
I am using a arduino nano to control a adafruit ultimate gps and a xbee wireless controller. However I recently ran into a problem using both at the same time (before I was using each separately until now) and read that I cannot listen to 2 software serials at the same time with a arduino. The biggest problem I see is that since I can only listen to one at a time, if I open a port, will cached data from the xbee and/or gps instantly start transferring in? Or or it more luck based that I will catch it as it comes? How should I go about coding around this? Should I just close and reopen the ports as needed(assuming there is no luck factor involved)? Any help is greatly appreciated. I will explain more if necessary.

You can use SoftwareSerial library in order to instantiate a second (soft) serial port.
By looking at the example, it seems that you can use any two digital pins to use SoftwareSerial library and instantiate a second serial port along with the hardware serial port.

You might be able to use the GPS's EN pin to enable and disable the communication to it, and also try to use the RTS/CTS pins of the XBee to control the flow, since that's their actual purpose there :)
I hope that helped.

The EN pin might shut it down and then you'll have to reconnect to sattelites?
You could however, use a transistor on the dataline so you can toggle the stream of data coming in.

The Mega and the Due have 4 UARTs. It seems like those should work, but they are much larger. I'm embarking on a project that needs to be small and use two serial ports. I'm looking at the Teensy, which has three UARTs.


text:
How can I add some additional 5 volt power
I have an Arduino which is being powered by a 9v, 2 amp power supply.  I have about 20 relays which are powered by 5 volts each.  I do not want to over work the voltage regulator on the board, so I would like to add another (possible 2) 5 volt regulator that I bought on amazon.  I am planning to:

Connect the regulators VIN to the Arduino's vcc (9 volt)
Connect the regulator's GND to the Arduino's GND.
Connect the regulator's VOUT to the Relay's VCC

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?
Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Absolutely. But don't daisy-chain the regulator to each supply input in turn, connect each one separately directly from the regulator.

Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

It is not advisable. Small manufacturing differences between regulators can result in them outputting slightly different voltages, which will lead to destruction of hardware.


text:
Is there a way to play sounds from an Arduino without using a sound shield?
I would like to play a wav file (spoken words) from my Arduino.  I do not want to add a sound shield.  Is there a way to play a sound through an output pin?  The quality does not have to be great.

Does anyone know how to do it without an sd card? I really need to know for a school project that we have to finish in like 2 days. help?

I helped someone with a similar question. The results are in my github repo at https://github.com/linhartr22/count. This example uses the PWM library and includes a reference to the article I used to learn how to convert audio files to MP3 with proper settings for the PWM libary. It plays audio through an 8 ohm speaker or a piezo buzzer connected directly to the Arduino.

The PCMAudio example shows how to play audio data via PWM. Note that you will need to access the MCU at a low level in order to do this; the Arduino libraries don't provide enough control over the hardware.

Yes, you can - see http://www.instructables.com/id/Simple-Wav-Player-Using-Arduino/
Space is quite limited, unless you use an SD card.

Yes, I did a project yesterday to play recorded voice.
You don't need a speaker module.
Just connect the speaker via a resistor to one of Arduino PWM output. Then Connect a micro-sd card module. Format your micro-sd card with FAT32 Option.
Use Sample wave converter to convert your sound files and select the options as 16,000Hz Mono 8Bit. You are all done. Use tmrpcm library. It's all easy.

old post but still a good question...
Here is a tutorial for playing 8 bit 33khz audio using the Adafruit M0 Express. You can play ~60 seconds of audio from the 2MB onboard flash through the 10bit Analog out pin.
https://github.com/hydronics2/SamdAudio
two other audio board solutions that offer near 16bit quality...

Adafruit's circuit python boards itsbyitsyM0, M4, feather M0. Same as above but using the circuit python interface instead of Arduino.
teensy3.2, teensy3.5, teensy3.6 (you can play out using the Analog pin without the audio shield but the audio shield has a nice 1/8" jack

Teensy Tutorial
Adafruit tutorial

Welcome to Arduino Stack Exchange! I am a bit puzzled by your answer because it is specifically about not using external hardware like a shield, but "to play a sound through an output pin". Thus your answer does not address the question at all.

@NickGammon The boards suggested are not shields or add-on boards but instead alternative Arduino (like) hardware. I agree it is 100% to the question but it is still a worthy answer for those visiting this question.

@NickGammon hey Nick! I love your work.. I use your tutorials all the time. Yeah I guess I forgot to say that you can play 20-60 seconds of audio from onboard flash. The Adafruit M0 has 2MB of onboard external SPI flash.

@Hoytman i think this arduino library can help you a lot https://sensorium.github.io/Mozzi/


text:
Find number of RX and TX-pin on ArduiMu
I've got an Arduino V3+ and need to find the correct PIN number for its RX and TX-pin on the FTDI-connector.
How can I find out the correct number of them to use them with the SoftwareSerial-library?
Why I need these numbers:
I'm connecting a Sparkfun Bluetooth Mate/BlueSMIRF to the ArduiMUs FTDI headers and need to set a few settings in its command mode before it operates without flaws.
This is the code I'm using:
#include <SoftwareSerial.h>

int bluetoothTx = ???;  // TX-O pin of bluetooth mate, Arduino D2
int bluetoothRx = ???;  // RX-I pin of bluetooth mate, Arduino D3
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  Serial.begin(9600);  // Begin the serial monitor at 9600bps

  bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  bluetooth.print("$$$");  // Enter command mode
  delay(5000);  // Short delay, wait for the Mate to send back CMD
  bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably
  bluetooth.begin(9600);  // Start bluetooth serial at 9600
}

You can use FTDI cable with your board on the last row of pads as you have highlighted.
Unfortunately your board designers do not publish a pdf version of the schematic so I opened the provided schematics in EAGLE and exported the FTDI connector diagram.
Here is the FTDI connector connections from the schematic:

Here is the pinout of the FTDI cable

So you can solder a 6 pin header on the bottom row and use the standard FTDI cable.
The FTDI row on your board indicates "BLK" on the left so orient your FTDI connector's black wire with the "BLK" pad on your board.
EDIT:
As per your edits you are using hardware serial on your arduino board to monitor and you are using one instance of "SoftwareSerial" to interface with bluetooth.
As SoftwareSerial library says, you can define any digital pins for Tx and Rx. In the example they have used Arduino pins 10 (pin 14 of the ATMEGA) and 11 (pin 15 of ATMEGA) for Rx and Tx respectively. In your non-standard arduino board, the micro-controller pin 14 is labeled as PWM1 and pin 15 is labeled as MOSI and they are brought out on connector JP7.

So in a nutshell you can use pin 4 of JP7 as SoftRx and pin 5 of JP7 as SoftTx.
If those pins are in use, you can always use other digital pins that are unused in your design. Just refer to the schematic of your board, ATMEGA328 datasheet and arduino libraries.

Thanks for your effort. I'm already using a FTDI cable to put Arduino Software on it. I need to know to RX & TX pin mumber because I connect a  Bluetooth module (FTDI compatible) and need to send a few messages to it (it is a Bluetooth Mate Silver and has a command mode). I need the pin numbers to communicate via ArduiMu with the Bluetooth module.

@Hedge pin number of what? ATMEGA device? pin number of board? pin number of FTDI cable? Please clarify your question. Thanks.

Sorry for the confusion. I need the PIN number of the RX and TX pin on the Arduino board to write to the TX channel and receive data from the RX channel of the ArduiMU overall. The SoftwareSerial-library needs the port numbers of them to operate SoftwareSerial mySerial(10, 11); // RX, TX

I added the code I need the PIN-numbers for to the original question. You should be able to  better understand what I'm trying to do.

@Hedge now I understand that you are using the main ftdi port to monitor and want to use another serial port for bluetooth. Is that correct?

If the bluetooth-device would accept data sending through the default Serial-port Serial.print("$$$"); it would be good enough too but it doesn't seem to work. I would prefer it this way since Bluetooth Mate and ArduiMU have 6 matching pins and therefore i can plug the Bluetooth Mate directly in the ArduiMU.


text:
How to make the Yun allow access to a resource
I have replaced /www folder on the Yun (backing it up first), how do I make it so the Yun will redirect to the new index.html? It, right now, gives Access to this resource is forbidden when I go to yun-name-here.local
Edit: I guess it's relevent to add I can do it fine with yun-name-here.local/index.html meaning it works. The real question is how to make it so I don't need to type /index.html (HURRAY LAZINESS!)
Edit II: It's Kittens game

Did you try editing the web server configuration?

web server config?

@IgnacioVazquez-Abrams I think I borked it... I replaced /etc/config/uttpd with it's backup after modifying and now I can't connect

fixed the borkedness

Which web server did you install on it?

@IgnacioVazquez-Abrams manly face Kittens Game manly face fail

That sounds like a web application, not a web server.

@IgnacioVazquez-Abrams It's both. I downloaded it from the git repository, and moved it to /www directory

Nothing in that repository is a web server.

The question still stands, though


text:
Increasing ADC resolution
At this moment I am using oversampling to increase my analogread resolution.
This in combination with increasing the frequency of the ADC.
Is someone able to take a look at it?
#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int value[100];   // variable to store the value coming from the sensor
int i=0;

void setup()
{
  Serial.begin(9600) ;
 int start ;
 int i ;

#if FASTADC
 // set prescale to 16 (1MHz)
 sbi(ADCSRA,ADPS2) ;
 cbi(ADCSRA,ADPS1) ;
 cbi(ADCSRA,ADPS0) ;
#endif
}

void loop()
  {
  for (i=0;i<100;i++)
  {
   value[i]=Read12bit(0);
  }
  for (i=0;i<100;i++)
  {
   Serial.println(value[i]);
  }
  Serial.println();//Some blanks between values
  Serial.println();
  delay(5000);

}

int Read12bit(uint8_t pin){
      int Result = 0;
      analogRead(pin);                      //Switch ADC
      for(int i = 0;i < 16; i++) {          //Read 16 times
        Result = Result + analogRead(pin);  //Sum results
      }
      Result = (int)Result/4;               //Divide by 4 for 12 bit value
      return(Result);
    }

At this moment the resolution of this oversampled analogread is 12-bits. With a little calculation the time to read will take 0,208milliseconds. If I want to increase my resolution more i.e. 13-bit. This will take the measurement 0,832 milliseconds. This seems rather big, so my question is can I do this in another way?
EDIT
Why?
I am trying to position multiple linear actuator using multiple arduino's connected via CAN-bus (the arduino's will not communicate with eachother unless an error occures) THe positioning has to be precise (<0.1mm on a 30 cm rod).
Why is 12 or 13 bit accuracy and/or resolution needed?
12 is probably enough. But I just like to find out the boundaries of the equipment :)
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Probably none 13-bit resolution is probably too high for my application anyways.
Other reason why I like a higher resolution
First couple of voltages I cannot use. My sensor gives a 4 to 20mA signal which i convert with resistor to ground.

Telling us the desired resolution and maximum allowed sampling time would help. Telling us why would help more. ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified. || You cannot usually extend ADC bits indefinitely by oversampling with any great  expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold ....

What desired max sampling time at say 12 bits?

as low as possible, I do not want my loop time over 10 ms (with some safety milliseconds build in). More then a millisec for a measurement is too much.

Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.
I often use the MCP3553 which allows 60sps at 22-bit.

Thanks for the tip. This wouldn't do the trick, the sample rate is too low (16 ms/sample)

Still considerably faster than your 208ms

Think you misread :p, 0,208ms @ 12-bit resolution. But every bit of precisionmore it will take 4 times as long.

As opposed to 16ms at 22bit resolution...

This is in response to the question.
It is an answer to the extent that it says that

The current method may not work (several reasons given),
There may be better ways to do it, and
Is it necessary?

Addressing these points, or knowing that they have been addressed, is an essential part of arriving at a good solution .
If we knew the desired conversion time and actual desired resolution it would allow better answers.
If we knew what you were trying to do it might help immensely.
ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified.
Apart from the statistical sampling considerations that you are addressing, you cannot usually extend ADC bits indefinitely by oversampling with any great  expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold and acquisition gating and more work.
As you try to squeeze more bits out of the ADC the assumptions become less likely to be consistently valid.
Also, implementation of the analog input circuitry initially becomes important and then immensely important as bits of ADC resolution increase (whether achieved by over sampling or other means).
12 bits  = 0.0244% per step (as you know)
or 1.22 mV steps in a 5V reference system
or 0.81 mV/bit in a 3.3V reference system.
Getting your overall system working to that level of accuracy is possible but usually not achieved.
Any reference you are using will be natively much less accurate than that and those sort of accuracies will require calibration both initially and possibly ongoingly.
Ratiometric systems, where eg the excitation voltage of a bridge also serves as a reference, allow reference accuracy to notionally be perfect (as readings and excitation are the same and move together.
However, ensuring that the voltage at the controllers Aref pin wrt controller Agnd, and the bridge's excitation pin wrt the bridge's ground input are the same  within usefully under 1.22 mV in a 5V 12 bit system (0.6 mV in a 13 bit system, and that the bridge and controller grounds are the same within say a few hundred uV, are an obvious necessity if the 13 bits of resolution are to be meaningful - but unlikely to be achieved without the most exquisite attention to both design & implementation. (Ask me how I know :-).)
Generally, it will be much easier to obtain and maintain ADC resolutions of as many bits as are needed by the use of purpose designed conversion ICs operating as close to the signal source as is reasonably possible. (Or using instrumentation amplifiers to acquire the signals and reliably "convey" them elsewhere.) Knowing desired conversion times and resolutions is a necessary first step.
BUT
Why?
Why is 12 or 13 bit accuracy and/or resolution needed?
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Such requirements - and much more accurate again, certainly do exist.
But knowing what the actual application is may help with decisions of how to meet it.

Thank you for your detailed answer! questions answered in my original post

In my tests, the Arduino ADC starts to suffer from accuracy issues when you push it to 500kHz for oversampling, but 250kHz does not suffer from this problem. Also you need some kind of dither/noise, or the oversampling does not really work. I found that pulsing a digital pin with a resistor connected to ground gave me enough noise for the techinque:
https://edwardmallon.wordpress.com/2017/02/27/enhancing-arduinos-adc-resolution-by-dithering-oversampling/

I found that two factors really mattered when I am taking voltage measurements.  First was a 100 uF cap across the analog pin and GND, and second was to make sure my voltage divider was set up to provide a sample voltage right in the middle of the ADC's range.  Never did try to adjust frequency, but I did definitely notice that it wasn't accurate at all until it had taken a few readings (with short delays in between on the order of a few seconds) before starting the 1-minute-per-reading loop.

you squeezing run time, I wonder, how much time you may save,
if instead of looping to measure you do 16 times +=
and >>2 instead /4
an another optimization to make  an own analog read function, it would be pretty simple based on original, so in additional you save time to call read function 16 times with all CPU overhead for each call.
lastly, in your own read function run the ADC in free run mode and accumulate a significant amount of data samples for oversampling.

Please improve your post by checking your grammar and semantics. I tried to edit it, but I don't get what you want to express.


text:
Arduino ADK, other board, shield or what?
Sorry for bothering.
I have a problem with my project and I can't fine someone who can help me yet.
I need the next configuration:
PC --------------USB cable-----------------MegaA---------------USB cable----------------MegaB
I need serial communication with USB cable in both boards.
I have now solved the ( PC --------USB cable------MegaA) part.
And the other part, I have done PC------------------USB cable------------------MegaB
But I need do that like the first schematic.
I don't have access to the MegaB because this is inside a machine, I can't access to its pines, I need connect to it by USB Cable.
Is possible do that with ARDUINO MEGA ADK in the MEGA A position? or I need other kind of board or add one shield (like USB host)?
I need send one thing from the pc to MegaA and Mega A send the same thing to MegaB.
Is it possible? because I can't find some way to specify that I need recieve the information from one serial port, and send it to another different serial port.
I need help, is very important.
Excuse my english
Thanks

Does MegaA have to relay your thing to MegaB? Couldn't you just use a USB hub to plug both of them into the PC?

You would need a USB host shield to achieve what you want.
The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware.  In this case the USB Host Shield as detailed on the Arduino website:
http://www.arduino.cc/en/Main/ArduinoUSBHostShield
In the list of supported devices is:

USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.

I think that Hot shield is the answer, but I don't know If I can use both ports at the same time ( if one of them not cancel the other one) and how i can indicate the port to receive and the port to send, all the programs that I have found using the serial pins, and when it define the serial communication using the pins number to differentiate the receive part of the send part.

You seem to be a bit confused about what a host shield does and how it connects to the Arduino it is stacked on.  There won't be any confusion in your program as the Host operations will be quite distinct.  It is possible you will eventually end up with a "HostSerial" or something class you can use to talk to the slave Arduino, but it will be up to you to proxy messages arriving on "Serial" through to that when appropriate.  To be honest, what you want to do seems beyond the realm where Arduino is a sensible choice.

A USB host is far beyond what an AVR Mega handle. You could add a 'daugther' board of some kind, but that would be a computer far more powerfull than the Mega itself (think of a RaPi, or a fat 32-bit micro-controller), so it would be a bit weird.
You might physically patch the first USB through to the second one, using for instance a relay. That would allow the PC (but not the first Mega) to talk to the second Mega.

The USB Host Shield, which will do the job fine, is not "a computer far more powerful than the Mega itself".  The Arduino is perfectly capable of performing the task with that small addition of a single SPI interfaced USB host chip.

@Majenko - on the contrary, most hosts are in fact computers more powerful than the mega.  But the real solution is to replace the hosting mega itself - for example with a $3.30 KL25Z

You don't actually need to use serial-over-usb, the two devices can communicate more simply. The simplest way would be to Serial1, which uses pins D18 and D19; connect Serial1 on MegaA to either the serial or serial1 on MegaB. Since MegaA's transmit is MegaB's receive, you need to cross-over the wires (i.e. connect MegaA's TX to MegaB RX and vice versa).
Complete details can be found at: http://www.arduino.cc/en/Tutorial/MultiSerialMega
Make sure the two Megas have a common ground - the easiest way is to use one power supply (in your case, the USB) - you should just be able to wire GND and +5V from one board to the same pins on the other. If you use two different power supplies (e.g. two USB ports, even on the same PC), they may have different ground levels, and you can get a current flow directly out of one ground, and in to the other, damaging your PC.

"I don't have access to the MegaB because this is inside a machine, I can't access to its pins" - so how does he go about that then?


text:
I am running 1.6.5, but the folder says 1.6.3?
I just downloaded the latest version of the Arduino software (1.6.5). However, when I look into the Application Support folder under Library (I have a mac), I find that I have a folder named 1.6.3:
Library ▸ Arduino15 ▸ packages ▸ arduino ▸ hardware ▸ sam ▸ 1.6.3
Does this mean there is a hidden 1.6.5 folder that I am not seeing?
BTW, this issue surfaced, because I am trying to fiddle around with the ADC clock speed, but it seems that nothing is happening:
void setup() {
  #define ADC_FREQ_MAX = 1;
  Serial.begin(9600);
  Serial.println(ADC_FREQ_MAX);
}

void loop() {
}

gives me:
opamp.ino: In function 'void setup()':
opamp:2: error: expected primary-expression before '=' token
opamp.ino:4:18: note: in expansion of macro 'ADC_FREQ_MAX'
opamp:4: error: expected primary-expression before ')' token
opamp:4: error: expected ';' before ')' token
expected primary-expression before '=' token

It could simply be that the versions of code within that folder are at a level called 1.6.3.  Big applications are usually componentized which means that the release level of the app as a whole may be different from the release levels of its parts.  I could easily imagine that inside the 1.6.5 IDE there are parts that haven't changed since 1.6.3 and hence retain that version identity.

Ok, but I am changing the ADC frequency to like 1Hz, and I can't see any noticeable change, i.e. the analogRead() function still samples way faster than that - an apparent contradiction (I've even restarted the IDE)

Your define is incorrect, it should be #define ADC_FREQ_MAX 1 only, no =, no ;.

It's likely the different versions have been installed in different places - system wide vs. user-specific, etc.

I'm voting to close this question because there isn't a single, specific clearly answerable question here, and the question has been abandoned in this state long enough that it is unlikely to ever be improved.

1.6.5 is the version of the Arduino IDE.
1.6.3 is the version of the Arduino SAM Boards package that you have installed.

Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via Tools > Board > Boards Manager are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

Tools > Examples > 01.Basics > BareMinimum
Sketch > Show Sketch Folder - this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.

The error you see is because of the equal sign in your #define.  That equal should not be there. So the line that uses it ends up being.
Serial.println(= 1);
Which is obviously wrong.


text:
Weird Arduino math result
I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result.

The expression is first evaluated as an int, hence 0, before converting it to float. If you want the expression computed as a float, then at least one argument must be a flost, e.g. 800.0 / 1000.

Both 800.0/1000 or ((float)800)/1000 will work.
The former works only with hardcoded constants, while the latter works also with variables:
int a = 800;
int b = 1000;
float c = ((float)a) / b;

A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.


text:
Reading tiny voltage changes
I have an mpx12DP pressure sensor that I want to use to measure the depth of water in a 1m tall water tank.
But it only measures up to 55mV of voltage change, which the arduino can't really detect changes in. (The sensor measures 0 to 1.45psi- 1m of water should give me 1.4psi, so I should be able to get really good accuracy).
Is this as good sensor to use for this purpose? How do I amplify the signal from the sensor? I have tried an LM324 op-amp, but couldn't get it to work (this may be entirely the wrong thing to use! And I was utterly unsure of the kind of circuit to use it in). Any advice on parts.. schematics.. a suitable already-amplified sensor that reads only up to 1.45psi?
Thank you,
Pressure sensor datasheet: http://www.digikey.co.uk/product-detail/en/MPX12DP/MPX12DP-ND/684659
Op amp datasheet: http://www.ti.com/lit/ds/symlink/lm124-n.pdf

55 mV should be (barely) measurable by the Uno, as its analog resolution is ≈ 4.9 mV. The op-amp looks fine, how did you wire it? Did you try the non-inverting schematic on p. 13 of its datasheet?

I can just about measure it- but not good enough to tell you how full the tank is! I was hoping for much better accuracy! And I tried to wire it up like this: http://www.practicalarduino.com/projects/water-tank-depth-sensor but its awfully complex and I'm not sure I did it right... however I'm not really sure how to do it correctly!

So to try the non-inverting schematic as on the datasheet pg13.. pin 4 goes to 5v, pin 11 to gnd, then pin 9 to the -ve pin of my sensor, and pin 10 to the +ve pin of my sensor, then i should be able to read from pin 8.. this doesn't work so I have read it wrong somewhere!

Oops, sorry, didn't notice the sensor had differential output.

You could try using analogReference(INTERNAL);, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.

It is reasonable to use  analogReference(INTERNAL);, as suggested by Alexander M, to set the range of the ADC to 1.1 V.
Another alternative is to use two resistors to make a voltage divider, to make an external reference of 1 V (min.) at the AREF pin, and then use  analogReference(EXTERNAL);, but the Arduino's supply voltage is likely to be noisier than the internal reference.
Regarding tiggun's suggestion about grounding the V- pin, it isn't clear to me that the mpx12DP will function correctly with V- and ground connected together.
In any case, you can use two or three of the op amps in the four-op-amp LM324 package to make a differential amplifier or an instrumentation amplifier.  See figures 38 and 39 on page 20 of the LMx24 datasheet mentioned in the question.  Figure 38 shows a differential amplifier; you could, for example, replace R3 with a 50KΩ resistor and R4 with a 1MΩ resistor to get a voltage scaleup of about 21, via the formula shown: Vₒ = (1 + R4/R3)·(V₂-V₁).  Alternately, you can use a small variable resistor as in figure 39 to make a variable-gain instrumentation amplifier.

The reference voltage must be at least 1.0V.

Your sensor has differential output, with a voltage difference between the Vout+ and Vout- being the measurement. The span of this difference is 0 to 55mV. The reason the sensor is wired this way is to reduce noise. To amplify this type of output you would need a differential output amplifier which is more complicated than a single op amp.
However, you can also just wire the Vout- from the sensor to ground, and then use the sensor as a single-ended output from 0 to 55mV (noise might be a problem). If you do this, you can then amplify Vout+ with your LM324 op-amp as described on page 13 of the LM324 datasheet with a non-inverting amplifier. By setting the ratio of R2/R1 to 60, you would get up to 55mV*80 = 4.4V which is pretty good.
The op amp needs some voltage headroom, so if you are using 5V supply for it, don't set the amplified voltage max to 5V.
edit: I don't think you need much headroom and 4.4V will give you better resolution than 3.3V

I can't find anything in the ATmega328 datasheet describing differential capabilities of the ADC. I did find info in the ATtiny85 datasheet, however. It has built-in 1x or 20x gain.

Never mind, I must've been thinking of the Mega.


text:
How to Store the results from a Ping Sensor in a variable
I need your suggestions and help with my Ping Sensor.
I have an Arduino Uno with a Parallax Ping sensor and a motor.
My ping sensor is set to to start the motor when the nearest object is <= 10cm. That works fine.
Now, I'd like the motor to start only if the values of the sensor are progressing in a decreasing manner i.e 15, 14, 13, 12, 11, 10 but do nothing if the values are progressing in a increasing manner.
I was thinking if I stored the last 3 pings as variables and using an if/else statement but I don't know how to implement it.
How can I implement this, or if you have any other suggestion, please help me.
Thank you
Here is what i have so far:
/* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 7;
const int motorPin = 9;
//Yomis code
//int pings[3] = {-1,-1,-1};
//int i;
//bool Increasing(int p1, int p2, int p3)
//{
//  if(p1 < p2 && p2 < p3){
//    return true;
//  }
//}
//
//bool Decreasing(int p1, int p2, int p3)
//{
//  if(p1 > p2 && p2 > p3){
//    return true;
//  }
//}
//
//end of yomis code
void setup() {
  // Set up the motor pin to be an output:

  pinMode(motorPin, OUTPUT);

  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{

  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(1000);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(2000);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(1000);

//        //Yomis code
//        if (cm <= 10)
//        {
//          Serial.println();
//          Serial.println(pings[0]);
//              Serial.println(pings[1]);
//              Serial.println(pings[2]);
//          Serial.println();
//          if(Increasing(pings[0],pings[1],pings[2]))
//          {
//            int Speed1 = 100;  // between 0 (stopped) and 255 (full speed)
//            int Time1 = 3000;  // milliseconds for speed 1
//            analogWrite(motorPin, Speed1);  // turns the motor On
//          }
//        }
//        else
//        {
//          analogWrite(motorPin, LOW);
//        }
//
//        //End of yomis code

  if (cm <= 10) {

    int Speed1 = 150;  // between 0 (stopped) and 255 (full speed)
    int Time1 = 2000;  // milliseconds for speed 1

    int Speed2 = 250;   // between 0 (stopped) and 255 (full speed)
    int Time2 = 3000;  // milliseconds to turn the motor off

    analogWrite(motorPin, Speed1);  // turns the motor On
    delay(Time1);                   // delay for onTime milliseconds
//    analogWrite(motorPin, Speed2);  // turns the motor Off
//    delay(Time2);                   // delay for offTime milliseconds
  }
  else if (cm > 10) {
    analogWrite(motorPin, LOW);  // turn the motor off
  }
  else {
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();

    delay(100);
  }

}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.m
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

The general idea of your code is fine, but it can be tweaked to make it more efficient.
Firstly, your function increasing(int p1, int p2, int p3) can be simplified to increasing(int *pingArray). This way you pass a reference to the function, rather than three ints. If you decide later that your pings array needs to hold more values you don't have to change the function arguements. However, if you're going to be experimenting with different lengths of the ping array you need to make sure you change the code within the function to reflect this. An easy way to stay on top of it is with #define:
#define MAX_PINGS 3       // Put this at the start of your code somewhere

int pings[MAX_PINGS];     // When you come to declare 'pings'
for (int x=0; x<MAX_PINGS; x++)
    pings[x] = -1;        // Whatever each element is initialised to.

// Your 'increasing' function
//   (... and the same for 'decreasing', if you decide to use it!)
bool increasing(int *pingArray)
{
    // CODE GOES HERE
    // and it doesn't matter how long pingArray / pings is
    // because you have 'MAX_PINGS' defined.
    return true;
}

// You call the 'increasing' function as you'd expect:
if (increasing(pings))
{ /* stuff */ }

Now to the concentrating:
Your initial work is good but from what I've read on ultrasonic sensors, and from experience with any generic sensor, is that the readings aren't going to be perfect. The real world is a noisy place and you aren't going to get nice, accurate distance readings. Finding the average is a simple technique, but you will need to find an optimal solution yourself. Once you have your nice row of average values you can then determine if the distance is increasing or decreasing or neither.
Thus you have two steps:
Average the distance
Create an array (dist, for now) and use it to find the average distance your sensor is from an object.
#define MAX_DIST 5

int dist[MAX_DIST];    // create an array, no need to initialise.
double distAverage;    // average distance, could be 'int' instead.
int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.

// As you get the distance from your sensor, update 'dist' and
// then calculate the running average.

dist[distIterator] = microsecondsToCentimeters(duration);
distIterator++;
if (distIterator == MAX_DIST) distIterator = 0;
distAverage = 0.0;
for (int x=0; x<MAX_DIST; x++)
    distAverage += dist[x];
distAverage /= MAX_DIST;

I hope you understand the cyclic buffer principle - if you don't you can google it! A key point about the way the code above is constructed is the use of that #define MAX_DIST 5. You can change that single number to anything and your code will change along with it. You will discover that there is an optimum number; I can't tell you what it is (but I recommend it remains odd).
Now that you have a nice reliable distance measurement, you need to find if it is increasing or decreasing...
Average the averages
As you have worked out, you need an array of values to determine if the distance is increasing. Bring in, again, the cyclic buffer.
#define MAX_DIST 5     // these could also be 'const int's
#define MAX_AVRG 3     // but my preference is this way

int dist[MAX_DIST];    // create an array, no need to initialise.
int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.
int distAvrg[MAX_DIST]; // create an array of averages.
int avrgIterator = 0;  // wwwwoooOOOOooo ? Not this time.

// There's no single 'distAverage' anymore; the result dumps straight
//into 'distAvrg[avrgIterator]'...

dist[distIterator] = microsecondsToCentimeters(duration);
distIterator++;
if (distIterator == MAX_DIST) distIterator = 0;
distAvrg[avrgIterator] = 0.0;
for (int x=0; x<MAX_DIST; x++)
    distAvrg[avrgIterator] += dist[x];
distAvrg[avrgIterator] /= MAX_DIST;
avrgIterator++;
if (avrgIterator == MAX_AVRG) avrgIterator = 0;

Now you have an array of your averages. Winner.
From here you can create your increasing/decreasing function. I'll leave most of this up to you, but consider the following:

The contents of distAvrg may not be perfectly smooth;
The longer any of the arrays, the more reliable the average;
The longer the array, the slower the response of the 'machine';
Using int rather than double for distAvrg may help 'numb' some of the fluctuations in averages;
Because distAvrg is a cyclic buffer, when analysing it make sure you start at the correct element! HINT: If you add your increase/decrease function after all the code above rather than amongst it, avrgIterator will always point to the oldest average value;
If the distAverage array gets beyond three of four elements, you should definitely pass it by reference to the relevant functions; this is what I did in the first codeblock I wrote. It's beyond this answer to explain why you should do it other than "it's more efficient". This is a general rule for any large chunk of data, but you'll learn more as you go along.

The simplest algorithm for determining whether the distAvrgs are increasing or decreasing is to run through from oldest to newest and count how many increases there are and how many decreases there are:
int direction = 0;
for (x=oldest ... x=newest)
{
    if (x > x+1) direction++;
    if (x < x+1) direction--;
}

The above is pseudo-code - you'll have translate it yourself. You end up with a value of direction that is a positive number (increase), a negative number (decrease), or zero. The actual value of direction will help you determine the speed of the increase/decrease, if it's relevant.

A possible solution:

** EDIT ** As pointed out by @EdgarBonet, double and float are 'expensive', in that they take up a lot of computing cycles to be dealt with. The Arduino website recommends avoiding them if you can. The alternative is to use scaled ints. For example, multiplying the return value from microsecondsToCentimetres() by 10 will give you the equivalent of one decimal place's worth of extra precision. No other code needs to change unless you're outputing the value on an LCD or similar and want it in centimeters. Dividing by 10 is conveniently the distance in millimeters, which is why I picked it, but there's no reason you can't scale by a different factor. Just be aware that there is a maximum (and mirrored minimum) value that int can hold, but I doubt you're going to hit it unless you scale by an unnecessarily high factor.

Let's say MAX_AVRG is 6. This gives five changes between distances to look at. The simplest function for determining an increase is:
bool increasing(int * DIST)
{
    int dir = 0;

    for (int x=1; x<MAX_AVRG; x++)
    {
        if (DIST[x] > DIST[x-1])   // change this to < for DECREASE
            dir++;
        else
            dir--;
    }

    if (dir > 0)
        return TRUE;
    else
        return FALSE;
}

The 'decrease' version is identical, save for the single commented line. The for loop starts at the second sample and checks against the previous sample, which is why x starts at 1, not 0 as 'usual'. The return value will be true if distAv has increased more times than it has decreased, and vice versa for decreasing().
Let's say distAve = { 1, 2, 1, 3, 4, 5 }. In the function:
distAve   1   2   1   3   4   5
            ^   ^   ^   ^   ^
start       |   |   |   |   |    dir = 0
increase   -'   |   |   |   |    dir = 1
decrease       -'   |   |   |    dir = 0
increase           -'   |   |    dir = 1
increase               -'   |    dir = 2
increase                   -'    dir = 3

dir > 0 therefore INCREASE.

But what if distAve = { 5, 4, 3, 2, 1, 6 } ? If increasing() will now return false because there are four decreases vs one increase, except the final distance indicates that the sensed object has ended up at an increased distance than when it started.
int distance(int * DIST)
{
    int overallDistance = 0;
    for (int x=1; x<MAX_AVRG; x++)
        overallDistance += (DIST[x] - DIST[x-1]);
    return overallDistance;
}

Now you have an explicit value for the overall distance change.

There is no point in replacing const by #define. 2) float is expensive in the Arduino, better try to use integers, even long if needed.

I agree with @EdgarBonet that it's silly or pointless to replace the const ints by #defines (as noted in his link, “const int constants do not necessarily occupy any storage” and are compile-time constants).  However, I recommend replacing const ints by enum'd constants, eg: enum { pingPin=7, motorPin=9};

@EdgarBonet: (1) I believe #define immediately describes to the reader the fact that you're simply substituting an otherwise meaningless number for a self-descriptive name - it's completely analogous to giving a variable a name rather than having to remember its address. I see your view that there's no point replacing const with #define, but tell me why one shouldn't use #define instead of const in their code. (2) Double-precision may be costly, but it's up to the coder to decide whether it's worth it or not. I agree scaling to utilise unsigned or long is lighter.

@jwpat7: I see no benefit whatsoever of an anonymous enum in place of either const or #define for an arbitrary list of integers such as pin associations or array lengths. Yes, you can save a tiny bit of typing if you have some consecutive pins but that's blisteringly trivial.

chaaarlie2, enum is a specific way of defining integer constants.  #define, on the other hand, is a non-type-checked way of defining textual substitutions.  const int is a slightly-oxymoronic way of defining a "constant variable".

Except in my answer to the OP, I'm talking explicitly about textual substitutions. Who cares if they're non-type-checked? What idiot would attempt to create an array of non-integer length, or try to declare pin 3.141 as an output? And even if they do, the compiler will cast said argument to an int - the same int each time it's referenced.

If the is no point in replacing const with #define, then stop recommending the replacement. The advantage of const is to make it simpler to clearly specify the type of the constants. 2) I am not talking about double precision, which is not supported on the Uno anyway. I am talking about simple precision, which is done by software and can make your program an order of magnitude slower. I would not recommend adding floats to an otherwise floatless program without at least warning about the consequences.

Okay but why is everyone arguing about const and #define. That's clearly not the real problem that the person who posted the question is asking, so i'm kind of lost. @chaaarlie2. What exactly does averaging the averages do, since the distances have already been averaged to find the correct distance.

Say you have six average (mean) distances. If each is greater than the previous then the distance is increasing, and vice-versa. However, if the six mean distances do not immediately indicate a specific direction, you take an average of the five differences between each distance. In this case I am using "average" in the broader sense: you could simply take a count of how many 'increases' vs 'decreases' and use the larger of the two to determine direction, or you could sum the distance-difference between each sample, eg. {5, 4, 3, 2, 1, 20} - five decreases, but an overall increase of 15.

I would use subtraction to find a decreasing series
you can subtract the new ping output from the previous one in every loop this way you can scale to a longer series without allocating more memory for the array
assuming you have defined somewhere:
/*use whatever number you want here*/
#define SERIES_LENGTH 3

declare globally:
int prevPingSample;
int decCount = 0;

than in your loop:
int pingSample = analogRead(sensorPin) //or however else you sample the sensor
if (prevPingSample > pingSample)
{ /*if the new reading is smaller than the previous -  the series is decreasing*/
 decCount = decCount + 1;
}
if (decCount >= SERIES_LENGTH)
{
    //move motor code
}
else
{
    decCount = 0;
}
//and whats left is to update the previous ping sample for the next loop
prevPingSample = pingSample;

A simpler solution. Use a variable to detect the trend and another for previous distance. Initialized to false and a very large number respectively.
Once a new distance is available the two variables are updated. If the trend is decreasing and the distance is less than your desired distance activate the motor.


text:
Analog INPUT_PULLUP for resistive sensors?
Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between Ax and GND. Software is the same, except declaring Ax as INPUT_PULLUP instead of INPUT.

Can you use the internal pull-up on an ADC pin?

Yes.

Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.
Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the DIDR0 and DIDR1 registers appropriately.

There is the convenience factor, though


text:
Pro Mini 5v with Adafruit motor shield v1 power sharing problems
I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine.
Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.
I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.

Uses 8 AA cells to power the motor shield on EXT-PWR input.
From EXT-PWR in motor shield one wire goes to RAW in Pro mini.
From Pro Mini, VCC connected to +5v on motor shield.
One micro servo having range sensor getting its current from motor shield.
Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)

Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off.
At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.
Thanks
Qazi

You mention all the power connections, but no mention of the ground...  Is the ground connected between the motor shield and the Arduino?

There are many ground pins on Arduino and motor shield, does it mean I have to connect every ground pin on both boards? I remember I connected some. Will check it again. Is there any specific ground pin to specific ground pin?

I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.

After lot of research, I found 5v regulator on pro mini is not good enough to power any outside circuit. It is running my motor shield v1 but when I want to run 9g servo from shield, servo shakes and stops in the middle. Waiting for my 5v regulator transister to make my own 5v supply.

Sounds good, a more capable linear regulator with heat sink. Another possibility is to get a DC to DC converter (buck regulator from 12 volts to 5 volts), that way is more energy efficient than a linear regulator. They cost just slightly more than a linear regulator on ebay, and don't need a heat sink.

I am talking about 7805 which is also dc to dc from 12v to 5v supply. Are we on the same page?


text:
Programmed 5 Volt output to power a relay
I need to put out 5 volts from an Arduino UNO digital pin. I've read that the pins can do approx. 5 volts, but I need to know if it will actually reach 5. I'm also powering a few other devices from the Arduino.
Are the digital pins capable of emitting 5 volts consistently? Are there any better alternatives?
Thanks.

A 2n7002 MOSFET - 15 cents in 1's at Digikey wilol allow you to drive 50-100 mA wit =h no other parts (maybe a catch diode oj the coil). A BC337 transistor will drive hundreds on mA of load (needs one resistor). NEVER drive a relay directly from a processor pin - even if you can. Too much to go wrong - uC dies ....

Your concern for the output capability of the pin should be its current sourcing or sinking capability, not its voltage. Arduino pins typically have a limit of 40ma per pin and a total maximum of 200ma. This is for the Atmega328p (you didn't say which Arduino you're using. You'll need to drive motors or relays or anything else with a substantial current requirement with a driver circuit powered independently of the Arduino itself. That can be with a shield made for the purpose or a circuit you design and build into your project. Motors and relays in particular need snubber diodes to protect the driving circuits from inductive "kickback" or spikes generated in their coils.

Note that the 40mA is the absolute maximum and isn't guaranteed.  For sustained reliable usage you shouldn't exceed 25mA.  Also the 200mA is the total for all IO pins combined.


text:
BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic
So I'm trying to hook up this BLE breakout board to an Arduino Uno. SparkFun has a hookup guide which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.
I have hooked up the board to my Uno with the following pinouts:
GRN -> Reset
RXI -> RX (tried with TX as well)
TXI -> TX (tried with RX as well)
VIN -> Tried 5V and 3.3V
CTS -> GND
BLK -> (No Connection)

I use their example code they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.
Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.

So I found out what I was doing wrong, and want to smack myself for it -.-
The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.
Hope this ends up helping someone out.