text:
Arduino fast ADC sampling--which burst control is best?
If one wants to do quick bursts of free-running ADC conversions, should one pause and restart using:
The ADC enable bit: bitClear(ADCSRA,ADEN) & bitSet(ADCSRA,ADEN),
The interrupt enable bit bitClear(ADCSRA,ADIE) & bitSet(ADCSRA,ADIE),
The start conversion bit bitClear(ADCSRA,ADSC) & bitSet(ADCSRA,ADSC),
The auto-trigger enable bit bitClear(ADCSRA,ADATE) & bitSet(ADCSRA,ADATE),
or do you need some more complicated combination of the bits?
Here's some code where I'm trying to trigger a pulse and  burst of samples and then report back to the host computer:
const int numSamples = 20;
const byte startPin = PD0; // start signal (pullup)
const byte pulsePin = PD6; // Normally low
const int pulse_us = 10 ; // output pulse length

int16_t sampleData[numSamples];
volatile int sample;
unsigned long t0, t;

// state machine:
typedef enum { STATE_NONE,  // idle
               STATE_SAMPLING, // record ADC
               STATE_DONE, // report data
 } states;
// current state-machine state
volatile states state = STATE_NONE;

void setup()
{
  Serial.begin(115200);

  pinMode(startPin,INPUT_PULLUP);
  pinMode(pulsePin,OUTPUT);
  // Clear ADC
  ADCSRA = 0;
  ADCSRB = 0;
  ADMUX = 0;
  ADMUX |= (0b0000 << MUX0); // Choose ADC channel 0
  ADMUX |= (0b01 << REFS0);  // Choose VCC reference voltage
  bitSet(ADMUX,ADLAR);  // ADC left align ADC result into ADCH register

  // sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
  // for Arduino Uno ADC clock is 16 MHz and a conversion takes 13 clock cycles
  //ADCSRA |= (0b101 << ADPS0); // /32 : 16M/32/13=38461Hz 26us
  //ADCSRA |= (0b100 << ADPS0); // /16 : 16M/16/13=76923Hz 13us 10 bit precision
  ADCSRA |= (0b011 << ADPS0); // /8  : 16M/8/13=153.8KHz 6.5us low precision
  //ADCSRA |= (0b010 << ADPS0); // /4  : 16M/4/13=307.6KHz 3.2us lower precision
  //ADCSRA |= (0b001 << ADPS0); // /2  : 16M/2/13=615.4Hz 1.6us  bad precision

  ADCSRB |= (0b000 << ADTS0); // Choose free running trigger mode

  bitSet(ADCSRA,ADATE); // enable auto trigger mode per ADSCRB:ADTSx
  bitSet(ADCSRA,ADIE);  // enable interrupts when measurement complete
  bitSet(ADCSRA,ADEN);  // enable ADC
  bitSet(ADCSRA,ADSC);  // start ADC measurements

}

ISR(ADC_vect) // Record samples
{
  sampleData[sample++] = ADC;  // read 10bit value from ADC
  if (sample >= numSamples) {
    bitClear(ADCSRA,ADEN); // stop recording
    state = STATE_DONE;
  }
}

void report(){
  t = micros()-t0;  // calculate elapsed time
  Serial.print("Sampling frequency: ");
  Serial.print((float)1000000/t);
  Serial.println(" KHz");
  for (int i = 0; i < numSamples; i++){
    Serial.print(i);
    Serial.print(' ');
    Serial.print(sampleData[i]);
    Serial.println();
  }
}

void startSampling(){
  sample = 0;
  t0 = micros();
  digitalWrite(pulsePin,HIGH);
  bitSet(ADCSRA,ADEN); // start ADC
  delayMicroseconds(pulse_us);
  digitalWrite(pulsePin,LOW);

}

void loop()
{
  switch (state){
    case STATE_NONE:
      if(digitalRead(startPin)==LOW){
        startSampling();
        state = STATE_SAMPLING;
      }
      break;
    case STATE_SAMPLING:
      break;

    case STATE_DONE:
        report();
        state = STATE_NONE;
        break;
    default:
    ;;
  }
}

Toggling ADEN was my first thought, but ADIE seems as if it would be faster, and ADSC seems cleanest, if it works to modulate free-running ADC mode.  Which would be fastest and cleanest?
I have a Nano on order, but nothing available for testing right now.

Using ADIE could give you faulty readings, as you could get an interrupt for a AD-conversion that started before you enabled the interrupts. Using ADEN will make the first conversion take longer, which you might not want. I'd set/clear the ADATE bit. Alternatively, is timing isn't that critical, you could keep the ADC running, and set sample back to zero, when you want to start recording a new set of measurements.

Thanks.  I hadn't considered ADATE.  I think I might need to do more than one bit, one to stop the next interrupt, and others to clean up the status on the first capture of the next cycle.  And protect the samples better in the ISR.

@Gerben -- Yes, letting the ADC run on automatic and toggling the sample recording seemed cleanest.

After some bumbling around, several bit are important:
ADCSRA &= ~(bit(ADATE) | bit (ADSC) | bit (ADIE)); // Disable

ADCSRA |=   bit(ADATE) | bit (ADSC) | bit (ADIE); // Enable

The interrupt enable bit bitClear(ADCSRA,ADIE) & bitSet(ADCSRA,ADIE), would stop the current ADC measurement from triggering an interrupt event.
The auto-trigger enable bit bitClear(ADCSRA,ADATE) & bitSet(ADCSRA,ADATE), triggers a new conversion as soon as the current one finishes.
The start conversion bit bitClear(ADCSRA,ADSC) & bitSet(ADCSRA,ADSC), is important for kicking off the first conversion.
The ADC enable bit bitClear(ADCSRA,ADEN) & bitSet(ADCSRA,ADEN), turns the ADC subsystem on and off, but there is a bit of a delay on start up.
Ultimately I left free-running automatic ADC enabled and switched the data recording on and off using the ADCSRA&bit(ADIE) as a "BURST" state variable.  I think this is good enough for generic impulse-response testing:
//: ArduinoPulseADCSample.ino -- Pulse a pin and sample response on ADC
// For Arduino Uno/Nano/mega
// https://github.com/drf5n/foxyPulseInduction_Discrimination/tree/discrimination/ArduinoPulseADCSample
// Adapted from  http://www.gammon.com.au/forum/?id=11488&reply=5#reply5
//          and https://github.com/pedvide/ADC/tree/master/examples/analogContinuousRead
//
// This code emits a digital pulse on A1 and collects a sample of highspeed ADC from A0
// It sets up a free-running ADC to quickly record a set of ADC data in
// response to the pulse.  The size of the pulse, pins, number of samples,
// speed of sampling, etc... are all configurable.
// The ADC interrupt handler controls the pulse length and filling the sample buffer
//
// Serial Commands:
//
//  *  Write v and press enter on the serial console to get the value
//  *  Write c and press enter on the serial console to check that the conversion status,
//  *  Write s to stop the conversions, you can restart it writing r.
//  *  Write r to restart the conversions.
//  *  Write p to emit a pulse and record a burst of values
//  *  Write d to see the data recorded during the burst (compatible with SerialPlotter)
//  *  Write m to see metadata about the sample size and interval
//
//  Loopback test with a jumper or RC network between A1 and A2.
//

// Configurables:
const byte adcPin = 0; // A0 -- Pin to read ADC data from
const byte pulsePin = A1; // Next to A0 -- pin to pulse
const byte oneshot_pin = 12; // OC1B pin on Mega, controlled by Timer1
const int pulse_us = 50; // pulse duration
const int numSamples = 20; // sample set
// Change the sampling speed with the prescaler config in setup()

volatile uint16_t samples[numSamples];
volatile int sample = 0;    // position in sample state variable
#define BURST (ADCSRA & bit(ADIE)) /* Sampling burst state variable */
int adcReading;
unsigned long sampleEnd;
unsigned long pulseStart, pulseEnd;

// ########## Timer1 One-shot functions
// The one shot pulses are output on Digital pin OC1B (Arduino Uno D10, Mega D12, Nano D3)
// Modified by Dave Forrest 2020-01-11 for Timer 1
// Based on Josh Levine's Nov 23, 2015 work at https://github.com/bigjosh/TimerShot/blob/master/TimerShot.ino

// Setup the one-shot pulse generator and initialize with a pulse width that is (cycles) clock counts long
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xffff-(cycles-1))
void osp_setup(uint16_t cycles) { // 1 idles, 0xffff never matches, 2-0xfffe makes pulses
  const byte prescaler = 0b010; // Choose /8 for 0.5us resolution
                                // 0b001: /1,      16MHz, 62.5ns resolution, 4ms max
                                // 0b010: /8,       2MHz,  0.5us resolution, 32ms max
                                // 0b011: /64,    250kHz,  4us  resolution, 263ms max
                                // 0b100: /256,  62.5kHz  16us  resolution, 1.048s max
                                // 0b101: /1024, 15625Hz, 64us  resolution, 4.194176s max
  TCCR1B =  0;      // Halt counter by setting clock select bits to 0 (No clock source).
  // This keeps anyhting from happening while we get set up
  TCNT1 = 0x00;     // Start counting at bottom.
  OCR1A = 0;      // Set TOP to 0. This effectively keeps us from counting because the counter just keeps resetting back to 0.
  // We break out of this by manually setting the TCNT higher than 0, in which case it will count all the way up to MAX and then overflow back to 0 and get locked up again.
  OSP_SET_WIDTH(cycles);    // This also makes new OCR values get loaded frm the buffer on every clock cycle.
  TCCR1A = 0b11 << COM1B0  | 0b11 << WGM10; // OC1B=Set on Match, clear on BOTTOM. Mode 15 Fast PWM.
  TCCR1B = (0b11 << WGM12) | (prescaler << CS10); // Start counting now. WGM 15=0b1111  to select Fast PWM mode
  // Setup the OC1B pin for one-shot output:
  //DDRB |= _BV(2);     // Uno Set pin to output (Note that OC1B = GPIO port PB2 = Arduino Uno Digital Pin 10)
  DDRB |= _BV(6);     // Mega Set pin to output (Note that OC1B = GPIO port PB6 = Arduino Mega Digital Pin 12)
  //DDRD |= _BV(3);     // Nano Set pin to output (Note that OC1B = GPIO port PD3 = Arduino Nano Digital Pin 3)
}

