text:
Unable to upload sketches after little oopsie (reversed input polarity)
So playing around with an arduino uno, I was powering it with a 12volt battery (putting power between Vin and Gnd) and I fat fingered the battery terminals, putting them in reverse (oops)
I see smoke coming out of the 5 volt regulator (the little 3 pin IC). I immediately pull out the battery thinking I've just bricked this thing.
After a minute or two I plug the battery in again (taking care to plug it in straight this time) and to my surprise it works, works pretty well. The last sketch I uploaded works perfectly fine.
I've been using the same thing for an hour or so. But now I wanted to upload another sketch and it doesn't upload. The voltages seem to be fine, I'm putting in 11.8 volts on Vin, there is 5.12 volts on 5v and 3.34 volts on 3v3
I thought there may be some problem with the voltage regulator, so I tried connecting it directly to the USB (powering it from USB) but still the same thing.
I find it intriguing that it works perfectly for everything except uploading new sketches, especially after such an explosive oopsie. Can any of you chaps deduce what the problem might be? I have a USBasp module so I can reburn the bootloader, but I doubt that's the problem.

You've blown the USB communications IC.  CH340/341 or FTDI or PLxxx or whatever.   Hook a USB-Serial adapter (uh, CH340/FTDI based, ironic, I know) to D0/D1 pins of Uno, also the ground lead to the Uno ground pin, and voila! you're back in business.   How do I know this?  I've done it twice... Different errors though, I'm not a complete idiot!)

The atmega328 that runs the sketch is fine, but the communication is broken somehow.  See the steps in https://arduino.stackexchange.com/a/13293/6628

Good find, I tried doing the serial test (shorting reset to gnd and then connecting tx to rx) and it seems to work fine (in that communication happens).
I'd deduce that the problem is happening between the USB controller (the little atmega chip) and the main controller (the atmega328). I'd have to search through the schematic to find it, but for now I've just uploaded the sketch directly, using ICSP.

Just remember that by programming using ISP you overwrite the bootloader, so you need to put that back when to determine if you fixed the board.


text:
Digital Input with long cable - flickering values
I have an Arduino Nano with two attached Motion sensors "PIXNOR HC-SR501". This sensor puts 5V on its middle Pin, when it detects motion. I have connected this Pin to my Arduino and read the value with digitalRead
Here is the simplified code of my loop:
void loop() {
    motion1 = digitalRead(motion_pin1);
    motion2 = digitalRead(motion_pin2);

    if(motion1== HIGH) {
      if(debug){
        Serial.println("Motion 1");
      }
    }
    if(motion2== HIGH) {
      if(debug){
        Serial.println("Motion 2");
      }
    }

    // Wait 1,0 Second
    Sleepy::loseSomeTime(1000);
  }

Problem is... This used to work fine, but I had to extend the cable to the motion sensors from ~10 cm to 500 cm. Now I have the problem, that the Arduino sometimes (quite often) detects voltage on the motion pins, although there is no motion. I guess the Input-pins are is too sensitive?
What can I do to prevent this flickering?

That device (datasheet) puts out 3.3V on the OUT pin, not 5V:

◦ TTL output: 3.3V, 0V

The excess cable is most likely picking up EMI and creating spurious pulses on the input. There are two basic ways of combating this:

Increase the drive strength (especially the sink capacity) of the output
Implement a balanced line communication system

You can combine both those quite easily, whilst at the same time boosting the output voltage to 5V using a 74HCT04 hex inverter chip (make sure it's the HCT variant).  Powered from 5V it will boost the logic level from 3.3V to 5V, and it will have a greater drive strength than the PIR chip alone.
Then the trick is to use multiple gates in the right way to make a crude balanced line system:

Basically you're double-inverting the signal so it remains the same logic level (high = high, low = low) but has higher drive strength, and you're also single-inverting the signal so it has inverted logic (high = low, low = high).  You then connect those to two different IO pins on the Arduino. Read both pins (instead of just one) and as long as the signal are opposite (Q = HIGH and !Q == LOW) then you have a valid signal. If both signals are HIGH then you have noise and you can ignore it.
You also need to ensure you select the right kind of cable. Ideally you need a cable with at least one twisted pair in it so that the Q and !Q signals are twined around each other. This ensures that if EMI is induced into the wire it's induced into both signals equally.  CAT5 Ethernet cable is often quite a good choice.

Thank you for this very detailled information and for pointing out my mistake with the 5V output of the sensor!

For implementing a balanced line, the MAX487 transceivers are quite cheap (less than 3 € apiece). You can feed a 3.3 V logic signal to the sending one (VIH(min) = 2.0 V) and you get 5 V on the receiving side.

Ouch, that's expensive. 74HCT04 can be purchased for just a few pence each in SMD, or a few tens of pence in DIP.

source: Stack Exchange

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

sort: votes


text:
Which is faster, Serial or DigitalWrite?
I am working on an Arduino Uno battle bot that uses a Sabertooth moter controller. Right now it is connected to the Arduino through Serial communication. Which is would be faster (So I can increase response time on my robot) Serial, or pwm using DigitalWrite?

I don't understand how you could substitute one for the other. Are you designing both ends? What sort of commands are you sending? Speed? Direction?

Using digitalWrite() is the slowest by far.
Using PWM could be the fastest.
Using Serial could be the fastest.
PWM:
You have to filter the PWM output to be a smooth analogue signal for it to be of any use. The filtering adds an inherent sluggishness, or response time, to the system - the harder the filtering the slower the reaction to changes in the PWM duty cycle. Adjusting the filter component's values will give an optimum point between smoothness and response time. Bear in mind that the motors may respond erratically if there is insufficient damping of the signal. This will probably give the Sabertooth a hard time, too. The datasheet recommends are filter response time of greater than 1ms.
Serial:
If you are considering the 2x 60Amp version (thanks for adding plenty of information in the question, by the way) then the fastest baud rate is 384kbps - or 48k commands per second. The Arduino will of course not be churning data continuously because it'll be busy running the rest of the program, but using serial it is theoretically possible to send commands faster than the motor controller's output PWM.
So which is faster?
No idea. Only you can determine this, and I doubt you'll be able to determine the answer without wasting your time on some experiments.
The motors will have an inherent mechanical dampening thus creating an overall bottleneck in the whole system response time. I can almost guarantee that both PWM and Serial methods will be much faster than the response time of the motors themselves.

The fastest would be “Simplified Serial Mode” at 38400 bps.
In this mode, a command is a single byte, transmitted as ten bits
(1 start + 8 data + 1 stop), which would take 0.26 ms to be transmitted.
Compare with the ≈ 1 ms lag you would get with an analog
filter. As per the data sheet, the caveats are:

resolution reduced to 7 bits
the communication may not be reliable at this fast speed.

Update: The fastest may actually be PWM, if you “cheat” a little bit
with the analog filter. The Sabertooth datasheet recommends

PWM frequency = 1 kHz
filter with 10 kΩ + 0.1 µF.

This gives a time constant RC = 1 ms, which is one PWM period.
You can then expect a worst case ripple of 1.22 V peak-to-peak.
The datasheet says you can increase the frequency or the capacitance
beyond those minimum recommended values. In both cases you would get
less ripple. But if we assume that this level of ripple is acceptable,
we can make things faster by decreasing both the PWM period and the
filter's time constant.
The trick is to configure the PWM output to run as fast as possible. The
outputs of the Uno can run as fast as 62.5 kHz at 8-bit resolution,
but for this we have to configure a timer using low-level port access,
instead of relying on the analogWrite() Arduino function. I would
rather avoid messing with Timer 0, because that would break all the
Arduino timing functions (millis(), micros(), delay() and
delayMicroseconds()). Here is an example program that uses Timer 2 to
output two PWM waveforms at 62.5 kHz on outputs 11 (aka OC2A) and 3
(aka OC2B):
void setup() {
    DDRB  |= _BV(PB3);    // OC2A = PB3 = Arduino 11 as output
    DDRD  |= _BV(PD3);    // OC2B = PD3 = Arduino  3 as output
    OCR2A  = 127;         // output A starts at 2.5 V
    OCR2B  = 127;         // same for output B
    TCCR2A = _BV(COM2A1)  // output A in non-inverting mode
           | _BV(COM2B1)  // same for B
           | _BV(WGM21)   // fast PWM
           | _BV(WGM20);  // ditto
    TCCR2B = _BV(CS20);   // clock with no prescaling
}

void loop() {
    // Full forward both motors.
    OCR2A  = 255;
    OCR2B  = 255;
    delay (1000);

    // Stop.
    OCR2A  = 127;
    OCR2B  = 127;
    delay (1000);
}

You could then smooth these outputs with an RC filter of
2.2 kΩ and 10 nF. That would give a time constant of
22 µs, longer than the PWM period which is 16 µs, and a
worst-case ripple of 0.9 V peak-to-peak.

pwm is faster.
PWM is directly to the port. Serial goers to a buffer is send char by char and the receiver needs to wait for all the data to arrive.

Both are (relatively) slow.  When speed is of the essence, use
port manipulation. This can execute a pin change as fast as a single clock cycle--faster than any library.

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


text:
Aurduino Mega prototype board connectors
Might someone shed some light on the 52 pin connectors on the end of the prototype board? Both boards have no 52 pin female connectors, the board that doesn't include the breadboard wire has a male connector that is not 52 pins. The female connectors are hard to find. I've only looked on Ebay.
Thanks
]2

