message:
Low-Pulse Occupancy and Voltage Divider

I have a PPD42NS dust sensor I'd like to hook up to an ESP8266-01 microcontroller. The ESP8266 uses 3.3v logic, but the PPD42NS uses 5v. The PPD42NS uses low pulse occupancy as output.

I'd like to use parts I have on hand, and I was wondering if a simple voltage divider built from 2 resistors can reliably shift the voltage without distorting the signal.

If not, could an NPN transistor do the job instead?

body:
While the PPD42NS has a 5-pin connector, it is shown at [seeedstudio.com](http://www.seeedstudio.com/wiki/Grove_-_Dust_Sensor) and [howmuchsnow.com](http://www.howmuchsnow.com/arduino/airquality/grovedust/) connected up with three wires: +5V, Ground, and an LPO or “Low Occupancy Output” signal, which goes low when a particle occludes an LED beam path.  LPO is used as an input to let sketches measure the fraction of time the beam's  occluded, which correlates with number of dust particles.

Yes, a resistive voltage divider will let you use the 0-to-5V occupancy signal as an input to your 3.3V-tolerant ESP8266.

What values of resistors should be used?  Because input pin capacitance is small (eg under 10 pF), signal "crispness" should be about the same over a broad range of resistances – say from a 100Ω+200Ω divider up past 1KΩ+2KΩ;  even 10KΩ+20KΩ might be ok.

The [Grove_-_Dust_sensor.pdf]( http://www.seeedstudio.com/wiki/images/4/4c/Grove_-_Dust_sensor.pdf) data sheet at seeedstudio.com says:

> Output Method  Negative Logic, Digital output,
Hi : over 4.0V(Rev.2) Lo : under 0.7V
(As Input impedance : 200kΩ) OP-Amp output, Pull-up resistor : 10kΩ

This suggests (but doesn't clearly indicate) that some sort of open-drain output might be used.  If so, instead of using a voltage divider one could remove the 10kΩ pull-up on the sensor, and pull the output to 3.3 V instead of 5 V, via either an external resistor or using an INPUT_PULLUP pinmode setting (if available on the ESP8266).

*Edit:* Regarding the comment, “I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?”:

The “max capacitance of 50 pF” spec, which is parameter D101 in table 2.1 of the MCP23017 spec sheet, refers to “Capacitive Loading Specs on Output Pins”, ie, how much capacitance MCP23017 outputs can drive.  It doesn't refer to input pin capacitance, so isn't relevant here.

In general, when a signal edge (a rise or fall) arrives at an input pin, the input pin's voltage doesn't change instantaneously.  The input pin's capacitance needs to charge or discharge.  (It charges for a rising edge, discharges for a falling edge.)  The speed of change depends on the RC time constant of the circuit.  A delay occurs, probably 1–3 time constants long, before the pin starts to switch.  (The switch may take a few tens or hundreds of nanoseconds.)

For example, if input circuit capacitance is 10 pF and its effective resistance is 100kΩ, RC = 10 pF · 100kΩ = 10⁻¹¹·10⁵ = 10⁻⁶ seconds = 1 microsecond.  Whether that's large enough to matter for your measurements depends on how many time constants have to occur before the pin starts switching, and on how narrow the LPO signals are.

In short, compute RC, and if it's more than a few microseconds, use a smaller value of R.  Alternately, if you have access to an oscilloscope, attach it to the input and try various resistance values in the voltage divider, to get a feel for how the signals degrade as the resistors in the divider get bigger.

Note, using a voltage divider causes different RC values for falling edges than for rising edges.  For example, suppose an actively driven 0-5V signal enters a divider with 10KΩ in series with 20KΩ, and the 0-3.3 V signal is taken from the resistors' junction.  Then R is 10KΩ for a rising edge, and 20KΩ for a falling edge.  If the 0-5V signal weren't actively driven high, but instead pulled up via a pullup resistor R' when a transistor turns off, then the rising edge R value would be R'+10KΩ for this example.


sender: user

message:
Arduino hangs on second GSM message (was GSM based led matrix display)

Friends, my team and I are working on a gsm based wireless display as a part of our project. We are using Arduino UNO as the microcontroller which is interfaced with a sim900 module. Upon arrival of a new sms in the gsm module, its contents will be passed on to the dot matrix led display through SoftwareSerial. We almost got the code working but the problem we now encounter is the reception of new sms. The code works fine for the first sms but to display the next new sms, we had to manually reset the Arduino every time. Can you guys help me? This is the code:

    #include <SoftwareSerial.h>
    #include <SPI.h>
    #include <DMD.h>
    #include <TimerOne.h>
    #include "SystemFont5x7.h"
    #include "Arial_black_16.h"

    #define DISPLAYS_ACROSS 1
    #define DISPLAYS_DOWN 1
    DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

    int temp=0,i=0,x=0,k=0;
    char str[160],msg[160];
    void ScanDMD()
    {
      dmd.scanDisplayBySPI();
    }

    SoftwareSerial SIM900(0, 1);

    void setup()
    {

       Timer1.initialize( 5000 );
       Timer1.attachInterrupt( ScanDMD );

       dmd.clearScreen( true );
       Serial.begin(9600);

       SIM900.begin(9600);
       void SIM900power();
       delay(20000);

         SIM900.print("AT+CMGF=1\r");
      delay(100);
      SIM900.print("AT+CNMI=2,2,0,0,0\r");
      delay(100);
    }

      void SIM900power()

    {
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
      delay(7000);
    }

    void loop(){
    for(unsigned int t=0;t<60000;t++){
      void serialEvent();
      if(temp==1)
      {
        x=0,k=0,temp=0;
        while(x<i)
        {
          while(str=='#')

          {
            x++;
            while(str!='*')

            {
              msg[k++]=str[x++];
            }
          }
          x++;
        }
       }
      }
         const char* dchars;
          dchars=msg;
         dmd.clearScreen( true );
       dmd.selectFont(Arial_Black_16);

      for(unsigned int i=0;i<=300;i++){
       dmd.drawMarquee(dchars,strlen(dchars),(32*DISPLAYS_ACROSS)-1,0);
       long start=millis();
       long timer=start;
       boolean ret=false;
       while(!ret){
         if ((timer+30) < millis()){
           ret=dmd.stepMarquee(-1,0);
           timer=millis();
         }
       }
     }
    }

    void serialEvent(){
      while(Serial.available())
      {
        char ch=(char)Serial.read();
        str[i++]=ch;
        if(ch == '*')
        {
          temp=1;
        }
      }
    }

The DMD library was found on the net.

sender: assistant

body:
Does nothing clear 'i' at the end of a message?  If not, then long/unexpected/multiple messages can overflow your str[160] buffer.

It also looks like writing to the msg[160] buffer isn't well protected from overflow.


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

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


message:
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?**

body:
That device ([datasheet](https://www.mpja.com/download/31227sc.pdf)) 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:

1. Increase the drive strength (especially the sink capacity) of the output
2. 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:

[![enter image description here][1]][1]

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.

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


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

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


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


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

  [1]: https://www.arduino.cc/en/Reference/PortManipulation


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

<!-- language: lang-c++ -->

    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.


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

[![no 52 pin connectors[![\]\[1\]][1]][1]][2]

  [1]: https://i.stack.imgur.com/Gqh7S.jpg
  [2]: https://i.stack.imgur.com/SRCjV.jpg

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


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

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


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


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

[![Uno layout][1]][1]

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

Here's the basic code that I presumed would make a sound, but no such luck.

<!-- language: c -->

    void setup() {}

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

Not sure where to begin debugging this...

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


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

<!-- language: c -->

    #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

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


body:
    // 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.


message:
How to access serial terminal through USBASP?

I have an [Arduino Pro Mini][1] 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?

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

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


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

 1. On the PC side, it uses a different software to capture the serial data from the `usbasp`.
 2. 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.
 3. The firmware of your `usbasp` programmer must be updated to the provided firmware using another programmer.

[![enter image description here][2]][2]

  [1]: http://community.atmel.com/projects/usbasp-tty-usbasp-programmer-modified-serial-support-and-terminal-program
  [2]: https://i.stack.imgur.com/elBcb.png


message:
Arduino IDE stopped uploading sketches to BLEduino board

I know similar questions to this have been asked before, but I have a "resp=0x**10**" 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][1]. 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:

[![enter image description here][2]][2]

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.

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board
  [2]: https://i.stack.imgur.com/1LkXg.jpg

body:
Looking at [this post about the uploading process](https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader) 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](https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board).

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.


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

body:
See my answer here: [Classes and objects: how many and which file types do I actually need to use them?](https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-do-i-actually-need-to-use-the) - specifically: [How the IDE organizes things](https://arduino.stackexchange.com/a/13182/10794).

> 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](http://forum.arduino.cc/index.php?topic=308853.msg2145054#msg2145054):

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


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

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

    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](https://github.com/sudar/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.


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

body:
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(",");
        }
      }


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

[![enter image description here][1]][1]

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

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


message:
How to access Attiny84 port B in Arduino IDE code?

Referring to guide at [High-low tech][1], 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);
    }

  [1]: http://highlowtech.org/?p=1695

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