// Setup the one-shot pulse generator to idle:
void osp_setup() {
  osp_setup(1);  // 1 puts it in idle mode, 0xffff never triggers, 2-0xfffe produces pulses.
}

// Macro to Fire a one-shot pulse. Use the most recently set width.
#define OSP_FIRE() (TCNT1 = OCR1B - 1)

// Macro to Test there is currently a pulse still in progress
#define OSP_INPROGRESS() (TCNT1>0)

// Macro to Fire a one-shot pulse with the specififed width.
// Order of operations in calculating m must avoid overflow of the unint16_t.
// TCNT2 starts one count lower than the match value because the chip will block any compare on the cycle after setting a TCNT.
#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); noInterrupts();OCR1B=m;TCNT1 =m-1;interrupts();}

// ##########  End of Timer1 One-shot functions
ISR(TIMER1_OVF_vect) { //When overflow...
  //  OCRA1=ICR1; // Constant off in WGM 14, COM1A1:0==0b11
  TCCR1B &= ~(0b111 << CS10) ; //turn off clock
}

//######### ADC Bit-bang for free-running capture of A0
void adc_setup_freerunning(const byte adcPin){
  // set the analog reference (high two bits of ADMUX) and select the
  // channel (low 4 bits).  this also sets ADLAR (left-adjust result)
  // to 0 (the default).
  ADMUX = bit (REFS0) | (adcPin & 0x07);

  // Set the ADC ADPSx prescaler flags to control sampling speed/accuracy
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits

  //ADCSRA |= 0b001 << ADPS0;   //   2    5 bit,
  //ADCSRA |= 0b010 << ADPS0;   //   4    6 bit, 5.36us
  //ADCSRA |= 0b011 << ADPS0;   //   8    9 bit, 6.51us
  ADCSRA |= 0b100 << ADPS0;   //  16   10 bit, 13us
  //ADCSRA |= 0b101 << ADPS0;   //  32     10 bit, 26us
  //ADCSRA |= 0b110 << ADPS0;   //  64     10 bit, 52us
  //ADCSRA |= 0b111 << ADPS0;   // 128     10 bit, 104us

  //enable automatic conversions, start them and interrupt on finish
  //ADCSRA |= bit(ADATE) | bit (ADSC) | bit (ADIE);
    ADCSRA |= bit(ADATE) | bit (ADSC) ;

}

void setup ()
{
  Serial.begin (115200);
  //pinMode(pulsePin, OUTPUT);
  osp_setup(); // Config Mega Digital 12 for oneshot output
  adc_setup_freerunning(adcPin);

}  // end of setup

// ADC complete ISR
ISR (ADC_vect)  // Store ADC burst values
{
  if (sample >= numSamples) // watch off-by-one
  {
    ADCSRA &= ~bit(ADIE);  // end of sampling burst so stop interrupting
    return;
  }
  // Handle samples
  samples[sample++ ] = ADC;
  //if ( sample == 0){
   // OSP_SET_AND_FIRE(pulse_us * 2); //
  //}
}  // end of ADC_vect

void loop ()
{
  char c;
  char buff[80];
  unsigned long sampleDuration;
  unsigned long pulseDuration;
  // if last reading finished, process it

  // if we aren't taking a reading, start a new one

  if (Serial.available()) {
    c = Serial.read();
    switch (c) {
      case 'c': // Converting?
        Serial.print("ADCSRA: ");
        Serial.println(ADCSRA, BIN);
        break;
      case 's': // stop conversions
        ADCSRA &= ~(bit (ADSC) | bit (ADIE));
        break;
      case 'r': // restart conversions
        ADCSRA |= bit (ADSC) | bit (ADIE);
        break;
      case 'v':
        adcReading = ADC;
        Serial.print(adcReading);
        Serial.print(' ');
        Serial.print((0.5 + adcReading) * 5.0 / 1024, 4);
        Serial.println(" V");
        break;
      case 'm':
        {
          unsigned long sampleDuration = sampleEnd - pulseStart;
          unsigned long pulseDuration  = pulseEnd - pulseStart;

          Serial.print("# Pulse: ");
          Serial.print(pulseDuration);
          Serial.print("us and ");
          Serial.print(numSamples);
          Serial.println(" samples.");
          Serial.print("# Time: ");
          Serial.print(sampleDuration);
          Serial.print("us burst of ");
          Serial.print(numSamples);
          Serial.print(" samples at ");
          Serial.print(1.0 * (unsigned long)(sampleEnd - pulseStart) / numSamples);
          Serial.println("us/sample");
          sprintf(buff, " sampleEnd, pulseEnd, pulseStart %02lu : %02lu : %02lu \n", sampleEnd, pulseEnd, pulseStart);
          Serial.print(buff);
          break;
        }
      case 'p': // start pulse
        sample = 0;  // reset sample SV
        pulseStart = micros();
        OSP_SET_AND_FIRE(pulse_us * 2); // pulse outside ISR
        ADCSRA |= bit(ADIF) | bit(ADIE); // clear existing ADInterruptFlag and enable ADC Interrupts
        while(BURST); // block until burst done
        sampleEnd = micros(); // Record times
        pulseEnd = pulseStart + pulse_us;
        break;
      case 'D':
      case 'd': {// report Data
          sampleDuration = sampleEnd - pulseStart;
          for (int ii = 0 ; ii < numSamples ; ii++) {
            if (c == 'D') {
              Serial.print(ii * sampleDuration / numSamples);
              Serial.print(' ');
            }
            Serial.println(samples[ii]);
          }
        }
        break;
      case ' ':
      case '\n':
      case '\r':
        break;
      case 'h':
      case '?':
      default:
        {
          Serial.println("\nArduinoPulseADCSample.in -- Pulse A1 and read a burst of samples from A0\n"
                         "based on serial commands");
          Serial.println("# https://github.com/drf5n/foxyPulseInduction_Discrimination/tree/discrimination/ArduinoPulseADCSample\nCommands: [vcsrpdm] ?");
          Serial.println("Commands:\n"
                         "p: Pulse -- Start a pulse cycle on A1 and record data on A0\n"
                         "d,D: Data -- Dump the data from the last pulse\n"
                         "m: Metadata -- Print the length of pulse, number of samples and rate\n"
                         "v: Voltage -- Conver voltage on A0\n"
                         "c: Converting? -- show ADCSSRA register\n"
                         "h?: Help -- Print this\n"
                        );
        }
        break;
        ;;
    }
  }

  // do other stuff here

}  // end of loop

This is the output from the p,m,d commands with a jumper connecting pin 12 to A0 with the /16 prescaler:
# Pulse: 50us and 20 samples.
# Time: 276us burst of 20 samples at 13.80us/sample
 sampleEnd, pulseEnd, pulseStart 19270968 : 19270742 : 19270692
0
1020
1023
1023
1023
3
0
0
0
0
0
0
0
0
0
0
0
0
0
0

And again with the /8 prescaler.  7.2us/sample or 139Ksamples/sec for 8-9bits isn't bad:
# Pulse: 50us and 20 samples.
# Time: 144us burst of 20 samples at 7.20us/sample
 sampleEnd, pulseEnd, pulseStart 4229952 : 4229858 : 4229808
0
792
1020
1022
1022
1020
1022
1022
1022
305
3
0
0
0
0
0
0
0
0
0

ArduinoPulseADCSample.in -- Pulse A1 and read a burst of samples from A0
based on serial commands
# https://github.com/drf5n/foxyPulseInduction_Discrimination/tree/discrimination/ArduinoPulseADCSample
Commands: [vcsrpdm] ?
Commands:
p: Pulse -- Start a pulse cycle on A1 and record data on A0
d,D: Data -- Dump the data from the last pulse
m: Metadata -- Print the length of pulse, number of samples and rate
v: Voltage -- Conver voltage on A0
c: Converting? -- show ADCSRA register
h?: Help -- Print this

Here's an R-C pulse-decay trace on the Serial Plotter with a 22K resistor across A0&12 and a 22uF capacitor from GND to A0.

Re “I left free-running automatic ADC enabled and switched the data recording on and off.”: I think you could do that by toggling just ADIE, without touching ADSC. Maybe clear the interrupt flag when setting ADIE, to avoid getting an interrupt from the last conversion of the previous burst.

@EdgarBonet -- With the ADIF=1 trick, ADCSRA |= bit(ADIF) | bit(ADIE) would clear any pending interrupt and enable future interrupts.  Sounds good.  I could then use the ADCSRA & bit(ADIE) instead of burst as my "sampling" state variable and save a test. I've been tweaking things to get down to the 13us/sample threshold that I can get for the ADPS2:0=0b100 /16 1MKz speed that has full 10bit accuracy, but I haven't trimmed the ISR down enough for the /8 clock. I like the pulse control in the ISR for the sync in my use case, but it's sloppy. Maybe pulse on sample vs micros() state var?

... The pulse length control is sloppy because the pulse is started out of sync with the sampling, and finishes in sync with the sampling.  I like the end synchronization with the samples for my particular application, but it would be nicer to configure a timer as a one-shot and trigger it in the ISR when the sample == 0, then you could get higher resolution pulse lengths with both the start and end of the pulse synced with the sampling.   Maybe it could reach 6.5us/sample with 8-9 bit resolution.

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