I presume the pictured board has pins underneath (like an Arduino shield). It would be designed so you can stack more than one on top of each other.

Yes, the board is stackable. Not bad for 4.99.


text:
serial port on RPi
In the Arduino IDE on my RPi on the top there is a header that says, File, Edit, Tools and help.
Following a Magpi article it said to go to tools then serial port and change that depending on what board you use. The only problem is that it's not there, when I click tools I scroll down and there grayed out it says, serial port.
Why is this grayed out? And why can I not change it? Also, what port should be used for an Uno?

It's greyed out because it can't find any serial ports.
That could be because:

There aren't any detected (not got the right kernel modules loaded)
You don't have permission to access the serial ports (are you in the dialout group?)

Have you followed the Linux installation instructions? http://playground.arduino.cc/Linux/All

That would require RTFM :)
For the last many years (on various linux variants including rpi) a quick solution is:
sudo chmod ugo+rw /dev/ttyACM0

after plugging in the arduino.

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


text:
Piezo not making sound
I've used the piezo on other projects with no problem, but for some reason this project isn't working out so hot.
Here's a photo of my current set up.

Here's the basic code that I presumed would make a sound, but no such luck.
void setup() {}

void loop() {
  tone(12,260);
  delay(10);
}

Not sure where to begin debugging this...

I can't see any wires connecting to the Piezo.

@Majenko 2 and 6 on the breadboard connect to the piezo.

No they're not - they're on the wrong side of the board.

As Majenko pointed out, the wires are not connected to the piezo.  By moving the piezo to the correct rails on the other side of the board, the circuit would be completed and the piezo should work.
Edit:
Building on Nick Gammon's comment, the rows of each side of a breadboard are not connected (to allow DIP packages).

To explain a bit more: for each number abcde are interconnected, and so are fghij, but those pairs are not connected.

And the reason for this is: You can plug a chip into the middle of the board, one set of legs is on one side, and you can plug your breadboard wires into them, and the other set of legs is on the other side. If the sides were connected together, the chip wouldn't work.

Ah! Perfect. That did the trick. Thanks so much!


text:
DHT11 and Pulse sensor incompatibility?
I am working on an IoT project to send data acquired from DHT11 and PulseSensor to a website. I can send the data properly when I use each of sensors alone but when I write a wrapper to use both sensors simultaneously, DHT11 returns check-sum error. PulseSensor uses interrupt based on TIMER2 , whenever I remove interruptSetup(); from setup block the problem is solved but obviously the PulseSensor does not work in this case.
I searched inside the DHT11 library, as far as I could understand it does not use any Timer or interrupt to make a conflict with PulseSensor requirements.
This project use to serial port to communicate with PC for debugging and another one to communicate with ESP8266.
Please help me in finding a solution for this problem. Or guide me to websites that Arduino gurus track more :)
#include <SoftwareSerial.h>
#include <stdlib.h>
#include <dht.h>

dht DHT;
//DHT11 PIN
#define DHT11_PIN 5
// LED
int ledPin = 13;

// Heart_Sensor_Variables
int pulsePin = 0;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 10;                // pin to blink led at each beat

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

//ISR variables
volatile int rate[10];                    // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P =512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

//function Prototypes
void interruptSetup(void);

//Thingspeak API key
String apiKey = "REMOVED FOR SECURITY REASONS";

// connect 11 to TX of Serial USB
// connect 12 to RX of serial USB
SoftwareSerial ser(11, 12); // RX, TX

// this runs once
void setup() {
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);

  // enable debug serial
  Serial.begin(57600);
  // enable software serial
  ser.begin(57600);
  // reset ESP8266
  Serial.println("AT+RST");

  // sets up to read Pulse Sensor signal every 2mS
   interruptSetup();
}

// the loop
void loop() {
  // blink LED on board
  digitalWrite(ledPin, HIGH);
  delay(200);
  digitalWrite(ledPin, LOW);

//Read DH11 Data
  int chk = DHT.read11(DHT11_PIN);

// DISPLAY DATA
switch(chk) {
  case 0: ser.println("OK"); break;
  case -1: ser.println("Checksum error!"); break;
}

  ser.print(DHT.humidity, 1);
  ser.print(",\t");
  ser.println(DHT.temperature, 1);

if (QS == true){     // A Heartbeat Was Found
  ser.println("BPM and IBI have been Determined");
  ser.println(BPM, 1);
  ser.println(IBI, 1);

                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.

        QS = false;                      // reset the Quantified Self flag for next time
  }

  // TCP connection
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // api.thingspeak.com
  cmd += "\",80";
  Serial.println(cmd);
  delay(1000);

  if(Serial.find("Error")){
    ser.println("AT+CIPSTART error");
    return;
  }

  // prepare GET string
  String getStr = "GET /update?api_key=";
  getStr += apiKey;
  getStr +="&field1=";
  getStr += String(DHT.humidity);
  getStr +="&field2=";
  getStr += String(DHT.temperature);
  getStr +="&field3=";
  getStr += String(BPM);
  getStr +="&field4=";
  getStr += String(IBI);
  getStr += "\r\n\r\n";

  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  Serial.println(cmd);
 delay(500);
  if(Serial.find(">")){
    Serial.print(getStr);
  }
  else{
    Serial.println("AT+CIPCLOSE");
    // alert user
    ser.println("AT+CIPCLOSE");
  }

  // thingspeak needs 15 sec delay between updates
  delay(16000);
}

void interruptSetup(){
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

    //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3){       // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T){                        // T is the trough
      T = Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P){          // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
      digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
      IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if(secondBeat){                        // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for(int i=0; i<=9; i++){             // seed the running total to get a realisitic BPM at startup
          rate[i] = IBI;
        }
      }

      if(firstBeat){                         // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++){                // shift data in the rate array
        rate[i] = rate[i+1];                  // and drop the oldest IBI value
        runningTotal += rate[i];              // add up the 9 oldest IBI values
      }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true){   // when the values are going down, the beat is over
   digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }

  sei();                                   // enable interrupts when youre done!
}// end isr

The DHT requires some precise timing on its one-wire interface e.g. a >40us HIGH pulse == 1, while a <40us HIGH pulse == 0. Your DHT library doesnt use interrupts directly but it does use micros() which is based on regular interrupts, which are disabled automatically when you are within the TIMER2 ISR (no need for your explicit cli() and sei(), by the way). If you waste too much time in your ISR, you'll miss bits/pulses on the DHT line and obtain incorrect data, hence your checksum error.
The simplest solution I can think of is to disable the TIMER2 interrupt before the read11() call and enable it again after. I dont have much experience with AVR interrupts but I think this small change should do it:
#define TIM2_EN() (TIMSK2 = 0x02)
#define TIM2_DIS() (TIMSK2 = 0x00)

// your code as usual

void loop(){
  // ...as before...

  TIM2_DIS(); //Enable TIMER2 Interrupt

  //Read DH11 Data
  int chk = DHT.read11(DHT11_PIN);

  TIM2_EN(); //Disable TIMER2 Interrupt

 //...as before...
}

// your code as before

You are totally right. I applied your suggestion and it solved the problem. There is no more check-sum error after disabling TIMER2 interrupt.Thank you. By the way, Do you have any general methodology in your mind to avoid this kind of conflicts when installing several sensors? I mean is there any pattern to follow in writing flaw-less codes?

@PuyaAmiri The only way is to take care to understand the workings of the libraries you depend on, else some unknown detail will blindside u. Libraries for sensors that employ SPI may clash if they use different SPI modes for example. Or libraries for sensors that use SoftwareSerial will require u to listen() to each port in turns. Interrupts, as you've seen, can also be problematic in subtle ways. If you will be using a bunch of libraries written by others and not your own code, then its essential that u get at least some general understanding of how they work.

// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor

Interrupts are automatically disabled in an ISR.
Don't do lengthy things in an ISR (like analogRead). That takes 104 µs when an ISR should take only a few µs.

But when a kind of exact signal sampling is needed the first thing that comes to my mind is using a TIMER and writing corresponding ISR . So, you mean it is possible to use timer over flow flag out of ISR ?!


text:
How to access serial terminal through USBASP?
I have an Arduino Pro Mini that I use with a USBASP to program. These are actually a clone Pro Mini and a clone USBASP I'm using.
With this configuration, is it possible for me to access the serial port on the Arduino, through the USBASP, using the IDE serial terminal? If so, this would alleviate another connection to the computer for debugging. How to do this?

From the USBASP documentation:

Planned: serial interface to target (e.g. for debugging).

..and further on..

Firmware:
  The firmware dosn't support USB Suspend Mode. A bidirectional serial
  interface to slave exists in hardware but the firmware doesn't support it yet.

Keep in mind, that's from 2011, so it's possible someone has built an updated version of the firmware with that functionality. You'd have to do some searching (I'm not familiar with any such firmware).
For now, your best bet is just getting a TTL serial-USB converter (they're cheap) and connecting it directly to the Pro Mini.

I've searched in google and found a project in Atmel Community that supports serial with USBasp here. They called it USBASP-tty. I've not tested it yet but i think it will work. There are basically three requirements for it :

On the PC side, it uses a different software to capture the serial data from the usbasp.
It needs the conventionally bought usbasp programmers to have the two serial connections (image: PDO and PD1 connected with the ISCP header) to work. If those aren't already made, you have to rewire the pins. Normally these connections aren't made and the ICSP pins are connected to ground.
The firmware of your usbasp programmer must be updated to the provided firmware using another programmer.

Note that the LC Tech USBasp follows the schematic exactly and has the pins connected, but the Baite EvUSBasp does not.


text:
Arduino IDE stopped uploading sketches to BLEduino board
I know similar questions to this have been asked before, but I have a "resp=0x10" which I haven't found elsewhere, so maybe it's different, the board is also not an Arduino Uno although it's should be fully compatible with it in adition to the Bluetooth part.
I'm a beginner to Arduino (and electronics in general) and I bought a Bleduino board. It was working without problems, I've tested a servo and a DC motor (with a motors shield) without problems. But, it suddenly stopped working! I basically can't upload any sketch no matter what I try, giving me this error (10 attempts):
         Using Port                    : COM11
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x10

avrdude done.  Thank you.

I did try the reset button before uploading (actually tried both black and white reset buttons on this board), double checked I'm using the correct board and ports.
I've used an old 12V power supply with 1000mA, so maybe that damaged the main chip? The L and LINK LEDs light up though when connected to usb or jack, and the bluetooth also connects to the IOS App.
I read [this][3] thorough answer for similar problems and my board passes the loopback test, but while uploading, only the L and RX LEDs flash!
Have I damaged the main chip? Do I have to buy a AVR programmer and burn a new Bootloader?
Edit:
A screenshot of wiring to test the Atmega16U2chip:

ATmega328Pchip Response:
Atmega chip detector.
Written by Nick Gammon.
Version 1.18
Compiled on Apr 10 2016 at 10:30:58 with Arduino IDE 10607.
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 = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96
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
7E20: 0xC2 0x00 0x80 0xE1 0x80 0x93 0xC4 0x00 0x8E 0xE0 0xC9 0xD0 0x25 0x9A 0x86 0xE0
7E30: 0x20 0xE3 0x3C 0xEF 0x91 0xE0 0x30 0x93 0x85 0x00 0x20 0x93 0x84 0x00 0x96 0xBB
7E40: 0xB0 0x9B 0xFE 0xCF 0x1D 0x9A 0xA8 0x95 0x81 0x50 0xA9 0xF7 0xCC 0x24 0xDD 0x24
7E50: 0x88 0x24 0x83 0x94 0xB5 0xE0 0xAB 0x2E 0xA1 0xE1 0x9A 0x2E 0xF3 0xE0 0xBF 0x2E
7E60: 0xA2 0xD0 0x81 0x34 0x61 0xF4 0x9F 0xD0 0x08 0x2F 0xAF 0xD0 0x02 0x38 0x11 0xF0
7E70: 0x01 0x38 0x11 0xF4 0x84 0xE0 0x01 0xC0 0x83 0xE0 0x8D 0xD0 0x89 0xC0 0x82 0x34
7E80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7E90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EA0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EB0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EC0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7ED0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7F00: 0xA6 0x01 0xA0 0xE0 0xB1 0xE0 0x2C 0x91 0x30 0xE0 0x11 0x96 0x8C 0x91 0x11 0x97
7F10: 0x90 0xE0 0x98 0x2F 0x88 0x27 0x82 0x2B 0x93 0x2B 0x12 0x96 0xFA 0x01 0x0C 0x01
7F20: 0x87 0xBE 0xE8 0x95 0x11 0x24 0x4E 0x5F 0x5F 0x4F 0xF1 0xE0 0xA0 0x38 0xBF 0x07
7F30: 0x51 0xF7 0xF6 0x01 0xA7 0xBE 0xE8 0x95 0x07 0xB6 0x00 0xFC 0xFD 0xCF 0x97 0xBE
7F40: 0xE8 0x95 0x26 0xC0 0x84 0x37 0xB1 0xF4 0x2E 0xD0 0x2D 0xD0 0xF8 0x2E 0x2B 0xD0
7F50: 0x3C 0xD0 0xF6 0x01 0xEF 0x2C 0x8F 0x01 0x0F 0x5F 0x1F 0x4F 0x84 0x91 0x1B 0xD0
7F60: 0xEA 0x94 0xF8 0x01 0xC1 0xF7 0x08 0x94 0xC1 0x1C 0xD1 0x1C 0xFA 0x94 0xCF 0x0C
7F70: 0xD1 0x1C 0x0E 0xC0 0x85 0x37 0x39 0xF4 0x28 0xD0 0x8E 0xE1 0x0C 0xD0 0x85 0xE9
7F80: 0x0A 0xD0 0x8F 0xE0 0x7A 0xCF 0x81 0x35 0x11 0xF4 0x88 0xE0 0x18 0xD0 0x1D 0xD0
7F90: 0x80 0xE1 0x01 0xD0 0x65 0xCF 0x98 0x2F 0x80 0x91 0xC0 0x00 0x85 0xFF 0xFC 0xCF
7FA0: 0x90 0x93 0xC6 0x00 0x08 0x95 0x80 0x91 0xC0 0x00 0x87 0xFF 0xFC 0xCF 0x80 0x91
7FB0: 0xC0 0x00 0x84 0xFD 0x01 0xC0 0xA8 0x95 0x80 0x91 0xC6 0x00 0x08 0x95 0xE0 0xE6
7FC0: 0xF0 0xE0 0x98 0xE1 0x90 0x83 0x80 0x83 0x08 0x95 0xED 0xDF 0x80 0x32 0x19 0xF0
7FD0: 0x88 0xE0 0xF5 0xDF 0xFF 0xCF 0x84 0xE1 0xDE 0xCF 0x1F 0x93 0x18 0x2F 0xE3 0xDF
7FE0: 0x11 0x50 0xE9 0xF7 0xF2 0xDF 0x1F 0x91 0x08 0x95 0x80 0xE0 0xE8 0xDF 0xEE 0x27
7FF0: 0xFF 0x27 0x09 0x94 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x04 0x04

MD5 sum of bootloader = 0xEA 0x3C 0x5C 0xA9 0x35 0xD1 0x36 0xA6 0x71 0xD1 0xB2 0x3F 0x7E 0x62 0x79 0x6F
Bootloader MD5 sum not known.

First 256 bytes of program memory:

0: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
10: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x00 0x00 0x00 0x00 0x00 0x00 0x00
20: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
30: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
40: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
50: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
60: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
70: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
80: 0x10 0x20 0x40 0x80 0x01 0x02 0x04 0x08 0x10 0x20 0x01 0x02 0x04 0x08 0x10 0x20
90: 0x04 0x04 0x04 0x04 0x04 0x04 0x04 0x04 0x02 0x02 0x02 0x02 0x02 0x02 0x03 0x03
A0: 0x03 0x03 0x03 0x03 0x00 0x00 0x00 0x00 0x25 0x00 0x28 0x00 0x2B 0x00 0x00 0x00
B0: 0x00 0x00 0x24 0x00 0x27 0x00 0x2A 0x00 0x2A 0x01 0x7D 0x02 0x11 0x24 0x1F 0xBE
C0: 0xCF 0xEF 0xD8 0xE0 0xDE 0xBF 0xCD 0xBF 0x11 0xE0 0xA0 0xE0 0xB1 0xE0 0xE2 0xE0
D0: 0xF8 0xE0 0x02 0xC0 0x05 0x90 0x0D 0x92 0xA8 0x30 0xB1 0x07 0xD9 0xF7 0x21 0xE0
E0: 0xA8 0xE0 0xB1 0xE0 0x01 0xC0 0x1D 0x92 0xA7 0x31 0xB2 0x07 0xE1 0xF7 0x10 0xE0
F0: 0xCC 0xEB 0xD0 0xE0 0x04 0xC0 0x22 0x97 0xFE 0x01 0x0E 0x94 0xFB 0x03 0xC8 0x3B

Programming mode off.

Thank you Nick! I think I'll have to wait then till I buy an Arduino board and test with.

Looking at this post about the uploading process a response of 0x10 is STK_OK. Now while that looks fine, if the uploader is expecting STK_INSYNC then it's not OK.
I suggest you go through more of the steps in the link you posted.
You could use the "board detector" sketch mentioned on that page, to see if the main chip is completely gone, or if there is another issue. Other issues might be things plugged into D0 and D1, wrong baud rate, wrong clock rate, etc.

Hi again!,
I've an Arduino Uno and tested with and apparently I have a failed ATmega16U2 chip!

It seems odd to me that a failed chip makes any sort of response. You reported it responded STK_OK each time.

I followed your instructions about that chip testing and I got:
Atmega chip detector. Written by Nick Gammon. Version 1.18 Compiled on Apr  9 2016 at 23:55:08 with Arduino IDE 10607. Attempting to enter ICSP programming mode ...................................................... Failed to enter programming mode. Double-check wiring! Programming mode off.
And here's a screenshot of the wiring:
link

And here's what I got when testing the ATmega328P chip:
link

Google Drive: You need permission - how about editing your question and including relevant extra details in that, rather than an off-site link?

Yes sure I'll do that in few hours

I've edited the post. Please review.

A screenshot of wiring to test the Atmega16U2chip: Processor = ATmega328P - it's not a Atmega16U2chip is it?

I really don't know what's the difference, I'm new to this, but I wired to the pins beside the usb socket as you advised.

According to this page, it's the BLE firmware Burn http://www.elecfreaks.com/wiki/index.php?title=BLEDUINO

The schematic is a bit hard to read, but it doesn't look like it has a Atmega16U2 chip on it. it suddenly stopped working - sounds like you damaged something, but that chip looks OK, except that it has an unknown bootloader (not necessarily a bad thing).

So, what do you advise me to do? Would using an AVR programmer solve the problem?

Read the link about problems uploading. You may possibly be able to program the chip with an AVR programmer. I can't say for sure.

Nick, I'm sorry but I must say THANK YOU! I've been able to solve the problem using the "ATmega328P responds but has no bootloader" part of your fantastic post! I'm able to upload to BLEduino board once again :)


text:
Will a .ino Arduino Sketch compile directly on GCC-AVR?
Okay, we all have seen those questions all over the web such as Arduino v.s. C++, or other similar questions. And a vast majority of the answers do not even touch compilation differences other than through abstracted information.
My question aims to solve the actual differences (not preferences) in how a .ino file renamed to a .cpp file or other similar file extension for c++ would compile using GCC-AVR. I know that at a minimum you have to include the Arduino header file, but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR. For simplicity's sake, lets use the classic blink example to explain what the differences are. Or if you have a better code snippet to use, please by all means, include the snippet in your answer and explain the differences thoroughly.
Please no opinions as to which is a better way or tool to use.
FYI. I use Platformio for development and I notice a conversion process happening behind the scenes during compilation. I am tryng to understand what is actually happening there, so when I code in Arduino, I understand the "pure" C++ version as well.
Thanks for your thoughtful answers to my question in advance.

Are you asking specifically about gcc on your desktop, or the GCC for AVR compiler avr-gcc? there is a much bigger difference there than there is between a .ino and a .cpp file.

@BrettAM The GCC-AVR toolkit as the Arduino UNO is the target board and uses a Atmel AVR chip, as I am sure you know. Thanks for the call out to ambiguity in my question. And yes I know that there is a much bigger difference. That is why I am asking this question. To learn what those differences are!

See my answer here: Classes and objects: how many and which file types do I actually need to use them? - specifically: How the IDE organizes things.

I know that at a minimum you have to include the Arduino header file

Yes you would need to do that.

but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR.

The IDE generates function prototypes for you. Code in a .ino file may or may not need this (it probably will unless the author is disciplined enough to code in the usual C++ way and do them themselves).

If the "sketch" contains other files (eg. other .ino, .c or .cpp files) then these would need to be incorporated in the compile process as I describe in my answer mentioned above.
Also you would need to (compile and) link in any libraries used by the sketch.

You haven't asked about the linking side of things, but naturally the various files, as compiled, need to be linked together, and then turned into a .elf and .hex file for uploading purposes. See below.

Example makefile
Based on the IDE output I made a simple makefile a while back:
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

In that particular case, the .ino file compiled without any problems after renaming it to Blink.cpp and adding this line:
#include <Arduino.h>

Thank you Nick for your concise answer, I am nowhere near the level you are, and didn't even think about a make file. So basically the syntax is there same, it is just all about linking objects, right? Thank you for sharing your make file for me to dissect. I am sure there will be more questions arising from that! Thanks again!

My file above worked when I posted it, but I believe may need tweaking for the later IDEs (because they move around or rename library files). Still, doing a verbose compile shows what the IDE is currently generating, which should get you started.

I would just like to add a few points to Nick Gammon's answer:

You do not need to rename a .ino file in order to compile it: if you
explicitly tell the compiler it's C++ (option -x c++), it will
ignore the unusual file extension and compile it as C++.
You do not need to add #include <Arduino.h> in the .ino file: you
can tell the compiler to do that for you (-include Arduino.h).

Using those tricks, I can compile Blink.ino with no modification, just
by invoking avr-g++ with the proper command-line options:
avr-g++ -mmcu=atmega328p -DARDUINO=105 -DF_CPU=16000000L \
    -I/usr/share/arduino/hardware/arduino/cores/arduino \
    -I/usr/share/arduino/hardware/arduino/variants/standard \
    -Os -fno-exceptions -ffunction-sections -fdata-sections \
    -Wl,--gc-sections -g -Wall -Wextra \
    -x c++ -include Arduino.h \
    /usr/share/arduino/examples/01.Basics/Blink/Blink.ino \
    -x none /usr/local/lib/arduino/uno/libcore.a -lm \
    -o Blink.elf

A few notes on the above command-line:

/usr/local/lib/arduino/uno/libcore.a is where I saved the compiled
Arduino core. I hate recompiling over and over again the same stuff.
-x none is needed to tell the compiler to mind the file extensions
again. Without it, it would assume libcore.a is a C++ file.

I learned those tricks from Sudar Muthu's
Arduino-Makefile. This is a
very general Makefile that works with many boards and with libraries.
The only thing missing relative to the Arduino IDE is the forward
declarations.

Very nice, Edgar! My solution basically mimics what the IDE does, yours solves the actual problem to hand in a much neater way. Of course you would have to make the libcore.a file in advance. I suppose that the lines in my answer which build core.a could be done in advance, so they don't have to be part of each build. Experience has shown that more complex sketches (eg. using Wire or SPI) need more files to be added to core.a.

@NickGammon: That's right, Muthu's Makefile (and, I assume, the Arduino IDE) tends to put whatever libraries you use in libcore.a. I do not really like this approach, as it makes the supposedly “core library” dependent on the particular program you compile. For single-file libraries, like Wire or SPI, I prefer to just put the library C++ file in the same compile command as the main program. That command line gets easily quite long, so I use a Makefile.

One of the things I like about the IDE is that you don't have to muck around. For simple projects anyway, it "just works".

Hi! I'm trying to figure out how to save some space in a large Arduino sketch, and would like to inspect the generated object file. I'm not sure I understand all this business about pre-compiling libcore.a, however. Is there an ELI5 for obtaining/inspecting the compiled code in a form similar to that which the Arduino IDE would generate?

@MRule: Disassemble the final .elf with avr-objdump. There are a few answers here explaining how.

Brilliant! This worked; Looks like the generated instructions are pretty disappointing in some cases. I wonder if there is any way to get the compiler to use the SBRC/SBRS (skip if bit in register clear / set) instructions.


text:
int not declared in this scope
This posting contains 2 sketches. the analogmux1 compiles successfully. Concerning analogmuvvolts sketch an error stating updateMux1 was not declared in this scope results. The int Mux1_State [8] = 0: is defined exactly the same in both however the error results.
I'm learning Arduino programming so there are other errors in the sketch. What I'm trying to accomplish is to display the actual voltage of each channel, not numbers which appear in the analogMux.
It would be appreciated if the community could provide me with some guidance.
Analogmux:
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};