[![ATtiny44/ATtiny84][1]][1]

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

Cheers!

  [1]: https://i.stack.imgur.com/7KtrR.png
  [2]: https://github.com/damellis/attiny/blob/master/variants/tiny14/pins_arduino.h#L33


body:
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`


message:
How to connect relay

![I want to control an LED using a relay..][1]
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

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

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

[![enter image description here][1]][1]

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.

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


body:
Wiring Diagram to Pin 13 for a single relay? This might help.
[![enter image description here][1]][1]

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


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


message:
Fritzing file for prototyping shield

I have a prototyping shield with mini breadboard similar to [Adafruit Proto Shield for Arduino Kit - Stackable Version R3](http://www.adafruit.com/products/2077).

Is there a Fritzing file for this.

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


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

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


body:
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][1] for a complete sample.

  [1]: https://www.arduino.cc/en/Tutorial/Genuino101CurieBLECallbackLED


body:
It's possible to using HC-05 with Intel 101.

I worked on the pin 0, 1, as the Serial1 class.


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

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


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


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

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


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

body:
There's two basic methods:

1. Provide a config.h file with the options in that the user modifies
2. 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.


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


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


message:
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)[![enter image description here][1]][1]

Do I have to solder a cable there to have access to 5V and GND? or there is another easier way?

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

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


body:
You can also use a Mega Screw Shield if you don't want to solder wires
[![enter image description here][1]][1]

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


message:
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][1].  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.

  [1]: http://forum.arduino.cc/index.php?topic=23025.0

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


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

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


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

body:
**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/][1]

  [1]: http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/

Hope this helps!


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

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


body:
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][1] 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.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP

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.


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

body:
There are two methods of doing what you want:

1. Add more ADC channels
2. 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.


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

[![Analog multiplexer][1]][1]

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](http://www.gammon.com.au/forum/?id=11976).

For 8 inputs the code is:

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

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

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


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


message:
Script on pc only gets 640 characters via serial

I experience that if the Arduino (Teensy 3.2) writes a rather long stream of characters to serial, the python script on the other end only receives the first 640 characters. I have found this result both by printing chars, printing lines and by using ArduinoJson's prettyPrintTo(Serial).

Note, that it does not matter what chunks of characters I read in the Python scripts, whether it is `read(5)` or `read(1000)`.

With the Arduino Serial Monitor, I get all the data, ie more than the 640 characters.

From what I can understand, it is not possible for a sketch to write "too fast" or "too much" to the serial, so there must be something on the pc side receiving the data. However, the Python script for some reason does not get all the data.

What is the problem here? Where should I look for the problem/solution? Perhaps this is more a Linux or Python question, but I will try here.

**Sketch - printLines()**

<!-- language: c -->

    void printLines() {
      for (int i=0; i<100; i++) {
        // length below is 40 incl end of line character
        Serial.printf("abcdefthijklmnopqrstuvxyz123456789--d\n", i);
      }
    }

    void setup() {
      Serial.begin(9600);
      delay(500);
      printLines();
      //printChars();
      //printJson();
    }

    void loop() {}

**Sketch - printChars()**

<!-- language: c -->

    void printLines() {
      for (int i=0; i<1000; i++) {
        Serial.write('x');
      }
    }

**Sketch - printJson()**

<!-- language: c -->

    void printJson() {
      StaticJsonBuffer<10000> jsonBuffer;
      JsonArray &root = jsonBuffer.createArray();
      for (int i=0; i<700; i++) {
        root.add(i);
      }
      root.prettyPrintTo(Serial);
    }

**Python script**

<!-- language: lang-py -->

    import serial

    ser = serial.Serial('/dev/ttyACM0')
    ser.timeout = 0.5

    # PARAMETERS:
    # (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
    num_chars = 100
    num_iterations = 10

    chars_read = 0
    for i in range(num_iterations):
        s = ser.read(num_chars)
        chars_read += len(s)
        print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
            % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))

**Terminal output**

    jan@jan:~/Desktop/batlogger/localserver$ sudo python localserver.py
    ### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
    ### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
    ### i: 2, reading 100 chars, char 200 to 299, len(s): 100, total chars: 300
    ### i: 3, reading 100 chars, char 300 to 399, len(s): 100, total chars: 400
    ### i: 4, reading 100 chars, char 400 to 499, len(s): 100, total chars: 500
    ### i: 5, reading 100 chars, char 500 to 599, len(s): 100, total chars: 600
    ### i: 6, reading 100 chars, char 600 to 699, len(s): 40, total chars: 640
    ### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 640
    ### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 640
    ### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 640

body:
I wouldn't be running as root. Why do that, just to execute a Python script?

Anyway, your problem is that you are not waiting for input. Your Python script is executing faster than the Arduino can pump out the bytes. At 9600 baud you send one byte every 1/960 of a second, so to send 4000 bytes (100 x 40) would take 4000 * 1/960 = 4.166 seconds. However your Python script powers along, getting the first 600 or so which may have been buffered already, and then finishes. You need to rewrite so you wait for a line to arrive. For example:

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

    import serial

    ser = serial.Serial('/dev/ttyACM0')

    while True:
      s = ser.readline()
      print (s)

When I ran that I saw all 100 lines.

Of course, you need to modify that to break out of the loop. Maybe a special character would do that. Typically a newline is used.

---

> PySerial's read function is blocking by default. - or it has a long timeout anyway

Not when I tested it. Using the code in the question, and without the Arduino even plugged in, I get:

    ### i: 0, reading 100 chars, char 0 to 99, len(s): 0, total chars: 0
    ### i: 1, reading 100 chars, char 100 to 199, len(s): 0, total chars: 0
    ### i: 2, reading 100 chars, char 200 to 299, len(s): 0, total chars: 0
    ### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 0
    ### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 0
    ### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 0
    ### i: 6, reading 100 chars, char 600 to 699, len(s): 0, total chars: 0
    ### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 0
    ### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 0
    ### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 0

Execution time: 5.5 s.

Of course, the code sets the timeout to 0.5s. But that isn't good enough. You can't assume that 400 bytes will arrive within 0.5s. They *should* if both sides are perfectly synchronized (at 9600 baud it would take 0.416s).

But serial doesn't work that way. You can't just read for 0.5s and hope everything you want arrives in that time. Heck, it may not have even started sending.

---

OK, I admit I tested with my Uno and not a Teensy, but this amended Python script shows similar results:

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

    import serial

    ser = serial.Serial('/dev/ttyACM2')
    ser.timeout = 0.5

    # PARAMETERS:
    # (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
    num_chars = 100
    num_iterations = 10

    chars_read = 0
    result = ""
    for i in range(num_iterations):
        s = ser.read(num_chars)
        result = result + str(s)
        chars_read += len(s)
        print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
            % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))
        print ("String = " + str (s))
        print ()

    print ("-" * 70)
    print ("Total output =")
    print (result)
    print ("Total length =", len (result))

Output:

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

    ### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
    String = b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'

    ### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
    String = b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'

    ### i: 2, reading 100 chars, char 200 to 299, len(s): 21, total chars: 221
    String = b'opqrstuvxyz123456789\xff'

    ### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 221
    String = b''

    ### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 221
    String = b''

    ### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 221
    String = b''

    ### i: 6, reading 100 chars, char 600 to 699, len(s): 100, total chars: 321
    String = b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'

    ### i: 7, reading 100 chars, char 700 to 799, len(s): 100, total chars: 421
    String = b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'

    ### i: 8, reading 100 chars, char 800 to 899, len(s): 100, total chars: 521
    String = b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'

    ### i: 9, reading 100 chars, char 900 to 999, len(s): 100, total chars: 621
    String = b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'

    ----------------------------------------------------------------------
    Total output =
    b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'b'opqrstuvxyz123456789\xff'b''b''b''b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'
    Total length = 669

----

Since the output of the Uno would be deterministic (it would do the same thing every time) the problem is in the way you are processing the data at the Python end. Look at the line numbers in the above list. They don't even start at 0.


body:
You are not using a serial connection, you are using a USB CDC/ACM connection, and that is a very very different thing.

With a serial connection when you send data it gets sent regardless of whether there is anything listening for it - the TX IO pin toggles high and low regardless.

However, with a CDC/ACM connection it's only possible to send data when there is something actively listening at the remote end - that is, when the port /dev/ttyACM0 has been opened by an application.

Until that port has been opened any data sent will remain in internal buffers.  These buffers are 64 bytes each in size (that's the size of a CDC/ACM packet), and there are (I would guess) 10 of them on the Teensy3.  After these buffers are full, because there is nothing receiving the data, there can never be any more room made for more data, so instead of blocking like a serial connection does it just discards the data.

So you have filled the buffers with 640 bytes of data and thrown away the rest.  That data just sits there.

Then eventually you open the /dev/ttyACM0 port and the Teensy3 is now able to send CDC/ACM packets through the USB.  And it has 10 of those packets sat there waiting to go out, so it sends them.  So you receive the 640 bytes of data that you had buffered up.

Your mistake is basically not waiting for the port to be opened before sending data to the remote end.  You can test the state of the port (kind of, but that's [a whole other subject](https://arduino.stackexchange.com/questions/20836/ifserial-not-working-correctly-on-micro-or-pro-micro/20839#20839)) by examining the Serial object:

    if (Serial) {
        // ... the port is open
    }

In general you can usually just wait at the start of your program before starting anything else with a simple while:

    while (!Serial); // Wait for the port to be opened


message:
Stepper motor doesn't start immediately when i pressed the button

When I release my hand from the button on pin 2, the stepper motor takes at least few seconds to stop, but I want it stop immediately. here's my codes:

<!-- language: c -->

     #include <Stepper.h>

        const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
        // for your motor

        // initialize the stepper library on pins 8 through 11:
        Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

        bool dir = false;
        bool power = true;

        void dir_pin() {
          if (!digitalRead(3)) {
            dir = !dir;
          }
        }//when the switch is being pressed
        //it condition would be different from last time

        void setup() {
          // set the speed at 60 rpm:
          myStepper.setSpeed(60);
          // initialize the serial port:
          Serial.begin(9600);
          pinMode(2, INPUT_PULLUP);//it is a easier way to using INPUT-PULLUP
          //cause you dont have to use a real resistor
          pinMode(3, INPUT_PULLUP);//why choose those two pins
          //cause for uno, the interrupt pin are pin 2 and pin 3
          attachInterrupt(digitalPinToInterrupt(3), dir_pin, FALLING);
          pinMode(A0, INPUT);
        }

        void loop() {
          int pwr = analogRead(A0) / 100;
          Serial.print("power:");
          Serial.print(power);
          Serial.print("  pwr:");
          Serial.print(pwr);
          Serial.print("  dir:");
          Serial.println(dir);
          while (digitalRead(2) == 0)
          {
            if (pwr) {
              myStepper.setSpeed(pwr);
              int pwr = analogRead(A0) / 100;

              if (dir) {
                //Serial.println("clockwise");
                myStepper.step(stepsPerRevolution);
                //delay(500);
              }
              // step one revolution in the other direction:
              else if (!dir) {
                //Serial.println("counterclockwise");
                myStepper.step(-stepsPerRevolution);
                //delay(500);
              }
            }
            else
            {
              myStepper.step(0);
            }
          }
          while (digitalRead(2) == 1)
          {
            pwr = 0;
            myStepper.step(0);
          }
          delay(10);
        }

body:
You tell it to move whole 200-step revolutions, so once it begins a revolution, it must continue.  At 60 RPM, that should be up to 1 full second after you open pin 2.   Depending on the analogRead(A0)/100, a full revolution could take much longer than 1 second -- maybe 5.86s to 6000s

If you want it to stop immediately, disregarding full revolutions, you could:

          stepsPerButtonpress = 1;

          ...

          if (dir) {
            //Serial.println("clockwise");
            myStepper.step(stepsPerButtonpress);
            //delay(500);
          }
          // step one revolution in the other direction:
          else if (!dir) {
            //Serial.println("counterclockwise");
            myStepper.step(-stepsPerButtonpress);
            //delay(500);
          }

Or you could reduce stepsPerRevolution to the fraction of steps you want to treat as a unit, and increase rpm proportionally.