text:
How can I get my Arduino to recognize a specific object using some kind of sensor?
This is my first question on this site, and I'm relatively new with Arduino. I do have some experience using the board to reprogram a robot that used infrared proximity sensors, servos, and switches.
I would like to add a sensor on to the robot that will allow him to recognize specific "obstacles" that I will put in his environment (not walls!) For instance, when he sees a red card, he needs to spin, but when he sees a green card, he needs to roll in the opposite direction. I do not want to spend much on the cards, but I would be willing to put a small battery and LED in them if I had to. The cards do not necessarily need to be colored, I was just using that as an example.
The robot will be in a well-lit room with noise in the background. He will be controlled by an Arduino Uno, an infrared sensor and a remote control. He can be pretty close to the cards if he has to (3 centimeters or so would be enough). It would be ideal if he could discern different types of cards, but that is not necessary as long as he's able to tell a card from the rest of his environment.
I am simply not sure how to go about implementing this. I have read about using photoresistors to differentiate color, and they're really cheap, but will they be accurate enough from a distance? This is the light sensor I was considering using:
http://www.mouser.com/ProductDetail/Adafruit/161/?qs=GURawfaeGuDpQ5XPTNqKUw%3D%3D&gclid=Cj0KEQiA6IC2BRDcjPrjm_istoUBEiQASrLz1rQNwZgntUcccnOmrFph-pCbu60R00GNozB_XbZxYz0aAn0j8P8HAQ
I'm willing to pay about 5$ for one if I need to.
If I use the light sensor method, can I just use brightly colored cards or will I need to use LEDs? Is there a better way to accomplish my goal that you are aware of?
Thank you for your time. If there is missing information in my question, please tell me and I will add it.

How about NFC RFID cards?

I'm not sure. Your mentioning it was the first time I'd actually heard about the things. They sound really neat, but it looks like it'll cost about 45$ for the setup, and for that money I can get a nice color sensor and the cards will be easier to make. Thank you for your response, though, and I will keep it in mind!

A cheap RFID sensor is a few pounds plus the stickers, they're like 0.1-0.2 pounds usually (depends on the quantity) I think you'd get like 100 stickers plus a reader for 25 pounds. Plus RFID is much more reliable.

If you are controlling your robot with a remote control, why do you need it to detect cards, instead you can tell it to do whatever you want right?
If you want to detect specific objects according to their colors, arduino is not a platform i will choose, because it doesn't have processing power to do image processing.
But take a look at this, http://charmedlabs.com/default/pixy-cmucam5/ it can talk to arduino, and you can train it by telling it identify colored objects which i might think is apt for your case.
RFID tags will be a good idea as @Majenko said.

I'm making a "game" where the robot "fights" enemies that you direct him towards. Once the robot recognizes an enemy, he "fights" it (knocks it over) and the player gets a point (or something to this effect). The Pixy looks awesome, but I think it might be a bit too powerful for a project of this scope. Thank you for your response. I will do more research on RFID tags!

You can get an RFID reader for $7 from eBay:

Cards are around 30 cents:

I have example code for an entry control system which uses that reader.
The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).
You could combine card detection with simple range finding using an ultrasonic detector.

Oh, wow, this looks great! Thanks so much! I think this will be perfect.

Detecting colour with RGB illumination and an LDR is not particularly accurate in my experience.  The idea is you illuminate the card (or whatever) with red light, take an LDR reading, then with green then blue.
This gives you a set of 3 light levels for the different colour components of the object.  Combining them together gives you an RGB signature for the object.  Ideally, on say a red card, the value from the LDR under red illumination is much stronger, and blue & green much weaker.
RGB LED + LDR colour detection does work, but it's not accurate, and it helps to block out ambient lighting.  Maybe if you put a lot of time into calibration, it would for you.  I had a classroom of 14 kids, each made-up one of these circuits, yet only a couple had any moderate success, if at all.
That said, we were using very cheap RGB LEDs and similar quality LDRs.
There's a bunch of stuff you can do to help the accuracy, like subtract readings with only ambient illumination, take multiple readings, etc.
I think you would save yourself a lot of time and frustration buy using a purpose-made colour sensor.
Something like the ADAFruit Colour Sensor -  https://www.adafruit.com/products/1334

source: Stack Exchange

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

sort: votes


text:
How can I connect a force sensitive resistor to a vibration motor via Arduino?
Please forgive me if my knowledge is limited--still very new to this!
I'm currently working on my senior thesis for my Industrial Design program and I'm struggling to figure out the components and code I need to link a FSR and a vibration motor. Basically the idea would be that high pressure on the FSR would equate to high vibration on the motor and vice versa so you could get variable intensity based off of how hard you squeeze the sensor. I've looked up a lot of different circuit diagrams for using a vibration motor with an Arduino and many of them seem to indicate that I will need a 1N4001 Diode, a 2N2222 NPN Transistor, a 1KΩ Resistor, and a 0.1µF ceramic capacitor. I'm currently using the Arduino UNO R3 and I don't want to fry it so before I go tinkering too much I wanted to ask what you all might do to achieve what I'm aiming to do.
Thank you and I appreciate any and all feedback!

When asking about circuits it's best to include a circuit diagram. The editor here includes a tool that lets you draw them as part of the question.

I'm not sure why you need the Arduino at all.  If the force on the FSR increases resistance then you just need to invert that value and apply it the motor.  To be honest this sounds more like an electronics problem so you might want to get this moved to SE EE.

Can you provide a data sheet for the fsr?

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


text:
Arduıno button problem
I did a project with a fingerprint sensor. You can do the fingerprinting process by typing down 4 on the serial port, but in the same time i want to do this process with pressing another button.Can someone help me?

code  http://www.heypasteit.com/clip/0IIQ6G
> #define  VB

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>

SoftwareSerial mySerial(10, 11);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

char data;
unsigned int p;
uint8_t id;

void setup()
{
  Serial.begin(9600);
  finger.begin(57600);
  Serial.println("Sensore baglaniyor!");
  if(finger.verifyPassword())
  {
    Serial.println("Baglanti basarili!");
  }
  else
  {
    Serial.println("Sensor bulunamadi ");
    while (1);
  }
}

void loop()
{
  delay(100);

  if(Serial.available()>0)
  {
    data=Serial.read();

    if(data=='1')
    {
      Serial.println("Delete all ID records");
      finger.emptyDatabase();
      delay(50);
      EEPROM.write(0,-1);    //reset ID counter
    }
    else if(data=='3')
    {
      id = EEPROM.read(0) + 1;    //get next available ID
      Serial.print("Enrolling ID #");
      Serial.println(id);
      getFingerprintEnroll(id);
      delay(50);
      EEPROM.write(0, id);        //save current ID
    }

    while (data=='4')
    {
      getFingerprintID();
      delay(50);

    }
  }
}

uint8_t getFingerprintEnroll(uint8_t id)
{
  uint8_t p = -1;
  Serial.println("Waiting for valid finger to enroll");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz(1);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  }

  Serial.println("Remove finger");
  delay(1000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER)
  {
    p = finger.getImage();
  }

  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz(2);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  default:
    Serial.println("Unknown error");
    return p;
  }

  p = finger.createModel();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Prints matched!");
    break;
  case FINGERPRINT_ENROLLMISMATCH:
    Serial.println("Fingerprints did not match");
    return -1;
    break;
  default:
    Serial.println("Unknown error");
    return -1;
    break;
  }

  p = finger.storeModel(id);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Stored!");
    break;
  default:
    Serial.println("Unknown error");
    return p;
    break;

  }
}

int getFingerprintID()
{
  p = -1;
  Serial.println("Waiting for registered ID");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  default:
    Serial.println("Unknown error");
    return -1;
  }

  p = finger.fingerFastSearch();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Found a print match!");
    break;
  case FINGERPRINT_NOTFOUND:
    Serial.println("Did not find a match");
    return -1;
    break;
  default:
    Serial.println("Unknown error");
    return -1;
    break;
  }

  digitalWrite(A1, HIGH);
  delay(500);
  digitalWrite(A1, LOW);
  delay(2000);

  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with accuracy value of ");
  Serial.println(finger.confidence);
  return finger.fingerID;
}

If you want to use 2 to get the finger print then change the line while (data=='4') to while (data=='2').  If you want to use 4 or 2 then change it to while (data=='4' || data=='2').  Is that what you mean?

@Look Alterno Thanks, but it’s not what I mean. I  mean doing the process with pressing random button.
Note:Serial port working

while (data=='4') will loop forever once the user enters 4, since you never modify data once you enter that loop. Is that the desired behavior?

Why is “Can someone help me?” not an actual question?


text:
Arduino sketch does not repeat
I have a Problem with my code.
My Goal is to receive a Ethernet message via UDP and send the message back via CAN.
It works fine but only with the first packet I send. When I send the same packet again there is no Response as you can see in the screenshot.
I´m using the Arduino Due with a Transceiver. The Programm which sends and reads the Messages is Vector Canoe
#include "variant.h"
#include "due_can.h"
#include "Arduino.h"

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

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

EthernetUDP Udp;

void setup() {

Can0.init(250000);
Serial.begin(9600);

Ethernet.begin(mac, ip);
Udp.begin(localPort);

}

void loop() {

    int packetSize = Udp.parsePacket();
    Udp.read(packetBuffer,packetSize);

   if (packetSize)
  {

    int Canframestosend= packetSize/8;    //Divides the Ethernet packet by 8 to match with CAN packet
    int count =0;
    int Rest=packetSize%8;                //Needed if the Ethernet packetsize isn´t a multiple of 8

    for(int j=0;j<=Canframestosend;j++){

    CAN_FRAME NewFrame;                   //CAN frames which are sent
    NewFrame.id=0xFA;                     //ID of the frames
    NewFrame.length=8;                    //Maximum of bytes a Can frame can have

    for (int i=0;i<8;i++){

       NewFrame.data.byte[i] = packetBuffer[count]; //Write the Ethernet info byte by byte on the CAN frames
       count++;
       }
    if(packetSize<count){
      NewFrame.length=Rest;                         //Shortens the last frame to avoid unnessecary zeros
      }
       Can0.sendFrame(NewFrame);

      }

   }
   delay(10);
}