void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  //pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
  updateMux1();
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And  analogmuxvolts
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue);
}

Is updateMux1() not in the second sketch?

The error is updateMux1' was not declared in this scope and indeed that function is not in the second sketch.

Declare the updateMux() function by copying it from your first sketch into your second sketch:
void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And do the conversions on the stored Mux1_State[] values during printing like:
  for(int i = 0; i < 8; i ++) {
    Serial.println(Mux1_State[i]*5.0/1024.0);
    if(i == 7) {
       Serial.println();
    } else {
       Serial.print(",");
    }
  }

I appreciate your help Dave.    Tom


text:
Connecting SIM900A GSM/GPRS module Arduino Mega
I have bought the following SIM900A GSM/GPRS module. I need to connect it to an Arduino Mega. Can anyone answer me which pin I need to connect to the Arduino?

GSM modules works on serial protocol. You will have to connect Rx Tx of GSM to Tx Rx of arduino but before that try googling for Interfacing GSM with arduino. Also this question should be migrated to Arduino SE

hai, Thanks for your reply. actually i have tired in searching for the exact board data sheet. there is additional TTL RX,TX and ground can be seen next to the serial port. and there are six pins behind the serial port one set covered by green jack and other two by blue. most of the googling showed we have to remove those jacket to use this module with arduino. but those modules don't have the TTL pins which i have told earlier.