Maybe there is an endless Loop but I don´t know which and why.
Hope anybody can help me with that!

I'd guess it's in the if(packetsize) logic -- if you get a packetsize of zero, you still try to read into a zero-size buffer and who knows what would happen.  Move the read inside the if(){...}
See https://www.arduino.cc/en/Reference/EthernetUDPRead
Also, you want to limit the reading to the UDP_TX_PACKET_MAX_SIZE size of the buffer, not to the size of the packet.
Update: The UDP_TX_PACKET_MAX_SIZE is only used in the user code, and nowhere else within the Ethernet Library.  You could use a larger buffer if you need to by defining and allocating a larger buffer and specifying its size in  EthernetUDP.read()  (see https://www.arduino.cc/en/Reference/EthernetUDPRead).

Thanks for your Response, the mistake was that i limited the buffer in PacketSize and not in UDP_TX_PACKET_MAX_SIZE. But what if my packets are bigger than UDP_TX_PACKET_MAX_SIZE? I wanted to be more flexible by limiting it to the packetSize i get from parsePacket.

If the packets are bigger than your buffer, you still do not want to read them into the smaller buffer. If it does write outside its allocated space, it could damage other variables.

Okay so is there an Limitation for my UDP_TX_PACKET_MAX_SIZE? I can change the value in the Code of the library and Wikipedia says a UDP packet can contain up to 65.535 Bytes

Looks like you can: http://forum.arduino.cc/index.php?topic=103502.0  Still, move your read inside the if(){} so you don't attempt to read if there is nothing to read.

Don't limit your receive buffer to the TX packet size, make it bigger than any expected received packet: BUFFERSIZE=2048; char packetBuffer[BUFFERSIZE]; ... Udp.read(packetBuffer,BUFFERSIZE);


text:
Receiving SMS by Arduino GSM Shield and control the LED with the content of this SMS?
I am using Arduino GSM Shield receiving SMS from an Android app. And the content of this SMS will control a LED. If the content of this SMS is not "off", the LED will be on and the content will be printed in the serial monitor. But if it is "off", the LED will be off immediately. Besides, the LED will keep being on until the "off" message coming. For now, I used the code from the example of the software. But I cannot use the content of this SMS to control the status of LED. With the code below, the LED could not be turned on and the content could not be displayed on the monitor. I think it was because the sketch failed to get the whole content of this SMS. Could anybody tell me how to solve this problem? Thanks.
#include <GSM.h>
GSM gsmAccess;
GSM_SMS sms;
char senderNumber[20];
int led=13;
void setup()
{
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);
  while (!Serial) {
    ;
  }
  Serial.println("SMS Messages Receiver");
  boolean notConnected = true;
  while(notConnected)
    {
      if(gsmAccess.begin("6442")==GSM_READY)
        notConnected = false;
      else
        {
          Serial.println("Not connected");
          delay(1000);
        }
    }
  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop()
{
  char c;
  int val=0;
  val=digitalRead(led);
  if (val==HIGH){
    digitalWrite(led,HIGH);
  }
  if (sms.available()){
    Serial.println("Message received from:");
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);

    if(sms.peek()=='#')
      {
        Serial.println("Discarded SMS");
        sms.flush();
      }
    while(c=sms.read())
      if(c='off'){
        digitalWrite(led,LOW);
      }else{
        digitalWrite(led,HIGH);
        Serial.print(c);
      }
    Serial.println("\nEND OF MESSAGE");
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

If the below answer actually helped you in fixing your problem, please mark it as answered/correct. Also, it would help others if you could edit your question to reflect the changes you have made to get it working.

@user2788 I added it below while, and then use strcmp(smsData,"off")==0 to check whether the content of this sms is "off".

First of all, you have a typo: You need the double-equals operator in
if (c == 'off') {

But more importantly, you can't use a char variable to hold or compare more than one character at a time. I don't know the details of the Arduino GSM library, but if sms.read() returns a string, then you'll need a string variable or an array of char to hold the result.

sms.read() function returns only a single byte of the SMS string. You can store the whole data in a character array and process it later like following:
char c, message[140];
int i=0;
while (c = sms.read()) {
    message[i++] = c;
}
if (strstr (message, "off")) {    //If SMS contains off anywhere
    digitalWrite(led,LOW);
} else {
    digitalWrite(led,HIGH);
    Serial.print(message);
}

And I believe the following portion in your code is not required as it is doing nothing:
val=digitalRead(led);
if (val==HIGH){
    digitalWrite(led,HIGH);
}


text:
Bluetooth Arduino control (was Speech recognition arduino control)
How to I control arduino with voice. I got an Android app but it works only with Internet connectivity. So I was an Android app with works offline when I connect to my Bluetooth HC-05. Please suggest me some ideas

You again?! We aren't an Android App search engine I am afraid. Maybe you should ask somewhere more appropriate?

But with that only we control arduino ya

99.999999999% of all android speech recognition apps use the Google Speech API. That is, by its very nature, an on-line facility. Good luck finding one that can run stand-alone on phone and is actually capable of recognising voice reliably.

The fact that, somewhere down the line, after going through a number of other bits of hardware, you may be controlling an Arduino is neither here nor there. We don't know (and we don't care) what android apps are available for voice recognition. Ask on an Android App forum, or maybe search the play store

By asking here you're effectively asking car mechanics about the technical aspects of the petrochemical industry.

I thought I will get the answer here.. As Android control over adruino is very command. My apology to you then

Android control may be common - speech recognition isn't and off-line speech recognition is even further from common. That is a very specific topic and as such has nothing at all to do with Arduino.

As far as the Arduino side of things, this question is effectively "Bluetooth Serial ardunino control".  Or maybe this question is intended to be "What sort of voice control apps can send strings to bluetooth".  The second question is better asked elsewhere, and also answered before any progress can be made on the first.

You might find your answer with someone else who has done the same thing on Instructables:
Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/
Hope this helps!

You might add the bluetooth/serial parsing code from that link, and a note that it gets the serial input from the Android app AMR_Voice.

ARM app works with Internet connectivity


text:
Digital pin output voltage, not triggering 71mA relay coil
I have a relay (VRS4H-S-DC5V-C), for which the triggering voltage required is 5V Min.  If I directly use the 5V voltage of Arduino  I'm able to trigger it, but if I use any digital pin in OUTPUT mode in digitalWrite I'm not able to trigger the relay.
Earlier I thought that it must be that because it's a small board its digital pins would be giving HIGH state as 3.3.V, but the fact is when I checked both the voltage of 5V (which is obviously shown 5V on multi meter) and that digital pin one, both show 5V. So the question is why the hell is digital pin not able to trigger the relay, since trigger the relay by 5V is of no use for me since I can't control it, i.e., when it should trigger and when not?

From the datasheet, the coil resistance is 70 ohms at 5V, so it is trying to draw 5/70=0.071A, or 71mA, which is more current than a nano can source.

Okay @Dave X...

The digital output pin cannot output sufficient current to drive the relay directly. Iirc this question was already asked. You need to add between the Arduino and the relay a driving stage, for example with a FET. Or you can use a shield that already has this additional circuitry.
Just google for "Arduino relay driver circuit" and you will get various options.
This is pretty close to your setup.

BTW, I just found out that at least some companies produce what they call "digital transistors" which is a fancy way to say that the component already contains some resistor integrated. Example: the resistor on the base of a BJT.

I used to use those for a while. You can get them with just a base resistor, and also with a base pull-down resistor integrated. Useful if space is a premium and/or you have thousands of them on a board. Other than that, for the cost of a couple of 0603 or 0402 resistors, they're pretty pointless.

Well firstly thank you both for such a quick response....the answer was quite okay...but the comments ...i found that quite overwhelming ...as in I dont belong to Electrical Domain by core I m a mobile Developer...so could you just explain it in rather simple words...i mean the comments part...i got the answer quite well...

When you follow the link I provided, you can see that it instructs you to build a circuit. Such circuit contains a transistor and several resistors. The comments were referring to special components called "digital transistors" which put, inside the same package, both the transistor and one or more resistors, thus reducing the number of individual packages that you have to interact with. It's just an optimization that you can safely ignore.

well okay got that...i found something after googling the keys u gave me....as in using 2 resistors , a transistor and a diode...i didnt remember exact values of them... but using them i can increase the current rate and therefore do my needful thing... :)


text:
Help compiling multiple .ino file code with code! (I'm not sure what to name this)
Ok, so i'm trying to make This Project and the code comes all in different .ino files but in the video its all in one program. So how do I compile all of the code onto the arduino? (By the way the code is on step 5 in a .zip file) Thank you!

One of the .ino files is likely the main code file.  Name the enclosing folder with the name of the .ino file, then compile it as normal.
In this case, AbHhGD.ino is the main file, and its folder should be named 'AbHhGD'
The comments indicate there are missing libraries you likely need to install.

Ok so I just rename the folder that has everything in it to AbHhGD and then compile abHhGD.ino?


text:
Machine installed with arduino suddenly turns on when usb is unplugged
Why is my machine suddenly turns ON when I unplugged the USB on my computer? Does it have connection on the auto reset feature of my arduino board?

String input = "";

void setup(){

  Serial.begin(9600);   // Sets up communication with the serial port

  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

  digitalWrite(11,LOW);

}

void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
    int data = Serial.read();
      // convert the incoming byte to a char
      // and add it to the string
    input += (char)data;

    recipe = input.toInt()+'0';    //recipe=0 if not a digit
    if(recipe == '0')
      recipe = data;

    if(data == '\n'){
      //Serial.print("Recipe: ");
      //Serial.println(recipe);
      //Serial.print("String: ");
      //Serial.println(input);
      input = "";
    }
  }

  if(recipe == 's'){
    digitalWrite(11,HIGH);
    delay(1000);
    digitalWrite(11,LOW);

    digitalWrite(6,LOW);
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
  }

  else if(recipe>'0' && recipe<'32'){

    recipe = recipe-'0';
    char binary[7] = {0};   // This is where the binary representation will be stored
    recipe += 32; // Adding 32 so that there will always be 6 digits in the string
    itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
    char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

  //Serial.print(signals);  // Print out the signals in binary

    int i;
    for(i=0; i<5; i++){
      if(signals[i] == '0')
        signals[i] = '1';
      else
        signals[i] = '0';
      digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
      //Serial.print(signals[i]);
    }

  }
  else
    loop();

}

Post your schematic or wiring, and point to the datasheet on your machine.  Maybe when the arduino is depowered and the pins tristate, your machine is no longer inhibited from being ON.  But that is only a guess based on the information in your question.

hi Dave X, where can I send/post my schematic diagram? do you have an email or something so i can show both the wiring and arduino code. thanks in advance

Please add it to your question.  The editor has a little mountain-landscape icon that lets you upload graphics.

Hi Dave x, here you go. I have added the sketch as well for you to correlate. this is to automatic select recipe once press "send recipe" and automatic start the tool once press "start" button

Is your Arduino powered only through the USB or is there alternate power?

Opening a serial connection will reset the board.

DaveX yes the arduino is connected on the tool's controller as well which also supply power to the board

I have already tried to put a 10uf capacitor to disable the auto reset but tool still start when i pull off the usb cable from the PC

Do not call loop from loop. You will quickly run out of RAM and the sketch will crash:
void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
...

  }
  else
    loop();

}

For the pins that are supposed to be high, I suggest pull-up resistors:
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

When the Arduino powers up it enters the bootloader for a second or so. Those pins won't be set high yet. A pull-up resistor would make sure they are high until such time as you want to drive them low.

If you are saying that the machine powers up when you disconnect the power to the Arduino, that is still a good reason for using pull-up resistors, to make sure that it does not operated until commanded to do so.

where will i connect the pull up resistors and how?

Typically pull-up resistors will be around 10k, and are connected from the pin to +5V. Of course, if the Arduino is not powered, then you need another source of the +5V.

please to clarify the "do not call from loop to loop"

Remove these two lines:
else
    loop();

When loop exits, is it immediately re-called. You don't need to do it that way, in fact it is a Bad Idea.

Hi Nick, where will i connect the pull up resistors and how? and also please to clarify the "do not call from loop to loop". What line should i need  to remove? thanks!

See amended answer.

It looks like the this line in your setup:
  digitalWrite(11,LOW);

... would trigger contact input 211, and do "Start of Program Operation when D11 switches from off to on" every time the sketch starts.
If the arduino resets, it will pull this line low.  Autoreset would initiate this.
By changing the line to the following, the code will wait until it gets an 's' before pulling the line low.
  digitalWrite(11,HIGH);

I don't have an Arduino, but perhaps http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection may help in managing the Auto-Reset issue.

Hi Dave X, thanks, so what i need to do is to remove the digitalWrite (11,LOW) line on the code?

It defaults to LOW, so removing it won't do much. Set it to HIGH if that is what is required here.

Yes, what Nick said.

Sorry fo the confusion. Pin 11 is set to HIGH initially that is why when I unplugged the controller , the machine will suddenly turns ON. If i set it to low, machine will turn ON when i unplug then plugged my ports to PC.

Your code seems to set Pin 11 to LOW initially.

Yes that is actually HIGH (typo error).


text:
Unreliable function of transistor, pump and ESP32
I have a 12 VDC pump, 8.5A, connected to a MOSFET transistor PSMN5R6-100PS,127.
The connection from the transistor to transformer, pump and a ESP32:
1    Gate   --> port to ESP32
2    Drain  --> (-) pump
3    Source --> Gnd ESP32, (-) transformer
(+) transformer to (+) pump
This is, as I understand it, how it ought to work. But with this configuration it doesn't...
But changing 3    Source --> (-) transformer, removing the Gnd connection to the ESP32, then it works. It, however, seems to be some kind of leakage in terms of current because the pump has a "clucking" sound, not fully activating, just making a sound. Sometimes it doesn't work at all, where a reset makes it work again. Any ideas how I can fix it reliably?

That transistor has Vgs(th) typical 3V if I read the datasheet correctly. ESP is at 3.3V? Might not be enough

This is not a question about Arduino. 2) Removing the common GND connection from the transformer (-) to the ESP32 will almost certainly lead to problems. 3) My guess is your MOSFET does not fully conduct at the ESP32 port output voltage (3.3V). You need to increase the gate voltage. Did you add a flyback diode across the pump to protect the MOSFET?

(2) Yes, I suspected this...What kinds of problems could occur?  (3) Yes, this has been my hypothesis previously, especially when considering that when connecting this same transistor to LEDs the light intensity is significantly lower that if the LEDs are directly connected to the transformer. No flyback diod has been added. Would it be best to just look for another transistor with a lower requirement in terms of gate voltage? Any ideas?

As can be seen from the datasheet for the PSNB5R6 (Fig 7) at 3.3V the MOSFET is barely even beginning to switch on.
You need to select a more suitable MOSFET that switches on fully at a voltage well below 3.3V, such as the STP40NF04L.

Will purchase this transistor and will have a look if it works!

When you're looking at them, you may want to look at the "safe operating area."  I don't know if I was reading it correctly, but in the datasheet for your PSMN5R6-100PS, the graph seems to suggest that at continuous (DC) operation at 12V about 6 AMP would be maximum.  So even if it had been able to turn on fully, it's not clear that you'd be able to use it unless you were pulsing 8.5 amps to the pump.

Looks more like 9A to me on that graph.

I struck lines over it to double check just now.  Though, I don't see a way to insert an image into a comment.  As long as they're aware of this aspect to picking one out, I'm content.

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


text:
Need help figuring out the pinout of a seven segmented display
A friend of mine gave me a 2in. 4 digit seven segment display. But when I sat down and looked at it, I found it has 7 pins on one side and 5 on the other and no indicators of its pinout on it. The only information I could gleam from it was the (presumably its model number) which said "PARA LIGHT A-5V4G-12-U1 H H0615". I searched online for it but only found ambiguous information that didn't help me. I have a feeling this is a fairly easy question, if so: sorry I am a noob.

Do you have a 1k resistor and a DC power source handy?

Without an image of the display, I'll have to guess. With 12 pins in total, what you most likely have is: 8 pins for 7 segments and the decimal point, and 4 COMMON anodes or cathodes, a detail you will have to discover yourself. This process requires a power source that can safely light LEDs. A multimeter in diode test mode will do since theres usually about 2 V across the probes and some internal resistance, enough to light up the LEDs in the display, though they wont be very bright. I will try to list the minimum number of steps needed to determine the pinout using this method.

Using a multimeter set to diode test mode, place the red probe on any pin (though its good to start at the edges). Now lazily run (i.e. make contact) the black probe through the remaining pins. If the display is a common anode display, you should see the all the segments of a particular digit (not different digits) light up in sequence.
Else, keep running the black probe through the pins until any segment at all lights up. Hold the black probe on that pin that caused the segment to turn on. Now run the red probe through the other pins. If all the segments of a particular digit light up in sequence, this indicates a common cathode display.
Another possibility is that no segment lights up at all, despite steps 1 & 2. Substitute the red probe, where it is held steady, for the black probe. Run the red probe through the remaining pins. If all the segments of a particular digit light up, then the display is a common cathode display.
On the other hand, if no digit's segments light up sequentially while running the red probe through the pins, but at least one segment of any digit lights up, then hold the red probe steady on its current pin, and run the black probe instead through the other pins. If all the segments of a digit light up in sequence, then you have a common anode display.

Take note of the pin that was held constant, in any of the cases above.
Now that you know what kind of display you have, you now need to discover the pinout for the segments and common anodes/cathodes. Get paper and pen so you can label each pin with its function. Create a table with pin numbers in one column (pin 1 - 12) and the pin functions (which you will find out) in the second column.

This image shows the segment labels. During the testing above, one
probe (PROBE A) was held steady on one pin while the other (PROBE B)
was run through the other pins. This caused all the segments of a
digit to turn on. The pin connected steadily to PROBE A is the COMMON pin for
the digit whose segments lit up. So in your table, Pin xx = COMMON
for Digit yy.
To get the COMMON for other digits, move PROBE A to another pin and
run PROBE B through the other pins until another digit has all its
segments turned on in sequence. The pin connected to PROBE A is the
COMMON for that digit. Include this in your table. Repeat until you
have identified the COMMON for each digit.
Finally to get the segment pins A - G and DP, place PROBE A on any of the COMMONs you have in your table and run PROBE B through the other pins. Each time a segment lights up, the pin connected to PROBE B should be associated with that segment's label in your table. E.g. if segment C lights up when PROBE B is on pin 10, then the table should have something like pin 10 = C. Keep going until you have all the segment pins identified.

An ok answer, +1, except in first bullet you should mention (1) that if no LED lights up then try reversing red and black probes, and/or other pin combinations and (2) the LEDs won't be particularly bright using this method, and it may be necessary to reduce room light slightly

@jwpat7 ok...editing now...

Nice step by step how-to. +1


text:
How can I work with two devices that use the SPI protocol?
I'm working with a project in which I need to use an SD card module and an RFID antenna simultaneously. The devices that I'm using are the MFRC522 and the CATALEX SD Card Adapter. Both have SPI Protocol, and they're using the libraries MFRC522.h and SD.h.
This is the pin layout that I'm using:
/////// For RFID //////////
             Arduino
             Mega
  Signal     Pin
  ---------------------
  RST/Reset  5
  SPI SS     53 (CUSTOM)
  SPI MOSI   51
  SPI MISO   50
  SPI SCK    52