From your pic, it looks like the upper left corner has a jumper with TTL level TX, RX, GND.

hai, thanks. i am also thinking your way. but i am not sure whether it is right or wrong. but if i go for this way do i need to do any changes on the pins behind the serial port which are covered by green and blue jacks. which i mean do i need to remove the jacks..or else any kind of changes...??

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


text:
How to access Attiny84 port B in Arduino IDE code?
Referring to guide at High-low tech, I were able to flash ATTiny84 via UNO through Arduino IDE 1.6.7.
I loaded a simple blink LED program on IDE pin 0 (physical Attiny84 pin 13, PA0) and everything works fine for pin 0 till 7 at Port A.
But what if I want to access or blink a LED at one of the pins at Port B? Example, PB0 (physical pin 2)
The following is my current code to blink PA7
int led=7; //PA7

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
  delay(100);
  digitalWrite(led,LOW);
  delay(100);
}

Refer to url link by @Mikael, this is the answer I'm looking for.
Arduino IDE & Pin Mapping
// ATMEL ATTINY84 / ARDUINO
//
//                           +-\/-+
//                     VCC  1|    |14  GND
//             (D 10)  PB0  2|    |13  AREF (D  0)
//             (D  9)  PB1  3|    |12  PA1  (D  1)
//                     PB3  4|    |11  PA2  (D  2)
//  PWM  INT0  (D  8)  PB2  5|    |10  PA3  (D  3)
//  PWM        (D  7)  PA7  6|    |9   PA4  (D  4)
//  PWM        (D  6)  PA6  7|    |8   PA5  (D  5)        PWM
//                           +----+

IDE Attiny84 Physical Pin
  0      PA0           13
  1      PA1           12
  2      PA2           11
  3      PA3           10
  4      PA4            9
  5      PA5            8
  6      PA6            7
  7      PA7            6
  8      PB2            5
  9      PB1            3
 10      PB0            2

In order to blink PB0, I would need to replace my code with int led=2; //PB0

Should it not be:
int led=10; //PB0

According to the ATtiny web-page the pin/ports are numbered as below:

The physical pin 2 is the Arduino ATtiny core pin 10. You can also find this well documented in the pins_arduino.h file.
Cheers!

the picture is not what i looking for but the pins_arduino.h does help a lot


text:
How to connect relay

How to I connect the pins of one channel relay to control and led which is connected to pin 13 of an arduino uno.can you tell me the steps which pin will go to which pin

Unclear.  Do you mean to use the Arduino pin 13 LED signal to drive the relay?  Or some other LED to be controlled by the relay?

I insert an LED on pin 13 ....so I want to control that

You need no relay to control a LED.  Merely a resistor to limit the current.  See the 220 ohm resistor in series with the LED in the tutorial at https://www.arduino.cc/en/Tutorial/Blink -- they insert a LED in pin 13 in series with a resistor to Ground.

Are you asking which are the outputs and which are the inputs of the relay board?  Look at the bottom of the board and compare it to the datasheet of the relay: http://www.langir.com/pdf/pcb-relay-T73.pdf

But in my relay I don't have any sign like normal connection,command connection and all so I want to know which one is what

I modified my answer a bit -- you can look up the datasheet of the relay and follow the traces on the circuit board.  Us folks on the internet can't do that without better pics/diagrams.  Please be careful attaching your circuit to AC line currents.

Wiring Diagram to Pin 13 for a single relay? This might help.

I believe that the Arduino ground should be common with the 12v source ground. I may be wrong, though that's the way it works for me. Also be aware that some of these relay cards work when the pin is LOW, others when the pin is HIGH. Mine energises when the pin is HIGH, though all tutorials I had read until the last had the relay switching on with a LOW pin.

This relay has "Normally Open (NO)" and "Normally Closed (NC)" outputs. Applying voltage would "invert" these.

It looks like http://www.elesof.com/electronics/product/one_6v_spdt_relay_board  , http://shop.ciseco.co.uk/jqc-3f-t73-5v-pcb-relay/ and it probably works like http://www.electronics-tutorials.ws/blog/relay-switch-circuit.html
I'd bet that the I/P line connects to the center pin on the transistor through one of those resistors.    If so,  I'd put a 5V 100mA source on the GND +5 pins on the side, then I'd use a jumper from the +5 on the end to the I/P on the end, and see if it triggers the relay as expected.
If so, I'd siconnect the jumper and I'd connect the end terminal's GND to the arduino GND, and (maybe?) pin 13 to the I/P line and expect the Blink tutorial that blinks the Arduino's LED to click the relay in time.
If you are asking which are the outputs and which are the inputs of the relay board, I can't tell from the pictures. Look at the bottom of the board and compare it to the datasheet of the relay: http://langir.com/pdf/pcb-relay-T73.pdf  --

I'd bet that screw terminals are the outputs, connecting to the right hand pair of outputs, and the center of the left hand three inputs.   And that the  control terminals are the pin connectors, with the I/P conneting through the transistor to one end of the coil, with the other end of the coil going to the +5V/12V pin connector.  There are likely two sets of pin connectors to provide for a separate coil/relay supply on the GND,5V12V connector versus a signal or signal plus power on the GND,I/P,5V/12V pin connector.  I'd bet the same-named pin connectors are electrically identical.  i.e. GND=GND and 5V/12V=5V/12V.
If you are controlling other than low voltage devices with this, I suggest you make certain you are safe before applying potentially dangerous currents.

Of course I don't need a relay for led but if I want to control an AC bulb..and can you tell me which one is command,normal connection of relay on that image

Common is always in the center, facing the terminals NO will be on the left in most cases and NC on the right.


text:
Fritzing file for prototyping shield
I have a prototyping shield with mini breadboard similar to Adafruit Proto Shield for Arduino Kit - Stackable Version R3.
Is there a Fritzing file for this.

A quick google search turned up a solution in the very first result:
https://forums.adafruit.com/viewtopic.php?f=31&t=36560
It is a contribution from an Adafruit customer.
All credits go to them.
Source thread: https://forums.adafruit.com/viewtopic.php?f=31&t=36560


text:
How to receive data via Bluetooth on an Arduino 101?
The Arduino 101 came out recently, and it has built-in "Bluetooth Low Energy" capabilities. The tutorials and code examples that can be found for the 101 all seem to be about transmitting data, but I can't find anything about receiving data. I've tried to go through the source code of the CurieBle library to find some hints, but I feel a little overwhelmed/lost. Could someone point me to a code example which demonstrates how to do this?
Context: I was previously using an HC-05 module paired with an Arduino Nano in order to receive data. In this case it is quite easy to connect the HC-05 to the Nano's digital pins and receive data like so:
#define RxD 7 // This is the pin that the Bluetooth (BT_TX)
              // will transmit to the Arduino (RxD)
#define TxD 8 // This is the pin that the Bluetooth (BT_RX)
              // will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);

void setup() {
  blueToothSerial.begin(9600);
  Serial.begin(9600);
  // Allow Serial communication via USB cable to computer
  pinMode(RxD, INPUT);
  // Set up the Arduino to receive INPUT from the HC-05 on Digital Pin 7
  pinMode(TxD, OUTPUT);
  // Set up the Arduino to send OUTPUT to the HC-05 on Digital Pin 8
}

void loop() {
  char recvChar;
  while(1) {
    if(blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      Serial.print("Read character: ");
      Serial.println(recvChar);
      // Print the character received to the Serial Monitor
    }
  }
}

Is there equivalent, and equally simple, code available, which would do the same thing via the BLE built into the Arduino 101?

According to the Arduino Callback LED tutorial, you can use the dedicated library to access the BLE features of the board. All the Curie Libraries are covering the new Arduino/Genuino 101 embedded characteristics .
In your case you must incluse the CurieBLE.h and configure the bluetooth service with Read/Write access.
Have a look to this page for a complete sample.

It seems the 101 only supports Bluetooth LE stack and not the full Bluetooth stack including RFCOMM, virtual com port. This means there is no proper supported way, but it seems people are working on workarounds.
https://forum.arduino.cc/index.php?topic=370123.0

It's possible to using HC-05 with Intel 101.
I worked on the pin 0, 1, as the Serial1 class.

I don't understand what you are trying to say. Can you please elaborate.


text:
Baud rate Arduino/Linux
I'm trying to communicate some numbers between a Linux program and my Ardunino Uno. To this end I wrote a C++ program which somehow contains:
#include <stdio.h>

int a,b;
a = 1;
b = 2000;

File* serial = fopen("/dev/ttyACM0","w");
fprintf(serial,"%d,%d\n",a,b);
fclose(serial);

Now out of standards I guess, the baud rate is 9600 bit/s. If I use stty -F /dev/ttyACM0 115200 I can change the baude rate of that port to 115200 bit/s. However the communication does not work anymore. My arduino program waiting for number,number does not show any action to the same code as before. Oh, and in the Arduino program of course I changed the code to serial.begin(115200);.
How can I change the baude rate in such a setup? If it is a concern, I'm using Ubuntu and an Arduino Uno.

Also take into account that default settings may mean that opening the port resets the Arduino.  There will then typically be a brief delay before the bootloader hands over control to your sketch, so anything your program writes immediately after a port-open-reset will be lost and never seen by your sketch.  You can add a delay before writing your data or change the modem control signal settings to not trigger a reset (or at least not trigger one on subsequent port openings).  Even more reliable might be to open the port bidirectional and wait to receive a ready prompt from the sketch.

Thanks for the highly relevant hint! Could you maybe elaborate more on how the reset trigger is called? Or where I can disable it?
At the time beeing a bidirectional opening is more hasstle, than service, but I'll have it in mind for the future.

Actually, I tried it again with exactly the same settings and it worked. It seems, as if Linux uses the settings of ssty, when referring to the "file" of a serial connection.
Thanks anyway!

Settings do tend to persist.  You may want to reboot your system and see that it still works, and isn't only working because of settings set up by some program you ran during your experiments.  Programs that use the serial port are split in behavior - some leave their settings behind, others (at least on a normal exit) will set things back however they found them.  Also be aware that the necessary difference from bootup defaults may be more than baud rate - there is a lot about word format and character mapping and special casing to contemplate, too.

Thanks, using stty -F /dev/.. I tried to verify the baud rate after a reboot, but it is reset to 9600 baud. I didn't use any other related programs to change settings. So I guess I have to write a script to change the rate at bootup.

Setting baud rates in a C program isn't a trivial task. You need to use the low-level open() instead of fopen() and act on the returned file descriptor with ioctl() or tcsetattr() / tcgetattr().  The former method allows the setting of non-standard baud rates while the latter only allows specific baud rates to be used.
I wrote a C++ class to deal with it all for me a while back. You are welcome to examine the methodology and/or steal whatever bits of it you like to use in your own program.

https://github.com/majenkotech/SerialPort


text:
Arduino Mimicking Voltage Dividing Keypad / Matrix
Still very new to Arduino, so bare with me. I've been all over Google looking for ways to hack my alarm keypad. This is my first time using the Arduino to hack something  :smiley-confuse:
The keypad has a 13.7v input. Every other contact I can touch shows 5v or less. I realized quickly that the key buttons were producing various voltages. A quick search revealed that it was a voltage divider. I can see the resistors on the ladder. I though about mimicking the ladder via the Arduino and using a common ground.
I can see two shift resistors that say HEF4094BT. My guess is that these power the led's on the board.
I can also see a chip that reads KSL1 r1342 that I can't seem to find a datasheet on.
I have a few questions, but I guess I need to tell you my end goal. I want to make my keypad an IoT device. I want to be able to read the status of the alarm, and possibly mimick the keypresses to disable the alarm or activate it.
1st. I was thinking I could share a common ground, and read a led state for high/low. Like the "Armed" Led. Thought I'd ask the community before I go and short something  :(
2nd. How can I mimick the keypad's output voltages? Maybe a DAC? If so, what do you recommend?
Other Information: It's a DSC PC1550 - 6 zone alarm. (...and I'm also guessing the Rx/Tx are some DSC proprietary serial connection for security :/ )
Cheers,
Robert.

Also see “text a cell number if my dsc pc1550 home security system alarms”  and  “dsc keybus protocol” and “dsc keybus talk”

Wow! Following one link, to another via the comments led me to [link]https://github.com/dougkpowers/pc1550-interface which makes me feel even more hopeful! I might be able to skip hacking, and move directly to Interfacing! The article didn't really state whether I should connect the wires directly, or use resistors. I'm assuming that the 13.3v is regulated by the arduino, but I'm not sure about the clock and data pins? - thanks @jwpat7

@RobertCole The Arduino I/O pins can take only up to 20mA of current, and a MAXIMUM of 5.5v. But that is not normal operating condition. That is assuming you are using an Arduino Uno, but otherwise the ratings don't change much. Anyway, a simple woltage divider can solve your problem

Reading the leds would work. Depending on the voltage going out of the shift register, you might need to add a buffer chip, to lower the voltage.
For the keypad I'd probably go with a variable resistor, better known as a digital potentiometer.
You could probably add a way to also read the keypad, from the arduino. Which might be useful, maybe.

Glad to hear that  my common ground would work for the leds. But I can't see the logic in the buffer chip?
Digital potentiometer makes sense [link]https://www.sparkfun.com/products/10613
and then pulse various resistances in relation to the resistance of the keypad?

The leds might be supplied with 12v. Connecting this to the Arduino will break if. So in that case you need to convert the 12v signals to 5v signals, using a buffer chip, or some discrete circuitry. The the voltage is around 5v, I would at least put a resistor between the led and the Arduino. PS depending on how the led is wired (resistor 'before' or 'after' led) you might have to connect your wire to the associated resistor. The pot. you linked is what I meant. But you have to measure the resistance of the keypad (while powered off) to see if the 10k version is okay.


text:
Arduino configure script for conditional compilation of libraries
I have a library that uses conditional compilation based on the preprocessor variables. The library is a separate .cpp object file with a header file.
How can I pass preprocessor variables to the compilation of the library? Standard #define in a sketch file wouldn't work, since their life will be limited to my sketch object file(s), not the library's.
Normally it is solved by the ./configure script and/or the custom make process. How can I do it on Arduino?
Supplying a separate compilation/source code of the library for all 2^8 combinations of the preprocessor switches doesn't seem feasible...

The problem here is that the Arduino IDE is not setup for doing this. Any real IDE has the possibility to set defines.
If you want your library to be used by arduino IDE users you will have to go to dirty routes like the #include and config.h approach already mentioned.
If I'm not mistaken arduino IDE compiles libraries with the full include path so you can have the config.h next to your sketch.ino file.
If the library is not intended for arduino IDE users I would advice using a real IDE like my Arduino Eclipse Plugin.

I already use your excellent Eclipse Plugin. (I tested several other IDEs, but your proved to give me the best experience). But I'd prefer my library to compatible with the standard IDE if I had a choice. Setting the Eclipse with your plugin took me a half a day and two attempts... Not everyone will be able to do that.

V3 is comming. That should make it easy :-)

There's two basic methods:

Provide a config.h file with the options in that the user modifies
Place the options on the command line with -D

A decent IDE allows you to modify the compilation command line to add options.
My IDE, UECIDE, allows the creation of menu entries that set library options.

Ad 1. How to tell the library where is my config.h? When library's object file gets compiled, it doesn't know the location of my project's path. Or am I wrong?

The config.h is in the library. Depending on the IDE it may be possible to have it in the sketch folder and it'll find it there, but I am not sure what order of include paths the Arduino IDE uses.

Another solution: Rename the library's .cpp file into another .hpp, and let the user include it in exactly one object file of his.
User would configure the library in lib_customization.h included before every #include<lib.h>. User would also need to include an extra source file object_file_that_defines_lib.cpp which includes library definitions.
Sketch.ino:
#include"lib_customization.h"
#include<lib.h>

void loop() {}
void setup() {}

lib_customization.h:
#define LIB_INCLUDE_FEATURE_A
#define LIB_INCLUDE_FEATURE_B

object_file_that_defines_lib.cpp:
#include"lib_customization.h"
#include<lib_definitions.h>


text:
Shield board with holes, do I need to solder?
I have a motor shield.
I can put it on top of my arduino Mega and works perfect.
However, since the shield plugs in on top of the arduino board, I don't have access to 5V and GND from Arduino Mega.
I just have holes on the board with 5V and GND. (look at image)
Do I have to solder a cable there to have access to 5V and GND? or there is another easier way?

Since there are two grounds, a 2-pin terminal block of the type already on the board may fit. Or, since the shield doesn't obscure the far end of the Mega (the end with the high numbered I/Os), you could pick up 5V and Gnd there. The ends of the double-row female header have respectively, 2 each 5V and Gnd connectors. You would pick those up with breadboard wires, though it is admittedly less secure.

do you mean that the 2 female header after 52 and 53 are 5v and GND ? (on the bottom right corner of my image)

Below 52,53 are both ground. Above 22,23 are both 5V. It also written on the board.

... in tiny script! It's easy to miss.

It also looks like, to the right of the yellow square, are 3 rows of through-board holes. Labelled: +5V, Gnd, and A0 to A5. You could remove the shield temporarily, and solder on a couple of rows of sockets there, giving you 6 x +5V and 6 x Gnd connectors.

You can also use a Mega Screw Shield if you don't want to solder wires


text:
Unable to upload code on Arduino Nano
My Arduino Nano v3.0 (made by Gravitech US) is behaving in an unexpected manner. Whenever I try to upload a simple Blink program on the board it always give error which is shown below.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x01
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x01
...

I have another Nano (a Clone) and an Arduino UNO, both of which work perfectly using the same USB cable and PC.
History: When I used this Nano (original) for the first time, it was having some issue related to the FTDI chip. The FTDI USB was locking up on power up. I referred an answer from Arduino Nano 3.0: FTDI USB locks up on power up.  I shorted the pin no. 26 (TEST) and 25 (AGND) on the FTDI chip, and then I was able to use it. I uploaded the Blink program and tested it, which was working fine.
Now, at present (three years later), when I try to upload even a simple Blink example sketch on it, it never succeeds, and gives me the above mentioned error.
I also tried holding the reset button and releasing it when it shows

Uploading...

Another Issue: Sometimes when I just check the continuity on my Arduino Nano just to confirm whether the hardware is okay or not, it gives me unexpected results. On checking, the Pins RST and GND get shorted sometimes. And sometimes even VCC, RST and GND get shorted. I also checked the small reset switch on board, and it is working fine.
I contacted Gravitech, but they aren't responding.
What can be the issue with my arduino Nano? I haven't used it yet in any of my project. Just the Blink program that I uploaded 3 years ago on it, was the last time I saw it working.
Any help would be greatly appreciated.

Have you verified that the RST pin isn't shorting to ground when uploading?  (After the reset button is released, of course).

Select Tools>Processor>ATmega328p(old bootloader)
I was having the same problem. The default uploaded sketch was causing the problem. The code was reading one of the analog pins and throwing the value via serial port and causing the problem. Changing to old bootloader fixed it for me

good morning. this is a question from 2016. new bootloader for Nano was introduced this year with the Old bootloader option in IDE

Ow i didnt know this. I faced this problem recently and found this fix working for me so i shared. Cheers


text:
How can I test/demonstrate what the serial input and output buffers are?
Serial is causing me a lot of pain, and I think there are certain basic principles that I simple have not understood. I hope that by understanding how to test/demonstrate the buffer size, I will come one big step closer to understanding how serial works.
I suspect it is only possible to demonstrate this by writing a piece of software for "the other end"; the pc. I do understand Python, and to some extent how to work with serial on Python, so if possible, please write the pc code in Python.
If you supply an example (piece of code), please explain how the example works.

What example are you talking about?

Do you mean what causes me problems? A lot of stuff does :) Basically my lack of understanding of how the buffer behaves is what causes me problems. I think it must be ok on SE to ask a question like this, analogues to http://stackoverflow.com/questions/12791864/c-program-to-check-little-vs-big-endian. Please elaborate if I misunderstood your comment.

In your last line you ask how "the example" works. Do you mean the Arduino serial example sketch?

Now I understand. I have edited my answer to make clear what I meant. Thx.

On the Arduinos with 1000 bytes of RAM or more, the hardware serial input and output buffers are both 64 bytes. For devices with less RAM they are 16 bytes. This information is in the file HardwareSerial.h

See https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h and https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp for the actual implementation.

You can think of the incoming serial buffer as a bucket of water under a dripping tap. Next to the bucket is a cup.
Water arrives through the tap and drips into the bucket. When you want to get some water, if there is enough water in the bucket, you dip the cup in and remove a cupful of water. If there isn't enough water you don't get anything in your cup.
If you don't dip the cup in for a while too much water will dribble into the bucket and it will overflow all over the floor.
It's exactly the same with serial data. It arrives through the UART hardware and is placed into the "bucket" by the UART receive interrupt. If you don't dip your cup in fast enough (Serial.read()) the bucket will overflow and any new data that arrives will spill onto the metaphorical floor.
To test this out you can just send more data to the Arduino than will fit into the serial buffer (typically 64 bytes) without reading any. Then after you have finished flooding the buffer you can read what is actually in the buffer and send it back again (maybe formatted nicely) so you can see what has actually ended up in the buffer and what hasn't.
One quick and dirty test would be to send the raw bytes 0 to 255 to the Arduino, then after a delay read them back and display the DEC values for them (Serial.print(Serial.read(), DEC))) to see exactly which bytes arrived and which didn't (hint: you should see the numbers 0 to 63 if the buffer is 64 bytes big).

For the transmit buffer it's slightly different.  You can think of it more as a bucket with a small hole in the bottom.
You pour data (water) in the top at whatever speed you want, and it trickles out of the bottom at a pre-set rate (the baud rate - the size of the hole). You don't like wet messes though, so if the bucket is full you wait a while before putting more water into it. Just like with serial - if the transmit buffer is full any attempts to add to it will block until data has been sent out by the UART transmit interrupt.

How about a library like ArduinoJson, with the prettyPrintTo(Serial) command, how does it make sure that it does not write too fast to the serial?

It doesn't. It just writes to the serial object when the serial object allows it to.

What do you mean "allows it to"? Does ArduinoJson in some way query if it is allowed to?

The key word in my answer is the one in italics: blocking. That is it stops and waits until there is room.

Ok, so it is simply not possible to spill over when Arduino is writing. It just blocks if the buffer is full. I see it clearly in your answer now. Thanks.

That is correct. The buffer is emptied asynchronously using an interrupt, so the write function just uses a simple while loop to wait for room to be made for another character.


text:
String matching serial input (was Code for voice recognition for arduino uno)
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

void setup() {
  // put your setup code here, to run once:
  Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
   if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
delay(100);// prepare for next data ...
}

can anyone help me how to write the sketch for voice recognition of the    above code.
I'm using AMR/BT voice control app`for voice recognition.

Third time asking? Third new user? We don't have a clue what this "AMR/BT" thing is you're on about (or I certainly don't, and neither does Google, so there's no hope for anyone else).

Its an app. Voice recognition app. So i want to add speech recognition to my above code. And also I'm using bluetooth HC-05

How does the app work? What does it do? How does it interface with an Arduino?

Its there in the Google play store.. search for BT voice  control

No, I won't. You tell us, by enhancing your question, what it is, what it does, how you use it, and how you expect to use it.

It's a voice recognition app which we speak to the microphone. And then it will convert the voice into text and send it to arduino through bluetooth. so i want to above sketch to be controlled by voice.