//////// For SD ///////////
             Arduino
             Mega
  Signal     Pin
  ----------------------
  SPI SS     49 (CUSTOM)
  SPI MOSI   51
  SPI MISO   50
  SPI SCK    52

As you can see the only line that they are not sharing is the Slave Select (aside from the RST pin of the RC522 module), so I believe that my wiring is correct.
I tried setting in LOW the chip select of the device that I wanted to use and in HIGH the one that I didn't. But this didn't work.
Any help you could provide would be appreciated! Thanks!

If that SD card adapter looks similar like the picture, I never could get it to work together with another SPI device.
What I used was a data logger shield for Arduino (with SD card slot and proto part, unused in my case), something like this: SD logger

That's the exact same SD adapter that I have. What I did was connecting the Vcc of the SD adapter to an specific pin, and whenever I want to use it I have to set a HIGH signal on it, and whenever I want to use the RFID reader I have to set a LOW signal. The only issue is that it might be dangerous for the device (SD adapter). I'm right?

I think you mean the Chip Select or Slave select to switch LOW when you want to use it. But maybe it helps if you add your sketch and scheme. The adapter contains a voltage regulator for 5->3.3V so that should cause not cause any harm. Switching Vcc too often might do, but I think you mean the CS or SS pin.

No, I did mean Vcc. Actually I'm powering the SD card with a digital pin that I switch when I want to use it.

Ok ... to preserve power? There might be better ways for that possibly. I don't know happens if you write, the function returns, while writing is not finished and you switch off the power. Check the power consumption when not in use, or otherwise check if it has a sleep mode. Or wait long enough to be sure there is no write active.l

I have a few of those in my parts box and I have left a little note with them that says "exlusive SPI" to remind myself. A search brings up this which seems to confirm it. The OP's solution of powering it on and off with a pin seems pretty smart to me - assuming it doesn't draw too much current from the output pin.
Update: I found this which suggests that powering the SD card adapter from an output pin is a bad idea. The card could be drawing more than the pins can reliably supply.


text:
Solution for simple multi-Arduino communication network (or alternative?)
I know similar question has already been discussed here but I could not get clear answer.
Here is the thing: I have one master device - Mega2560, and multiple (about 9 but could be expandedin future) I2C perfiferals - displays, that can have one of two possible I2C IDs - limitation by the manufacturer. As I can't connect and talk to them from a single I2C bus I chose to attach each two of them to a Mini-Pro's I2C pins and connect the 5 Mini-Pros to the master. The question is am I going to the right direction, and which connection would do the trick? I2C is obviously out of question, so the remaining are UART and SPI. UART would require some external hardware to cope with multiple outputs from the slaves, SPI would require additional pins from the master for chip select signal.
Data rates are not high - min 10-20 kbps.
I think the SPI offers better solution, but I'm no expert, what do you think?
Cheers!
Stefan

What distances are you wanting to communicate over?

very short - the modules are within 40cm of each other, actually they will be combined in a common box with single front panel.

SPI afaik is not good over bigger distances (> 1 meter). If you need many CS signals you always can use a multiplexer (like 74HC595N). I am not sure if it is 'normal' to have many SPI devices connected to one Arduino though.
Other solutions: I2C, but I don't have much experience with them. I heard about I2C expanders (MCP23017) that maybe are useful.
Also RF might be a possibility, also depending on the distance and most important speed (and latency).
In case for the Mega, it has 4 UARTs so that could maybe be used to spread the load.

I2C is not better over long distances. It is not designed even really to go through wires but be just between chips on a PCB.

@Majenko ... I removed the part about distance, thanks.

I would use i2c to drive them but unfortunately the OLED displays have hardcoded duplicated IDs I cannot connect them to a common i2c bus.

Thanks all for your answers.
I did some more research with the new info you provided and found my perfect solution: TCA9548A. That's a 1-to-8 port i2c multiplexer that will allow the master MEGA2560 to control up to 8 independent i2c buses, where I can connect my displays. The chip is dirt cheap here - 2 euro only, and it is available in the store.
Thanks again guys!

Please add this as comment or update to your question. Since it is not an answer, I had to flag it like that.

@MichelKeijzers For the distances involved I was going to suggest an I2C switch as one possible solution. This answer is an answer to the question - and there is nothing wrong with a user answering their own question.

@Majenko ... true ... I see it adds more than only a thank you. I retracted my flag (even upvoted it).

I would suggest using 485 communication though it will increase the hardware but you will be able to add upto 32 devices and also have greater communication distance.
You can use MAX485 IC or you can directly use TTL to 485 Module


text:
ColorPal Sensor
First off let me preface this my explaining my background. I am a mechanical engineering student and have some programming knowledge but it's limited. I'm trying to make a skittle sorter and I right now I'm working on the color identification part. I bought a ColorPal sensor for the project but I'm having trouble using it. I modified the demo a bit and it sort of works but not as well as I would like. Can someone please help me with my code or perhaps suggest an easier color sensor to use. Also I hope I paste my code correctly.
#include <SoftwareSerial.h>

#define sio      6           // ColorPAL connected to pin 6
#define unused   255         // Non-existant pin # for SoftwareSerial
#define sioBaud  4800

// Received RGB values from ColorPAL
int red;
int grn;
int blu;

// Set up two software serials on the same pin.
SoftwareSerial serin(sio, unused);
SoftwareSerial serout(unused, sio);

void setup() {

  delay(2000);

  Serial.begin(9600);
  reset();                    // Send reset to ColorPal
  serout.begin(sioBaud);
  pinMode(sio, OUTPUT);
  serout.print("=(00 $ m)!"); // Loop print values, see ColorPAL documentation
  serout.end();               // Discontinue serial port for transmitting
  pinMode(sio, INPUT);
  serin.begin(sioBaud);       // Set up serial port for receiving
}

void loop() {
  readData();
}

// Reset ColorPAL; see ColorPAL documentation for sequence
void reset() {
  delay(200);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  pinMode(sio, INPUT);
  while (digitalRead(sio) != HIGH);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  delay(80);
  pinMode(sio, INPUT);
  delay(200);
}

void readData() {
  char buffer[32];

  if (serin.available() > 0) {
    // Wait for a $ character, then read three 3 digit hex numbers
    buffer[0] = serin.read();
    if (buffer[0] == '$') {
      for (int i = 0; i < 9; i++) {
        while (serin.available() == 0);     // Wait for next input character
        buffer[i] = serin.read();
        //Serial.print(buffer[i]);
        if (buffer[i] == '$')               // Return early if $ character encountered
          return;
      }
      //Serial.println("");
      parseAndPrint(buffer);
      delay(10);
    }
  }
}

// Parse the hex data into integers
void parseAndPrint(char * data) {
  sscanf (data, "%3x%3x%3x", &red, &grn, &blu);  // Pull the R, G, and B values from the data string

  char buffer[48];                               // create a buffer
  //sprintf(buffer, "r = %4.4d    g = %4.4d    b = %4.4d", red, grn, blu);   //print the values into a buffer as formatted integers
  int sum = red + grn + blu;
  //Serial.println(sum);
  if (sum >= 120 && sum < 126) {
    Serial.println("Purple");
  }
  if (sum >=  238 && sum < 248) {
    Serial.println("Green");
  }
  if (sum >= 230 && sum < 235) {
    Serial.println("Red");
  }
  if (sum >=  330 && sum < 340) {
    Serial.println("Orange");
  }
  if (sum >=  420 && sum < 430) {
    Serial.println("Yellow");
  }
}

Sorry, I typed this on my phone so of course I misspelled things, how great.

Please edit your question (click "edit") and mark the code as code.  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.  Note, instead of “sort of works but not as well as I would like” say what it actually does and what you actually want.

Indeed, please say what is wrong with it. I can see a bug, but maybe it's nothing to do with the problem you're seeing.

You can't just sum the RGB values and expect to differentiate the colors.

Probably converting it to hue and then checking it's value will work much better. Did you try using red/green/blue sheets to check if the sensor works?

In parseAndPrint
You need to check the return value of sscanf to see if the function read the data.
The problem you are having is the difference between + and &.  The sensor is providing 3, 3 digit hex values (which should be sprintfed with %03x not %4.4d).  Adding these together isn't going to give you the write answer.  For instance $001001001 should give you a colour of r=1, g=1 and b=1.  If you add those together you get 3, but you really want 0x001 0x001 0x001.
You need to recalibrate you system and keep the three values separate and represent each colour by a minimum and max of those three colours and then check the value 3 values you receive are within the 3 ranges you have.
// Define a structure (could be a class) to hold the data
struct ColourData
{
    int redMin;
    int redMax;
    int grnMin;
    int grnMax;
    int bluMin;
    int bluMax;
    char Name[30];
    ColourData (int rm, int rx, int gm, int gx, int bm, int bx, char* name)
      : redMin(rm), redMax(rx)
      , grnMin(rm), grnMax(rx)
      , bluMin(bm), bluMax(bx)
    {
        sprint(Name, "%s", name);
    }
};

// Define an array containing the data
ColourData colours[MaxColours] = {ColourData(150, 200, 0, 20, 150, 200, "Purple")
                         , // Add some more

// The code to check the colours
for (int index = 0; index < MaxColours; ++index)
{
    if (  red >= colours[index].redMin && red <= colours[index].redMax
       && grn >= colours[index].grnMin && grn <= colours[index].grnMax
       && blu >= colours[index].bluMin && blu <= colours[index].bluMax)
    {
       Serial.println(colours[index].Name)
    }
}

authors: Вадим Бондарь


text:
Have I bricked my Arduino Uno? Problems with uploading to board
I can't upload sketches to my Arduino Uno.

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?

For those wondering, this isn't an actual question!
It's more of a reference question. The question itself is made quite broad on purpose. The answer however is greatly detailed and so can this question be used as a reference.

It's more of a reference question. Quite correct. See It's OK to Ask and Answer Your Own Questions.

@Nick_Gammon Yes. But I feel that you somehow should have noted it somewhere. At first sight I was (slightly) annoyed by the fact that the question was so broad and it seemed that you didn't have done any research. But when I saw your answer, it all made sense.
Also, (when you can) you shouldn't forget to accept your own answer, so that others who are trying to help don't start answering, looking into or commenting questions on this (which wouldn't really help you, as you did already find a rather good way to debug this problem).

Thanks for the feedback. I initially thought to post the question with a note that I was going to post my own answer, but then I saw the checkbox about "answer your own question" so I ticked that instead. As for accepting it, I'm not allowed to for 20 hours. It seemed a bit odd to me to accept your own answer, but certainly I can do that when I am permitted to. I asked a question on Meta Arduino What is a canonical question, exactly? to try to work out the correct procedure but got no responses.

@FuaZe and Nick Gammon: This seems great in general, the only suggestion I'd make would be to make the subject more suggestive of what the question and answer are really about. As it is, I think I might have been tempted to blow it off as too vague. Perhaps the title could be "How can I troubleshoot failed uploads?"

What do others think? "Troubleshoot failed uploads" sounds a bit bland to me. On the Arduino forum we often get people wondering if they have "bricked" their Arduino in the thread title, rather than the (possibly more accurate) title: "I am having trouble uploading".

Amended title to include "problems with uploading" in it.

I know this is an old question, but maybe you can still help me...I've been following your troubleshooting procedure since I can't get any sketches to upload to my board, and got as far as the loopback test. When I try to do open Serial Monitor, however, I get the error "Error opening serial port 'COM2'. (Port busy)" even though COM2 should be the correct port. Any suggestions?

Just solved it thanks to help on the Arduino forums; turns out this is a bug in the 1.6.8 version of the Arduino IDE, and reverting to 1.6.7 solved the problem right away.

Also try the product page FAQs.  My Arduino MKR Zero, wasn't a recognised usb device, and required a double pressing the reset button while plugged into my PC.

It probably isn't bricked
I've got quite a few Arduinos, and over the last few years have only ever "bricked" one, and I think that was by zapping it with static electricity. Unfortunately that particular one had a SMD (surface mounted) processor chip, so it isn't easy to try swapping it with another chip.
Stay calm, and try the following steps ...

Example board
An "Arduino Uno" is not just one thing that might fail. It has multiple major components, and possibly only one has failed (if any). See this reference photograph:

Major components are:

Atmega16U2 processor - this handles the interface to the USB connection
Atmega328P processor - this is the "main" processor which has your sketch on it
Voltage regulator - this converts incoming power from the power jack to 5 V
Power LED (green) - marked "On"
Indicator LED (yellow) marked "L" - connected via an op-amp to digital pin 13
Rx and Tx LEDs (yellow) - these indicate if the USB chip (Atmega16U2) is receiving or transmitting

Note that the Rx and Tx LEDs are not connected directly to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications via USB, not if you have something (like a GPS) plugged directly into digital pins 0 and 1.
Also note that since the "L" LED is connected via an op-amp, it may illuminate if pin 13 is set to an input in your sketch. This is normal. It doesn't mean that something is erroneously sending data.

Check the power
USB power

Plug the board into your computer with the USB cable and check that the green "On" LED lights up.
Use a multimeter and a couple of jumper leads to test between the 5V pin and the GND pin (arrowed at the bottom). You should get a reading of around 5.0 V (I got 5.04 V on mine).

(You can buy a cheap multimeter for around $10 if you don't have one, but you are better off getting a better one for around $50 - check all the electronics web sites and stores.)

Also test between the 3.3 V pin and the GND pin - you should get 3.3 V.

If you do not get 5 V with the USB cable plugged in make sure the other end is connected to your computer. Also try a different cable.
Power jack

If you are using, or planning to use, the power jack (marked "power in" on the photo) disconnect the USB, and plug in a power supply - which should be 7 to 12 V DC with positive on the center pin.
Measure the 5 V and 3.3 V pins as above. You should still see the same voltages on them.

If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is.

Check the power-on LED flash
If you have the Optiboot bootloader (the Uno normally ships with that) then if you press and release the Reset button, or unplug and plug the USB or power cable back in, the "L" LED should flash quickly 3 times. The "on" and "off" times are 50 ms each, the three flashes should be over within about 1/3 of a second.
If it doesn't, you may have a problem with the bootloader, or the main processor chip (Atmega328P).

Try uploading a sketch
Important: If you are having trouble uploading sketches remove any connected devices (like shields). Also remove jumper wires plugged into the board sockets. In particular, there should be nothing plugged into digital pins 0 and 1 (Rx and Tx) because that will interfere with communicating with the uploading computer.
Choose one of the simple example sketches (eg. Blink) and try to upload it. This is what you should see:

The "L" LED should flash 3 times. This is because the main chip is being reset by a command from the uploading process.
The "Rx" LED should flash quickly. This is the instructions from the uploading process trying to activate the bootloader.
The "Tx" LED should flash quickly. This is the processor acknowledging the uploaded data.

You may see the above, even if the uploading process fails. This could be because the wrong board type is selected.
If only the "Rx" LED flashes, it could be because of a problem with the bootloader, or the main processor chip (Atmega328P). Someone is knocking, but no-one is at home!
Check the board type
If the LEDs flash, but you get a message like this:
avrdude: stk500_recv(): programmer is not responding

Check the board type:

If you have the wrong board type selected it will probably send the wrong uploading instructions, and time-out or otherwise fail. If you are like me and have different boards lying around it is easy to forget that the last upload you did was for a different board type.
Check the comm port
If the LEDs don't flash at all, you may have the wrong comm port selected.
Check the comm port:

Try a different PC / Mac if possible
Try your Arduino on a different PC/Mac if you have one to hand. This can narrow down whether or not you have an issue with the particular computer you have plugged it into, or computers in general.
Do a loopback test

Disconnect all shields and other wires
Remove the board from the power
Connect a jumper wire from RESET to GND (orange wire in photo)
Connect a jumper wire from Rx to Tx (white wire in photo)

Wiring:

Plug in the USB cable, and start up a terminal program - such as the Terminal Monitor in the Arduino IDE. Type something and send it (eg. hit Enter in the Terminal Monitor).
Everything you type should be echoed back.

If everything is echoed back: That confirms you have the right comm port, the USB cable is OK and the USB interface chip (Atmega16U2) is probably OK.
If nothing is echoed back, check:

You have the correct comm port.
Try a different cable. Some cheap USB cables only have power wires and not data wires.
Check the device driver for the Arduino is installed. You probably don't need to do this if that board worked previously on this computer, but it can be worth doing if this is the first time you plugged this board into this computer.

Test the Atmega16U2 chip
If your board fails the loop-back test, and you are certain the USB cable is OK, then you can test the Atmega16U2 chip itself. There is an ICSP (In Circuit Serial Programming) header on the board, adjacent to the Atmega16U2 chip, and near the USB socket.
Disconnect the power first (unplug the USB cable and any power cable).
Then you can connect the ICSP header via 6 jumper wires to a known good Uno, as shown in the photo:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the Atmega16U2 chip is marked with a small white dot, near the "F" in "AREF". Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".
Connect up:
Good board         Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Double-check your wiring.
Then on the "known good" board install the "Atmega_Board_Detector" sketch as described on the Atmega bootloader programmer page. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Detector".
Once installed, open the serial monitor, set it to 115200 baud, and you should see something like this:
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x94 0x89
Processor = ATmega16U2
Flash memory size = 16384 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xCF
Clock calibration = 0x51
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 3000

Bootloader:

3000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
3010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
3020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xEE 0xC4 0x00 0x00
...
3FE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
3FF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD8 0x8C 0x70 0x6D 0xFE 0x1F 0xDC 0x38 0x82 0x1E 0xCE 0xAE 0x23 0xB2 0xE6 0xE7
Bootloader name: Arduino-dfu-usbserial-atmega16u2-Uno-Rev3

First 256 bytes of program memory:

0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
...

However if you get a message like this:
"Failed to enter programming mode. Double-check wiring!"

That would appear to indicate that your ATmega16U2 is not working.

Test the ATmega328P chip
Disconnect the power from the "known good" Arduino Uno and rewire the ICSP jumpers as per this photo, to connect them to the "main" processor on your Uno:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".
The wiring is the same as before, except you are connecting to the other ICSP header - the one at the end of the board, furthest from the USB socket.
Good board       Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Once connected, open the serial monitor, set it to 115200 baud, and you should see something like this:
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
...

MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
Bootloader name: optiboot_atmega328

First 256 bytes of program memory:

0: 0x0C 0x94 0x35 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
10: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
20: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
30: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
...

In this case it confirms that the main processor is working, and has the Optiboot bootloader on it.

Things you can fix
Failed voltage regulator
This isn't easy to replace, but it is only needed if you use the power jack. If you run from USB then it is not required. Alternatively you could arrange for a 4 to 5 V supply (eg. 3 x AA batteries) and connect them to the 5 V socket on the board directly.

Failed ATmega16U2 chip
This is only required for uploading sketches via the USB port, and serial debugging. It isn't particularly easy to replace because it is a SMD (surface mounted device). However you can manage without it.
You can upload sketches via the ICSP header, if you purchase a ICSP programming device.
Examples of such devices plugged into the ICSP socket:

(Those photos were taken of a Ruggeduino, but the concept is the same).

You can also get an FTDI cable, like this:

Connect it to your board's serial ports like this:

FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

Now you can upload sketches directly to the main processor, bypassing the USB chip.

You can also use my Atmega chip stand-alone programmer to upload .hex files - this lets you copy the .hex file for a sketch onto an SD card, and then program the board via the ICSP header.

Failed ATmega328P chip
The main processor can be replaced fairly easily if it is mounted in a socket. Get a replacement chip from somewhere like Adafruit for around $US 6. Alternatively, try eBay. Try to get a chip which has the Optiboot bootloader already on it, to save hassle.
Carefully prise the existing chip out of the socket, and install the new one, taking note of the location of pin 1. Pin 1 has a notch on the chip, and its correct orientation is noted on the first photo in this post with a yellow dot (closest to the edge of the board). You will probably need to straighten the legs slightly. Hold the chip by the ends and gently push down onto a flat surface, like a desk, until the are pushed inwards a bit. Try to not touch the metal pins, you may zap them with static electricity.

ATmega328P responds but has no bootloader
I have a sketch at Atmega bootloader programmer which will replace the Optiboot bootloader. The wiring is the same as for the chip detector sketch. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Programmer".
Install the sketch on your "known good" Uno, and connect it to the target board with the wiring shown earlier.

Open the Serial Monitor on your "good" Uno and you should see this:
Atmega chip programmer.
Written by Nick Gammon.
Version 1.35
Compiled on Jul  9 2015 at 15:06:58 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...

Type "U" for the Uno (Optiboot) loader.
Using Uno Optiboot 16 MHz loader.
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...

Type "G" to program the chip.
You should see:
Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Done.
Programming mode off.
Type 'C' when ready to continue with another chip ...

This takes about one second. Now the bootloader is installed.

Watchdog timer problems
The watchdog timer (off by default) can be configured to reset the processor after a certain time. The intention is to recover from a "hang" for a processor deployed in the field. However if the timer is set for a short period (like 16 ms) then the processor can reset again before the bootloader has a chance to do anything.
The symptoms are that you cannot upload any new sketches. Some modern bootloaders (like Optiboot) take steps to stop this problem as one of the first things they do. However others do not.
This can be difficult to recover from, because once the sketch runs, you have the problem of it resetting, and if you have the problem you can't replace the sketch. People often report that they have to burn a new bootloader to recover. However that is only because, as a side-effect, burning a bootloader erases the current sketch.
There is a way of recovering. Take these steps:

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting, and thus activating the watchdog timer
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
It should now upload OK - as the sketch which activated the watchdog timer never started.

Problems with the Mega2560 upload
I mention this here, even though this post is really targetting the Uno board, because it is quite common.
Some versions of the Mega2560 bootloader look for "!!!" in the incoming upload from the PC, and if they see that, drop into debugging mode. This causes the upload to fail.
Example code:
Serial.println ("Furnace overheating!!!");

Solutions:

Install a more recent bootloader. My "bootloader uploader" sketch mentioned earlier in this reply should install a bootloader that does not have that issue.

Or (more simply):

Do not use "!!!" in your sketch.

Problems uploading to the Leonardo / Micro / Esplora etc.
Boards with the ATmega32u4 as their main (and only) processor can be trickier to upload to. This is because the same chip has to handle uploads and also run your code.
There is a small window of opportunity, after the board is reset, when it looks for a new sketch to be uploaded. The technique for uploading to these boards is:

Compile your sketch without errors.
Start the upload
As soon as the IDE reports "Uploading" press and release the Reset button.

You only have a second or so to do this, before the old sketch starts running. Don't be discouraged if you have to repeat this process a couple of times. That is normal.

References

Solving problems with uploading programs to your Arduino
Sketch to detect Atmega chip types
GitHub site with chip detector / bootloader programmer
Atmega bootloader programmer
Atmega chip stand-alone programmer to upload .hex files
Engbedded Atmel AVR® Fuse Calculator
Arduino Uno Rev3 pinouts photo

Wow. This is a great great great answer

That is a wonderful answer sir.

"If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is." - why would this prevent you from uploading sketches?

You are quite right, it wouldn't. However the check-list was supposed to be a general check-list for failures. In this case it would be more like "I can upload a sketch, but when deployed in the field, with a power supply (wall-wart) it doesn't work".

I recently had a problem with the new FTDI drivers that "brick" chinese "FTDI compatible" (well you could say imitation) chips. They put the PID of the device to 0x0000, which will make the drivers invalid. You can choose to change the PID back with the M_PROG tool on FTDI or to change the drivers (and set up windows to allow unverified drivers).

I thought consumer outrage caused them to stop doing that?

@Nick Gammon I would have put after  "Check the comm port" to plug in the arduino on another computer running arduino IDE if that possible. If the arduino is detected and works on another different PC than it still ok. That may save time - if you have multiple PCs or can borrow one- rather than go through your long answer.

Good idea. I added that.

Excellent work, @Gammon. You answered a lot of questions I had not thought to ask. As for bricking boards, the only way I have done that is by having a Nano installed out at my solar panels inside a white box where the outside air temperature got above 100 F. That one never came back. But otherwise, the Nano seems to be very tolerant. So, I now have a small fan that turns on when the box's internal DHT-22 temp is above about 90. Haven't lost another board since.

What do you mean here "Note that the Rx and Tx LEDs are not connected directly to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications via USB, not if you have something (like a GPS) plugged directly into digital pins 0 and 1."? I have gsm/gps module connected to RX0 and RX1. It was working with module connected to arduino too, but once arduino command line start throwing:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
Errors

I suggest you post that as a new question. Comments under answers are not really intended for a question/answer session.

Fantastic answer, couldn't be more complete.

I tried the loopback test with my Arduino Nano. The TX/RX leds blink but nothing is printed in the serial monitor. Can you help me with that? Also I cannot upload anything.

About the "Problems uploading to the Leonardo / Micro / Esplora etc." part: I blocked an Arduino Micro by stupidly having a sketch calling cli() without matching sei(), which causes an "USB device not recognized" on the PC when connecting the USB port. The easiest way to recover the board in this situation is to connect an external programmer using ICSP and to re-burn the bootloader (which will erase the sketch). It probably also work to just upload a new sketch using the external programmer but I didn't try.

@LeFauve Did you try my suggestion of holding down Reset towards the end of my post?

@NickGammon Yes, I tried this first but there is less than one second between the moment I release the reset and the moment I get the "USB device not recognized" message. At this point, the Arduino IDE don't even see an Arduino on any port so it cannot upload anything to it.

At least - as I assume you upload your sketch via avrdude - please give more information about the upload failure (e.g. output of sketch uploader) so people here can help you better.
Additionally to the great answer of Nick Gammon, please search for exclamation marks in your sketch. If your sketch contains a string with more than or equal to 3 exclamation marks, the upload will fail, as old versions of the Arduino Bootloader will interpret these exclamation marks as another function and the upload will stop.
An example for stopping the upload:
char* test = "This will stop the upload!!!";

See Google Code issue.

Good point. This applies mainly to the Mega2560, but I admit I omitted that. :)

Added a section to deal with this issue.

I have bricked 2x ATMega328P on my Arduino Uno board due to static (I think).
The static seems to have killed the TX pin and hence the program can't be downloaded using the USB cable.
The easiest solution is to replace the microcontroller. You can buy a new ATMega328P DIP programmed with the Arduino bootloader (such as this one from Adafruit) and you are ready to go again.
Alternatively, you can still program the ATMega328P's by using the Atmel Ice or AVRISPmkII programmer or by using another Arduino as an ICSP programmer. When you do, all but the Tx pin work fine.


text:
Interfacing Arduino with matplotlib animation
I've also asked this question over on stack exchange so I'll link the actual question here.
The short story is I have a plot that updates in real time from data collected on an Arduino. The plot updates on a 50ms + overhead interval and I can either choose on the Arduino side to either delay the loop 50ms + compensation or use flush(). I'm running into some problems with the delay option where my program begins to lag (Python side). I'm wondering if flush will work as I expect and hold the output until my python program reads from the serial port. So then the Python program is completely controlling the flow of data every time it polls for an update.
Edit: Here's a snippet of the code.
void loop() {
  // put your main code here, to run repeatedly:
  val1 = analogRead(0);
  val2 = analogRead(1);
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  //Serial.flush();
  delay(50);
}

Please post a snippet of the Arduino side of the code. It should not send data faster than every 50 ms.

I edited my post to add the snippet

Thanks! You can test this: Reduce the update speed and verify the lag. When you get no lag. Increase the number of samples written. Typically python does not read the serial port directly. It goes through the operating system. There is also buffering going on in the python serial module and on top of that there is the garbage collector. You can help the python side by using a lower update rate but still keep the sample rate on the Arduino side.

What serial speed are you using - is 50ms enough time to transmit all the data?  If you're using slow serial, maybe just transferring the data is taking too long.

Uh... answered over there, copied below.

Please do not cross post questions as it leads to duplication or effort.  I have flagged the question on SE SO for deletion.

On the Arduino side, flush simply waits until the last byte has been fully transmitted.  It says nothing about how quickly it is being read by the PC.
The general problem you are having is called "flow control".  It has been solved with many different techniques, like "handshaking".  For example, the PC could send a character when it has received the last byte of a data set (a line, as returned by readline):
line = self.ser.readline()
self.ser.write("!"); // Tell Arduino line was received
line = line.split()

While the PC proceeds to parse the line, the Arduino will eventually receive the handshake character:
void loop()
{
  // Send a line
  Serial.println( ... );

  // Wait for handshake character
  bool gotHandshake;
  do {
    while (!Serial.available())
      ; // wait for chars
    char c = Serial.read();
    gotHandshake = (c == '!');
  } while (!gotHandshake);
}

Then the Arduino can proceed to send the next data set (i.e., a line).  The OS on the PC will buffer characters from the Arduino until the python program receives them with readline and sends another handshake character.  No delay required.