So you want the arduino to be controlled by some unspecified stream of serial data? (that just happens to be generated on an app and delivered via bluetooth....)  What would the stream look like?  "Ari on"  "Ari off" ?

Yeah may be like Lights On , Lights off

... As far as the arduino would care, it sounds like it would all be serial dat, and the voice recognition is irrelevant.  What's the question? And what's with the "press 0 or 1..." do you mean "say 'zero' or 'one'..." ?

Inplace of pressing 1 0r 0 i want speech to text...which means i will give a command lights on or light off

If you tell us what your mystery app sends to the Arduino we can help you craft the code to interpret that data. Until you tell us that simple basic bit of information we cannot help you.

Alright...the app is like google tap/ google voice search

Put https://www.arduino.cc/en/Tutorial/SoftwareSerialExample on your arduino, hook up your bluetooth, talk to your app, and watch what it prints in the serial monitor.

Does http://arduino.stackexchange.com/a/3978/6628 help?

Forget it - an Arduino is neither capable of performing voice recognition itself, nor  a reasonable choice for collecting audio data on behalf of some remote compute service which is.

Please stop creating new accounts to ask the same question.

Your question is not very specific.
But, I think your talking about the AMR_Voice application for Android, and your trying to use the HC-05 BT to connect to your cell. I hope I'm right in my guess, and funny enough, someone over at Instructables did exactly the same thing.
Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/
Hope this helps!


text:
I can not upload hex files outside of the Arduino IDE to my Pro Micro
I have a strange problem. I am trying to upload a .hex file to my lovely Arduino Pro Micro, but am unable to do so. If I use the Arduino IDE, it goes through perfectly fine and uploads the sketch. However, if I try to use avrdude from the terminal I get:
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

My commandline is:
avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -t

and the full output is:
Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: leave prog mode
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: exit bootloader

Thank you for any help, it is greatly appreciated.
--Dominic

The programmer is wrong. You don't have avr109 bootloader, enable verbose upload from the IDE and copy-paste the command it used.

That is what I did. Also, the chip on my Arduino says "MEGA32u4" right on it...

Oops, I read it as Pro Mini not as Pro Micro.

Unlike the 328P and similar boards the 32U4 has no hardware method for triggering a reset to enter the bootloader.
On the boards with a UART -> USB interface the USB interface chip manually toggles the RESET pin to activate the bootloader. Without that chip a reset can't be done.
So a different method had to be invented. That method involves opening the serial port at 1200 baud and immediately closing it. That triggers a reboot into the bootloader.
The Arduino IDE manually performs that task when you press the upload button. It is not something that avrdude knows how to do.
So you will have to come up with some method of opening the serial port at 1200 baud immediately before running avrdude. Of course, it means the serial interface device disappears for a short while whilst the chip reboots and enters the bootloader, so you need to ensure you have a delay between the reset method and the call to avrdude - a delay that is long enough for your OS to redetect the chip, yet not so long that the bootloader times out.

Excellent! Thank you. I reset the board manually to test it, and I was able to upload my hex file normally.

I had this bizarre problem with my Leonardo and Uno boards. I was even using Arduino IDE (v1.8.5) to upload the code. In some extreme circumstances, one of the boards was not even listed under serial ports (Tools->Port)
After many attempts I simply burned bootloader using another Uno, and that solved the issue!
It is still unclear to me what happened but the issue was caused by an RFID card reader using SPI (ICSP pinouts on the board). The card reader (PN532) was sending data to Arduino when either I was uploading the code or the board was booting up.
UPDATE Jan 2020
After time and many attempts, I realised that Arduino UNO should not be accessed via ISP interface during code upload. The module PN532 was randomly massaging UNO when I flushed the microcontroller which corrupted the code.

What bootloader and what version(s)? There are several bootloaders. Can you elaborate? Did you use the official ones? Or Optiboot?

@PeterMortensen, I don't remember what bootloader was the most recent in 2017 but that was for sure the official version at that time available in Arduino IDE.


text:
Expanding analog inputs to the Arduino
I need the Arduino to read about 100 analog inputs. Is this even doable? If not what is the maximum analog inputs I can read into the Arduino (The maximum non trivially would be to use the analog pins that the board already provides).
But can I expand those out? Thanks!!

You know that to scan 100 inputs you will take a quite long time, don't you? Time means something around 10-20 ms for all the acquisition, but anyway you'll get a low sample rate

Could you tell use what you need it for? 100 analog inputs seems excessive. Having e.g. 100 sensors would probably also lead to other issues like power. There might be an easier way of accomplishing what you want without 100 analog input.

Reviving an old thread and violating etiquette, but I am looking for solutions as well and would be interested in seeing Frank Mcculling's code (if he's still around).

Use a bank of 8-channel ADCs with SPI interface.  Sample times can be much faster than the internal ADC. http://ww1.microchip.com/downloads/en/DeviceDoc/21298e.pdf  with 2 MHz clock, and 24 clocks to read and reply, a conversion can be done in 12 uS.  100 inputs can be done in just a few ms total then if you have good loop code to cycle thru 8 inputs on 13 chips.

about reading multiple temperature sensors with just 1 arduino pin use the DS18B20. They work in paralell.

Expanding on part of Majenko's answer, you can use an analog multiplexer like the 74HC4051 to turn one analog port into 8.

Its cousin, the 74HC4067, will multiplex 16 ports. Now with 6 analog inputs on the Arduino Uno, you could have 6 x 16 inputs = 96. The A/B/C controls signals could be paralleled up.
This would let you handle 96 inputs with only 6 extra chips, and pretty simple code. I have code examples on my page about 74HC4051 multiplexer / demultiplexer.
For 8 inputs the code is:
// Example of using the 74HC4051 multiplexer/demultiplexer

// Author: Nick Gammon
// Date:   14 March 2013

const byte sensor = A0;  // where the multiplexer in/out port is connected

// the multiplexer address select lines (A/B/C)
const byte addressA = 6; // low-order bit
const byte addressB = 5;
const byte addressC = 4; // high-order bit

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting multiplexer test ...");
  pinMode (addressA, OUTPUT);
  pinMode (addressB, OUTPUT);
  pinMode (addressC, OUTPUT);
  }  // end of setup

int readSensor (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
  // now read the sensor
  return analogRead (sensor);
  }  // end of readSensor

void loop ()
  {
  // show all 8 sensor readings
  for (byte i = 0; i < 7; i++)
    {
    Serial.print ("Sensor ");
    Serial.print (i);
    Serial.print (" reads: ");
    Serial.println (readSensor (i));
    }
  delay (1000);
  }  // end of loop

There are two methods of doing what you want:

Add more ADC channels
Multiplex the existing ADC channels

SPI or I2C ADC chips are readily available in a range of resolutions, sampling speeds and number of channels.  They are fairly simple to add to any Arduino.
For instance the MCP3208 will give 8 channels of 12-bit resolution on SPI, which means 3 pins (MOSI/MISO/SCK) + 1 per chip (SS). So 1 chip would be 4 pins, 2 chips 5 pins, 3 chips 6 pins, etc.
Adding lots of chips to the SPI bus though can itself be troublesome with the increased capacitance of all those inputs meaning you have to reduce your communication speed somewhat or add extra buffering to drive the bus with more current.
I2C chips can be harder to have lots of them since there are only a limited number of addresses on an I2C bus - plus on many Arduinos the I2C is also two of the analog pins, which you may not want to sacrifice.
The second option involves using analog multiplexers (eg the 4051) to switch different sources in to the existing analog inputs.
A third option which you probably haven't considered is to have multiple arduinos (or other low-cost microcontrollers) each doing some of the sampling and then implementing some kind of communication method between them (or to a single master). This has the added advantage that it's then possible to sample multiple channels at once (one per microcontroller) speeding up your operation somewhat.

I have been exactly working with the same Issue. I need a program that reads 100 Thermistors...Why? well, some times you need it.
I kinda finished that already.
I tried the 74HC4051 multiplexer / demultiplexer. But, for some reason I didn't get the desired result.
First thing you will find...POWER, you will need an external power supply, in my case I just made a voltage divider and connected the thermistor to that power, then just use the Analog port for reading...
I use I2C protocol, 8 arduino Mega 7 slaves and One master. and since send send Integer, float, and blah, blah was kinda not helping I just made it for It can send the Analog reading over I2C and the master makes all the desired conversion.
If you still are interested, I can send you the source code for master and slaves. With this template you can connect up to 50 arduinos and the master will look for every arduino connected in the network and ask for data.
Regards