message:
Stepper motor is not working according to code

#include <Stepper.h>
    #define STEPS_PER_MOTOR_REVOLUTION 32
    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 480  //2048
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
    int Steps2Take;
    int dirpin=8;
    int steppin=9;
    int buttonApin=2;
    int buttonBpin=3;

    void setup() {
      pinMode(dirpin,OUTPUT);
      pinMode(steppin,OUTPUT);
      pinMode(buttonApin,INPUT);
      pinMode(buttonBpin,INPUT);
    }

    void loop() {
      int valA=digitalRead(buttonApin);
      int valB=digitalRead(buttonBpin);
      if(valA==HIGH) {
        digitalWrite(steppin,HIGH);
        digitalWrite(dirpin,LOW);
        small_stepper.step(40000);
        delay(1000);
      }
      if(valB==HIGH) {
        digitalWrite(steppin,HIGH);
        digitalWrite(dirpin,LOW);
        small_stepper.step(-40000);
        delay(1000);
      }
      if((valA==LOW)&&(valB==LOW)) {
        digitalWrite(steppin,HIGH);
        digitalWrite(dirpin,LOW);
        small_stepper.step(0);
      }
    }

Here I have written this code to rotate stepper motor. When the input on digital pin 2 becomes high, then the motor should rotate clockwise. When the digital pin 3 becomes high, it should rotate in a different direction. When the input on both pins is low, the motor should not move.

But with this code the motor is moving continuously even if you apply high input to digital pins.

Please suggest how to fix this problem. For input signal I am taking signal from relays: if relay is in on condition, it should give a high signal and vice versa.

body:
Disclaimer: I've never used this library.  The following is my thoughts from looking at the code.

[This example][1] seems to do basically what you want.  It doesn't seem to be necessary to do any `digitalWrite`s yourself - you just need to call call `.step(x)`.

There also doesn't seem to be any need to anything in the "do nothing" case - you don't need to tell it not to step, as far as I can see.

I couldn't work out why you were stepping 40000 steps at a time.  I've changed it to 1.  You can change it back if I missed something.

Also note I've used `else if` so that if both inputs are high, the motor doesn't go forward AND backwards.  Maybe that's the behaviour you want, and if not, again, you can change it.

    #include <Stepper.h>
    #define STEPS_PER_MOTOR_REVOLUTION 32
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
    int buttonApin=2;
    int buttonBpin=3;

    void setup()
    {
        pinMode(buttonApin,INPUT);
        pinMode(buttonBpin,INPUT);
    }

    void loop()
    {
        int valA=digitalRead(buttonApin);
        int valB=digitalRead(buttonBpin);
        if(valA==HIGH)
        {
            small_stepper.step(1);
            delay(1000);
        }
        else if(valB==HIGH)
        {
            small_stepper.step(-1);
            delay(1000);
        }
    }

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


sender: user

sender: assistant

body:
Does the relay actually connect the pin to ground when it is off?  Or does it leave the input floating?  If it leaves it floating then you should use a pull-down resistor to make sure the pin actually sees ground and not stray interference.

If you can rewire the relays you can use an active low configuration and save the resistor since the Arduino has built-in pullup resistors.


body:
  I think its better to use count function .. you need to test yor stepepr motor first ..here the code to test .. i hope its will help :)

    #define IN1  50
    #define IN2  51
    #define IN3  52
    #define IN4  53
    int Steps = 4096; //4096(full rotation 360 degree )
    int cstep = 0;

    void setup()
    {
      Serial.begin(9600);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);

     Serial.println("Enter character for control option:");
     Serial.println("h : anticlockwise");
     Serial.println("i : clockwise");
     }

     void loop()
    {

       if (Serial.available()>0)
       switch(Serial.read())
     {
       case 'h':
       Serial.println("anticlockwise");
       for(int x=0;x<Steps;x++)
    {

         step1();
         delayMicroseconds(1000);
    }
      break;

       case 'i':
       Serial.println("clockwise");
         for(int x=0;x<Steps;x++)
       {

           step2();
           delayMicroseconds(900);
       }

       //delay(1000);
        break;

      }

      }

       void step1()
      {
        //stepp
        switch(cstep)
     {
       case 0:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     case 1:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, HIGH);
     break;
     case 2:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 3:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 4:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 5:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 6:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 7:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     default:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     }

     cstep=cstep+1;
     if(cstep==8)
      {cstep=0;}
     }

      void step2()
    {
    //stepp
    switch(cstep)
    {
     case 0:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     case 1:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     case 2:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 3:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 4:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 5:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 6:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 7:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, HIGH);
     break;
     default:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;

     }

      cstep=cstep+1;
     if(cstep==8)
     {
      cstep=0;
      //Serial.println("habis");

      }
     }


message:
Disable SCK temporarily to save power

for logging of environmental data, I am using a MicroSD card adapter (no brand name, eBay, China) and a 4GB Intenso SD card. I want to read data and write it to the SD card once every 10 minutes. Power consumption needs to be as low as possible.

Between the measurement points, I switch off the power supply to my sensor and SD card adapter using an NPN transistor (BC547B, 2N3904, 2SC945) and put my controller to sleep using [jeelib][1]. Everything works fine!

*But* I realized, that even during sleep, still 1mA of current is drawn. This disappears, when I remove the SCK connection between the Arduino and the SD controller. Doesn't sound like a lot, but for my purposes, it's a major concern (when SCK is removed, I'm around 6µA during sleep).

**Is it possible to switch the SCK signal off during sleep to save that last bit of power?**

In case it matters, I am using the SdFat library to write to SD. Initialization is done before each write. I figured, this would be necessary because of the poweroff of 10 minutes. Here's the function:

    #include <SdFat.h>
    const int chipSelect = 10;
    String outfilename = "Bienen.log";

[...]

    int writeToFile(String outfilename, String writestring) {

      SdFat SD;
      if (!SD.begin(chipSelect)) {
    #ifdef DEBUG
        Serial.println("Card failed, or not present");
        error_signal();
    #endif
      } else {
    #ifdef DEBUG
        Serial.println("card initialized.");
    #endif
      }

    File outfile = SD.open(outfilename.c_str(), FILE_WRITE);
    #ifdef DEBUG
      Serial.println(outfile);
    #endif
      if (outfile) {
        outfile.println(writestring);
        outfile.close();
    #ifdef DEBUG
        Serial.println("Wrote successfully.");
        ok_signal();
    #endif
        return 0;
      } else {
    #ifdef DEBUG
        Serial.println("Writing failed.");
        error_signal();
    #endif
        return 1;
      }
    }

ok_signal() and error_signal() are merely functions to flash an LED.

**EDIT:**
Thanks for your reply! I tried the code snippets

    SPCR &= ~_BV(SPE)
and

    SPCR |= _BV(SPE)

at the appropriate places, although I did not understand them. There was, however, no change in power consumption - SCK still seems to run.

I could not adapt the physical changes detailed in the suggested wordpress article, as the adapter there is quite different from [my microSD adapter][2], and I know too little about hardware to adapt the author's suggestions. It looks and sounds quite promising though ...

Thanks for your time! Any help is greatly appreciated!

  [1]: http://jeelabs.org/2011/12/13/developing-a-low-power-sketch/ "jeelib"
  [2]: http://robojax.com/products/images/ELE_SDCARDUI_176.jpg

body:
Re-visiting the issue, I have found a simple answer:

I set the SPI pins as outputs and inputs respectively:

    const int chipSelect = 10;
    const int MOSIPin = 11;
    const int MISOPin = 12;
    const int SCKPin = 13;

and

      pinMode(chipSelect, OUTPUT);
      pinMode(MOSIPin, OUTPUT);
      pinMode(MISOPin, INPUT);
      pinMode(SCKPin, OUTPUT);

Now, before I power down my machine, I do the following:

      SPI.end();
      digitalWrite(SCKPin, HIGH);
      digitalWrite(chipSelect, HIGH);
      digitalWrite(MOSIPin, HIGH);

Now, the drawn current drops from 1mA to roughly 0,02mA, which is satisfactoy for me!

Thanks for reading!


message:
Arduino to ESP8266 (SoftwareSerial) communication, does not receive full data

I have an Arduino Uno and an ESP8266, connected over serial through ESP8266 pin GPIO_2 (which is set as RX over espsoftwareserial) and 11 on Uno (which is set as TX over SoftwareSerial). I am trying to send data in this format:

 **<0.000000:0.000000:0.000000:0.000000:0.000000:0.000000:24.50:24.50:1.49>**

It is < char then number with six floats, separator :, and again... 9 times

I am using:

 - [espsoftwareserial library][1]
 - [Original SoftwareSerial library][2]

Arduino UNO code:

    SoftwareSerial ARD_ESP(10, 11); // RX, TX

    totalVolume[0] = 0.000000;
    totalVolume[1] = 0.000000;
    totalVolume[2] = 0.000000;
    flowRate[0] = 0.000000;
    flowRate[1] = 0.000000;
    flowRate[2] = 0.000000;
    float temperature_cold_value = 24.50;
    float temperature_hot_value = 24.50;
    float propane_gas_value = 1.49;

    void setup()
    {
       ARD_ESP.begin(57600);
       Serial.begin(9600);
    }
    void loop()
    {
    if (millis() - previousMillis_esp_post > 5000 && run_state_metering == 1)
         {
              ARD_ESP.print("<");
              ARD_ESP.print(totalVolume[0],6);
              ARD_ESP.print(":");
              ARD_ESP.print(totalVolume[1],6);
              ARD_ESP.print(":");
              ARD_ESP.print(totalVolume[2],6);
              ARD_ESP.print(":");
              ARD_ESP.print(flowRate[0],6);
              ARD_ESP.print(":");
              ARD_ESP.print(flowRate[1],6);
              ARD_ESP.print(":");
              ARD_ESP.print(flowRate[2],6);
              ARD_ESP.print(":");
              ARD_ESP.print(temperature_cold_value,2);
              ARD_ESP.print(":");
              ARD_ESP.print(temperature_hot_value,2);
              ARD_ESP.print(":");
              ARD_ESP.print(propane_gas_value,2);
              ARD_ESP.print(">");

              Serial.print("<");
              Serial.print(totalVolume[0],6);
              Serial.print(":");
              Serial.print(totalVolume[1],6);
              Serial.print(":");
              Serial.print(totalVolume[2],6);
              Serial.print(":");
              Serial.print(flowRate[0],6);
              Serial.print(":");
              Serial.print(flowRate[1],6);
              Serial.print(":");
              Serial.print(flowRate[2],6);
              Serial.print(":");
              Serial.print(temperature_cold_value,2);
              Serial.print(":");
              Serial.print(temperature_hot_value,2);
              Serial.print(":");
              Serial.print(propane_gas_value,2);
              Serial.print(">");
              Serial.print("");

              previousMillis_esp_post = millis();
         }

   ESP8266 code: (it's programmed with Arduino IDE)

    #include <ESP8266WiFi.h>
    #include <SoftwareSerial.h>
    #include <string.h>

    SoftwareSerial ARD_ESP(2, SW_SERIAL_UNUSED_PIN);

    const byte numChars = 32;
    char receivedChars[numChars];
    boolean newData = false;

    String sensor_1_total_volume;
    String sensor_2_total_volume;
    String sensor_1_flow_rate;
    String sensor_2_flow_rate;
    String temperature_cold_value;
    String temperature_hot_value;
    String propane_butane_gas_value;
    String mereni_token = "xxxxx";

    void setup() {

      Serial.begin(115200);
      ARD_ESP.begin(57600);
      delay(10);
    }

    void loop() {

      recvWithStartEndMarkers();
      showNewData();

      sensor_1_total_volume = getValue(receivedChars, ':', 0);
      sensor_2_total_volume = getValue(receivedChars, ':', 1);
      sensor_1_flow_rate = getValue(receivedChars, ':', 2);
      sensor_2_flow_rate = getValue(receivedChars, ':', 3);
      temperature_cold_value = getValue(receivedChars, ':', 4);
      temperature_hot_value = getValue(receivedChars, ':', 5);
      propane_butane_gas_value = getValue(receivedChars, ':', 6);

    }

    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (ARD_ESP.available() > 0 && newData == false) {
            rc = ARD_ESP.read();

            if (recvInProgress == true) {
                if (rc != endMarker) {
                    receivedChars[ndx] = rc;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars - 1;
                    }
                }
                else {
                    receivedChars[ndx] = '\0'; // terminate the string
                    recvInProgress = false;
                    ndx = 0;
                    newData = true;
                }
            }

            else if (rc == startMarker) {
                recvInProgress = true;
            }
        }
    }

    void showNewData() {
        if (newData == true) {
            Serial.print("This arrived: (unparsed)");
            Serial.println(receivedChars);
            Serial.println("DATA sensors: (parsed)");
            Serial.println(sensor_1_total_volume);
            Serial.println(sensor_2_total_volume);
            Serial.println(sensor_1_flow_rate);
            Serial.println(sensor_2_flow_rate);
            Serial.println(temperature_cold_value);
            Serial.println(temperature_hot_value);
            Serial.println(propane_butane_gas_value);
            Serial.println(mereni_token);
            newData = false;
        }
    }

    String getValue(String data, char separator, int index)
    {
        int found = 0;
        int strIndex[] = { 0, -1 };
        int maxIndex = data.length() - 1;

        for (int i = 0; i <= maxIndex && found <= index; i++) {
            if (data.charAt(i) == separator || i == maxIndex) {
                found++;
                strIndex[0] = strIndex[1] + 1;
                strIndex[1] = (i == maxIndex) ? i+1 : i;
            }
        }
        return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
    }

It works fine, but ESP receive only three values, another 6 does not.
I have tried to change bitrate to 57600, but thats not help.
I think that there is a problem with speed or waiting for full data.

Can you help me ? Many Thanks.

Here is the output from ESP:

    This arrived: (unparsed)0.000000:0.000000:0.000000:0.00
    DATA sensors: (parsed)
    0.000000
    0.000000
    0.000000
    0.004

    xxxx

  [1]: https://github.com/plerup/espsoftwareserial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialConstructor

body:
You are sending number+'.'+6 float +separator = 9 char at least.

You are sending 9x this, 81 char at least. Plus '<>' and maybe some more chars...

And you store it in 32 char long buffer. Somehow it does not fit all inside, who knows why?  :(

As you can see, you got like 32 chars only of the full transmission. Try to set `numChars` to something like 100 and try again. See, if it is better.

(Also I would use pattern

          ARD_ESP.print("<");
          Serial.print("<");
          ARD_ESP.print(totalVolume[0],6);
          Serial.print(totalVolume[0],6);
          ARD_ESP.print(":");
          Serial.print(":");

to leave the ESP more time to process stored data, but it is probabelly not problem now)


message:
Convert LIRC config file to Arduino IR remote command

I have a [LED 24 button remote][1] with a few broken buttons and I want to simulate all the buttons with an esp8266 using an [IR remote library][2].

  [1]: http://is.alicdn.com/img/pb/557/412/430/430412557_545.jpg
  [2]: https://github.com/markszabo/IRremoteESP8266

I would like to know if someone can help me translate the LIRC config file with all the functional buttons to an ESP lib command.
I have 2 lircd.conf files of the same remote (everything worked on a raspberry) and I'm using the same circuit on an ESP8266 (wemos d1 mini pin D5 and D6).

lircd.conf 1

    begin remote

      name  lumina
      bits           16
      flags SPACE_ENC|CONST_LENGTH
      eps            30
      aeps          100

      header       8860  4530
      one           508  1724
      zero          508   607
      ptrail        508
      repeat       8863  2301
      pre_data_bits   16
      pre_data       0xFF
      gap          107224
      toggle_bit_mask 0x0

          begin codes
              PWR_ON                   0xB04F
              PWR_OFF                  0xF807
              LI_LOW                   0xB847
              LI_HI                    0x906F
              R                        0x9867
              G                        0xD827
              B                        0x8877
              W                        0xA857
              R1                       0xE817
              R2                       0x02FD
              B4                       0xF00F
              G1                       0x48B7
              B1                       0x6897
              FLASH                    0xB24D
              STROBE                   0x00FF
              FADE                     0x58A7
              SMOOTH                   0x30CF
              G2                       0x32CD
              R3                       0x50AF
              R4                       0x38C7
              G3                       0x7887
              G4                       0x28D7
              B2                       0x20DF
              B3                       0x708F
          end codes

    end remote

lircd.conf 2

    begin remote

      name  lumina
      bits           16
      flags SPACE_ENC|CONST_LENGTH
      eps            30
      aeps          100

      header       8861  4525
      one           515  1718
      zero          515   600
      ptrail        516
      repeat       8865  2291
      pre_data_bits   16
      pre_data       0xFF
      gap          107235
      toggle_bit_mask 0x0

          begin codes
              B1                       0x6897
              PWR_ON                   0xB04F
              PWR_OFF                  0xF807
              LI_LOW                   0xB847
              LI_HI                    0x906F
              R                        0x9867
              G                        0xD827
              B                        0x8877
              W                        0xA857
              R1                       0x9867
          end codes

    end remote

Output from a few buttons read from the esp using the IRremoteESP8266 library .

    F0C41643
    4039382595
    Unknown encoding: F0C41643 (32 bits)
    Raw (68): 8850 -4550 550 -650 550 -650 550 -650 500 -650 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -1750 500 -1750 500 -1750 550 -1750 500 -1750 550 -1750 550 -1750 500 -1750 500 -650 500 -1750 550 -1750 550 -650 550 -650 500 -650 550 -650 550 -650 550 -1750 550 -650 500 -600 550 -1750 500 -1750 550 -1750 550 -1750 500
    ------------------

    A3C8EDDB
    2747854299
    Unknown encoding: A3C8EDDB (32 bits)
    Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -650 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -600 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -1750 550 -1750 550
    ------------------

    86B0E697
    2259740311
    Unknown encoding: 86B0E697 (32 bits)
    Raw (68): 8900 -4550 550 -600 550 -650 550 -650 550 -600 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -600 550 -1750 550 -1750 550 -600 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -600 550 -650 550 -1750 550 -1750 550 -1750 550
    ------------------

    A3C8EDDB
    2747854299
    Unknown encoding: A3C8EDDB (32 bits)
    Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -600 550 -650 500 -650 550 -600 550 -650 550 -1750 550 -1750 500 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -650 500 -650 550 -1750 550 -650 500 -1750 550 -650 550 -1750 550 -1750 550 -1750 500

body: Looks like is just plain NEC IR protocol. So use something like `irsend.sendNEC(0xB04F, 16)` for POWER_ON.


message:
How can I make this button toggle the position of a servo?

I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo

    // variables will change:
    int pos = 0; // variable to store the servo position
    int buttonState = 0; // variable for reading the pushbutton status
    int button_mode = 1; // Variable for the button's current state.
    // button_mode = 1 when the button is up, and 0 when the button is pressed.
    // This variable is 'static' and persists because it is declared outside a function.

    void setup() {
      myservo.attach(8); // attaches the servo on pin 9 to the servo object
      Serial.begin(9600); // Initialize the Serial port at 9600 baud.
      pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
    }

    void loop() {
      buttonState = digitalRead(9);
      if ((digitalRead(9) == LOW) && (button_mode == 1)) {
        // Check Digital pin 9 to see if it's pressed.
        pos = 150; //set servo position variable to 150
        myservo.write(pos); //set servo postion to 'pos'
        delay(1000); // wait 1 second
        button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
        Serial.println("Button has been pressed."); // and report that to the serial monitor.
      } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
        pos = 50;
        myservo.write(pos);
        delay(1000);
        button_mode = 1; // Button was down before, but is released now. Set the button to
        Serial.println("Button has been released"); // released and report that to the serial monitor.
      }
      delay(100); //small delay to account for button bounce
    }

body:
Do something like this:

    int angles[2] = {0,180}
    bool state = 0;

then:

    if(button == PRESSED)
      state = !state;

finnally, to control the servo:

    Servo.write(angles[state]);


body:
The code is not well structured. Here is what I would do:

    if (button_pressed()) { //test to see if button is pressed
      button_state +=1; //increment button
      if (button_stat & 0x01) {//if lsb set
        myservo.write(SERVO_POS1); //set servo position 1
      } else {
        myservo.write(SERVO_POS2); //set servo position 2
      }
    }

You can debounce if you wish in button_pressed().


message:
Serial.print start prints unreadable character without any reason

I wrote the following code. The idea is to execute some AT command on my ESP-01 module. The problem is that first command is execute without problem, the second sometimes but the reply on AT+GMR is the following:
    AT

    OK
    AT+GMR

    AT version:1.1/0.0(May 11 3016 18:09:57)
    SDK version:1.5.ar.0
    AR)�WS�TZ�j
    C�j�L�AZCA�O�C�

    FINE

The problem is that, after some thing that I don't understand, the formatting (maybe the baud change?) gone wrong. Then the reply of the following commands became unreadable. Any idea why it happens?

    #include <SoftwareSerial.h>
    #define DEBUG true
    SoftwareSerial wifi(2,3);

    void setup() {
       Serial.begin(115200);
       wifi.begin(115200);
       sendCommand("AT\r\n", 2000);
       sendCommand("AT+GMR\r\n",2000);
       sendCommand("AT+CWMODE=2\r\n", 2000);
       sendCommand("AT\r\n", 2000);
       Serial.print("\n\nFINE");
    }

    void loop() {}

    String sendCommand(String cmd, int timeout){
       wifi.print(cmd);
       return readSerial(timeout);
     }

     String readSerial(int timeout){
       long int time = millis();
       String res = "";
       while( (time+timeout) > millis() ){
            while(wifi.available()){
              char c = wifi.read();
               res += c;
            }
        }
        if(DEBUG)
           Serial.print(res);

        return res;
     }

body: The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.


body:
[![ esp connections][1]][1]

Take a look at the connections check the all the connections properly i also had the same problem

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


message:
Qduino Mini bricked?

So I have been experimenting with keyboard inputs and I think I may have accidentally put a loop in my code that never actually ends the keyboard input thus not allowing me to upload any sketches to fix the problem.

Here is the error code I got when I tried to upload a blank into the qduino:

    Arduino: 1.8.1 (Windows Store 1.8.1.0) (Windows 10), Board: "Qduino Mini"

    Build options changed, rebuilding all
    Sketch uses 4136 bytes (14%) of program storage space. Maximum is 28672 bytes.
    Global variables use 148 bytes (5%) of dynamic memory, leaving 2412 bytes for local variables. Maximum is 2560 bytes.
    An error occurred while uploading the sketch
    processing.app.SerialException: Error opening serial port 'COM11'.
     at processing.app.Serial.<init>(Serial.java:125)
     at processing.app.Serial.<init>(Serial.java:66)
     at processing.app.SerialMonitor$3.<init>(SerialMonitor.java:93)
     at processing.app.SerialMonitor.open(SerialMonitor.java:93)
     at processing.app.AbstractMonitor.resume(AbstractMonitor.java:110)
     at processing.app.Editor.resumeOrCloseSerialMonitor(Editor.java:2240)
     at processing.app.Editor.access$2400(Editor.java:77)
     at processing.app.Editor$DefaultExportAppHandler.run(Editor.java:2315)
     at java.lang.Thread.run(Thread.java:745)
    Caused by: jssc.SerialPortException: Port name - COM11; Method name - openPort(); Exception type - Port busy.
     at jssc.SerialPort.openPort(SerialPort.java:164)
     at processing.app.Serial.<init>(Serial.java:114)
     ... 8 more
    Error opening serial port 'COM11'.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

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

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

body: Ok strange, just after posting this the qduino decided to flash a different light on me so I try to upload again and it works... So apperantly just by keeping the qduino connected for some time it will start to work again...


message:
Failing to write to SD card using SD.h

Using a knockoff Arduino Nano (pinout seems to be the same), I would like to record data to an external SD card. I have everything hooked up (correctly I think) but I continue to fail to initialize the card using `SD.begin()`.

Here's a snippet of code that I'm running to do this:

    //Wire and MS5803_I2C libraries for communicating with the pressure sensor.

    #include <Wire.h>
    #include <SparkFun_MS5803_I2C.h>
    // For the SD card reader.
    #include <SPI.h>
    #include <SD.h>

    const int chipSelect = 4;

    void setup(void) {
      Serial.begin(9600); // Set baud rate.
      pinMode(10, OUTPUT); // Set data output pin for the SD card reader.
      digitalWrite(10, HIGH);
     // see if the card is present and can be initialized:
     if (!SD.begin(10)) {
       Serial.println("Card failed, or not present");
       // don't do anything more:
       return;
     }
     Serial.println("card initialized.");
      delay(500);  // Wait half a second before continuing.
    }

    void loop(void) {
      Serial.println("Hello Library!");
      delay(100000);
    }

Here's the Nano pinout:

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

And a picture of the circuit.

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

  [1]: https://i.stack.imgur.com/qLIni.png
  [2]: https://i.stack.imgur.com/Msdv5.jpg

body:
The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?

When your Nano board is 5V, you need a SD module with a level shifter for the signals.

To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.


body:
Is it my eyes or there's nothing connected to D4...?

    const int chipSelect = 4;

Your chipSelect/CS pin seems connected to D10.


message:
How can i provide enough power on an UNO to use the HC-12 wireless module?

Scenario:  The Uno is being powered by USB for programming, and the HC-12 wireless communications module is wired correctly.  But it will not work.

In reading through the web literature, it is mentioned that to use the HC-12 in the high-power (100 mW) mode requires a power supply in excess of what the laptop's USB port will provide.

I am finding nothing on Stackexchange that addresses this issue.

So the question is, how do I get the power to run the Uno with the HC-12?  I need to be able to periodically update the programming and test it while that auxiliary power is applied, and need to know it is safe to do so.

body:
There two options I have found that work well.

First is a simple wall-wart that provides 12 Volts to a barrel connector, like for a CCTV camera.

Or, if I want to run the Uno from a separate higher-amperage USB charging port I have found that there are "USB A Male to CCTV male" cables that work.

Doing the latter means the Uno is running at 5V instead of utilizing the on-board regulator to drop a higher-voltage input, which only matters if your circuit expects to find more than 5 Volts on the Vin pin (although that is not supposed to be an output pin, of course).

Through thorough experimentation I've proven that both methods work.

The best part is that the Uno can easily tolerate having both CCTV-style power and also being plugged into the laptop for programming and testing (like using the serial monitor).

Lesson learned:  The HC-12 simply will not work without auxiliary power, and it is safe to provide such power while also plugging the serial port into a laptop.


message:
Trouble while using Arduino DUE as programmer

I'm trying to use the arduino DUE board as a  AVR Programmer. My target device is atmega328p. After uploading the ArduinoISP into the DUE Board. I've tried to let a pin toggle using the following code:

    #define F_CPU 10000000
    #include <avr/io.h>
    #include <util/delay.h>

    int main (){
     DDRD |= (1<< PD7);
     for(;;){
      PORTD ^= (1<< PD7);
      _delay_ms(1000);
     }
     return 0;
    }

I want to use the internal oscillator and based [this example ][1] I've adjust the makefile:

    DEVICE     = atmega328p
    CLOCK      = 8000000
    PROGRAMMER = -c arduino -P COM10 -b 19200
    OBJECTS    = main.o
    FUSES      = -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

the problem that I have is that when run :

    make flash
I get the following :

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

and yes the port COM10 is definitely correct.

does anyone have a suggestion how to solve this ?

thanks in advance !

  [1]: https://gist.github.com/holachek/3304890
  [2]: https://i.stack.imgur.com/bFDr5.png

body:
There error you have is from *avrdude* failing to get a communication link established to the 'programmer' (which manipulates the target.)

Here is a link that may help with the connection

[Stk500 error][1]

Here is another relative link that may help

[Arduino ISP on DUE][2]

Best of luck.

  [1]: https://arduino.stackexchange.com/questions/17/avrdude-stk500-getsync-not-in-sync-resp-0x00-aka-some-dude-named-avr-won
  [2]: https://petervanhoyweghen.wordpress.com/2013/06/11/arduinoisp-on-the-due/


message:
Why is integer-to-string not working in this sketch?

I am using a Pro Mini to read analog values and to send them via serial.

Goal of the sketch is to stream these values to Serial as fast as possible, to obtain a steady stream of at least 1000 readings per second. For this reason I reduced the ADC prescaler and I increased serial speed.

I tested sending binary values with Serial.write and it works (it's the fastest), I tested Serial.print (it's the slowest), and I tested an [optimised conversion integer-to-string][1] (found on StackOverflow) in association with Serial.write.

This optimised conversion is faster than Serial.print (it would allow me to send the full strings within the given timeframe), but it gives me wrong values. I cannot understand why it happens, the code looks fine to my not-so-expert eye.

A correct stream as sent by Serial.print would be (spaces added for clarity):

    3075 \t 2800 \t 4132 \n

"Wrong values" means that the last value gets repeated for all the three columns:

    4132 \t 4132 \t 4132 \n

What is the issue in my code regarding the int2str conversion?

Since I cannot get one measurement taken and sent every 500 us, I would like to use the optimised routine to get plaintext readings at 1000 us intervals.

The source code follows. I cut out the function slimADC because it was tested as working, while I left all the 3 methods for sending data via serial: binary, optimised, Serial.print.

    #include <digitalWriteFast.h>

    volatile unsigned long previousMicros, currentMicros;

    #define SAMPLES 8
    volatile unsigned int valuesX;
    volatile unsigned int valuesY;
    volatile unsigned int valuesZ;

    char* x;
    char* y;
    char* z;

    void setup() {
    // set pins, ADC prescaler and initialise ADC
      pinModeFast(A0, INPUT);
      pinModeFast(A1, INPUT);
      pinModeFast(A2, INPUT);
      ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear bits
      ADCSRA |= bit (ADPS0) | bit (ADPS2);  // 32: 32 us per ADC
      slimADC(0);
      slimADC(0);

    // initialise Serial
      Serial.begin(250000);
      Serial.write("\n");
      Serial.write("\n");
      previousMicros = 0;
    }

    void loop() {
      currentMicros = micros();
      if ((currentMicros - previousMicros) < 1000) { return; }
      previousMicros = currentMicros;

    // ADC readings, repeated SAMPLES times
      valuesX = 0;
      valuesY = 0;
      valuesZ = 0;
      for (uint8_t i = 1; i < SAMPLES; i++) {  // 8*3*32=768 us
        valuesX += slimADC(0);
        valuesY += slimADC(1);
        valuesZ += slimADC(2);
      }

    // SERIAL TRANSMISSION

    // fastest
    //  Serial.write(valuesX / 256);
    //  Serial.write(valuesX % 256);
    //  Serial.write("\t");
    //  Serial.write(valuesY / 256);
    //  Serial.write(valuesY % 256);
    //  Serial.write("\t");
    //  Serial.write(valuesZ / 256);
    //  Serial.write(valuesZ % 256);
    //  Serial.write("\n");

    // good
      x = int2str( valuesX );
      y = int2str( valuesY );
      z = int2str( valuesZ );
      Serial.write(x);
      Serial.write("\t");
      Serial.write(y);
      Serial.write("\t");
      Serial.write(z);
      Serial.write("\n");

    // slowest
    //  Serial.print(valuesX);
    //  Serial.print("\t");
    //  Serial.print(valuesY);
    //  Serial.print("\t");
    //  Serial.print(valuesZ);
    //  Serial.print("\n");
    }

    static int slimADC(uint8_t pin) { ... }

    char _int2str[7];
    char* int2str( register int i ) {
      register unsigned char L = 1;
      register char c;
      register boolean m = false;
      register char b;  // lower-byte of i
      // negative
      if ( i < 0 ) {
        _int2str[ 0 ] = '-';
        i = -i;
      }
      else L = 0;
      // ten-thousands
      if( i > 9999 ) {
        c = i < 20000 ? 1
          : i < 30000 ? 2
          : 3;
        _int2str[ L++ ] = c + 48;
        i -= c * 10000;
        m = true;
      }
      // thousands
      if( i > 999 ) {
        c = i < 5000
          ? ( i < 3000
              ? ( i < 2000 ? 1 : 2 )
              :   i < 4000 ? 3 : 4
            )
          : i < 8000
            ? ( i < 6000
                ? 5
                : i < 7000 ? 6 : 7
              )
            : i < 9000 ? 8 : 9;
        _int2str[ L++ ] = c + 48;
        i -= c * 1000;
        m = true;
      }
      else if( m ) _int2str[ L++ ] = '0';
      // hundreds
      if( i > 99 ) {
        c = i < 500
          ? ( i < 300
              ? ( i < 200 ? 1 : 2 )
              :   i < 400 ? 3 : 4
            )
          : i < 800
            ? ( i < 600
                ? 5
                : i < 700 ? 6 : 7
              )
            : i < 900 ? 8 : 9;
        _int2str[ L++ ] = c + 48;
        i -= c * 100;
        m = true;
      }
      else if( m ) _int2str[ L++ ] = '0';
      // decades (check on lower byte to optimize code)
      b = char( i );
      if( b > 9 ) {
        c = b < 50
          ? ( b < 30
              ? ( b < 20 ? 1 : 2 )
              :   b < 40 ? 3 : 4
            )
          : b < 80
            ? ( i < 60
                ? 5
                : i < 70 ? 6 : 7
              )
            : i < 90 ? 8 : 9;
        _int2str[ L++ ] = c + 48;
        b -= c * 10;
        m = true;
      }
      else if( m ) _int2str[ L++ ] = '0';
      // last digit
      _int2str[ L++ ] = b + 48;
      // null terminator
      _int2str[ L ] = 0;
      return _int2str;
    }

**Appendix**

The bare ADC conversions take about 768 us.

With binary data I am sending via serial 3x uint16_t plus one end of line and two tabs, meaning 9 characters per reading. At 250 kbps 8N1 the minimum time required is 324 us. Using RealTerm (for Win) I can see that I get a stram of 9k chars/s, as expected.

With Serial.print I am sending 4x string[4] (readings are always between 1000 and 9999), plus tabs and newline, meaning 15 bytes per reading. RealTerm however gives me an incoming stream of 11-12k chars/s, therefore Serial.print is too slow.

The optimised int-to-string function (even without modifying it to avoid checking for negative and for >9999, not needed in my case) still sends 15 bytes per reading, and RealTerm also shows me an actual stream of 15k chars/s, as expected.

  [1]: https://stackoverflow.com/a/20567753/2131851

body:
it took me a while and i'm still not 100% sure if I got you right. I think you have two questions:

> 1) how to speed up the entire execution?

the serial routines will be your biggest bottleneck. I would suggest that a) you speed up the baud rate; and b) you try to use a tx interrupt here.

> 2) why isn't the int2str() routine working?

because int2str() stores the converted string in a buffer (_int2str[]), which is subsequently destroyed by conversions. so for it to work, you should do something like this:

      serial.write(int2str(x)); serial.write("\t");
      serial.write(int2str(y)); serial.write("\t");
      serial.write(int2str(z)); serial.write("\n");

BTW, int2str() can be written a lot better than it is now.

edit: to add an alternate int2str() implementaton.

    //positive and negative numbers
    //int is 16-bit type
    char *int2str2(int i) {
     static char _int2str[7];
     unsigned char tmp, str_len=0;  //converted string starts at _int2str[0]

     //process the sign
     if (i&0x8000/*<0*/) {
       _int2str[str_len++]='-';   //insert leading '-'
       i=-i;        //make the number positive
     };

     //convert the next position (10,000)
     tmp = 0;       //reset tmp
     while (i >= 10000) {
       i-=10000;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the next position (1,000)
     tmp = 0;       //reset tmp
     while (i >= 1000) {
       i-=1000;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the next position (100)
     tmp = 0;       //reset tmp
     while (i >= 100) {
       i-=100;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the next position (10)
     tmp = 0;       //reset tmp
     while (i >= 10) {
       i-=10;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the lsb
     //tmp = 0;       //reset tmp
     //while (i >= 100000ul) {
     //  i-=100000ul;      //decrement i
     //  tmp+=1;       //increment counter
     //}
     tmp = i;
     _int2str[str_len++] = tmp + '0'; //form the msb

     return _int2str;
    }

here is what I would use. I benchmark against yours, converting numbers from 0 to 32767. total cycle count for yours is 10.5 million and 7.0 million for mine. Now, the actual performance will depend on a lot of factors, like your chips, compilers (I used IAR AVR), and optimization settings, to name a few.

Note: the routine was written as a generic one. if you are only converting 10-bit numbers (from a 10-bit adc for example), it can be greatly simplified, and execution time greatly shortened: <160K cumulative cycles converting numbers from 0 to 1023.


message:
LCD displays wrong temperature

Hi I have a program that does not work right as I aspect:

    v = tempC;
    h = tempC * 10;
    h = h % 10;
    memset(stempCA, 0, sizeof(stempCA));
    sprintf(stempCA, "%+.2d.%d", v, h);

it works fine on positive temperature "+11.22"
but not for negative values : "-02.-1"

where is my mistake?
 thanx

body:
I think, that -1=-1, not 9 as you would like. I use

    if (tempC<0) {print'-';tempC=-tempC;};
    print tempC as usual for positive numbers


message:
How to setup HC05 Module to be distinguishable

I'm not sure if this is a dumb question, but here goes  :

I am developing an Android app that uses a custom Bluetooth device as a companion. I'm using an HC05 module to interface the device with my app. What I need is a way for me to distinguish my HC05 module from, say, some other HC05 module that might be in range.

The obvious way of doing this would be to set the device name in a certain format. But I was wondering if there was a more better approach to this.

On searching, I found that UUID's are used for a similar purpose (i.e. service discovery), but I couldn't find any further info. Is it at all possible to set a custom UUID for the HC05 module so that I can filter devices in my Android app based on that?

body:
As frarugi87 recommended in the comments, you need to change the device's name. Changing the device name will allow you to identify it by a custom name that you come up with. To do this you need to use something called AT Commands. Here is a guide that contains many of the system parameters that you can check and change via AT Commands: http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS

Here is a brief summary about how to change the device name, quoted from the above Instructable:

First switch the device into command mode

> For the HC-05 module to switch to AT command mode, the HC-05 pin 34
> (often referred to as the Key pin) needs to pulled HIGH but in a
> certain order of events explained below. When the HC-05 enters the AT
> command mode, it will communicate at 38400 baud rate. Follow these
> steps in the stated order to switch to the HC-05 to AT command mode.
>
> 1. Wire the HC-05 and Arduino Uno per instructions.
> 2. BEFORE YOU CONNECT THE ARDUINO TO THE USB remove the VCC (power) red wire from the HC-05 so it's not getting any power from the
> Arduino. All other wires are still connected.
> 3. Now connect the Arduino Uno to the USB cable extended from your PC.
> 4. Make sure the HC-05 module is NOT PAIRED with any other Bluetooth device.
> 5. Re-connect the Arduino Uno 5V wire to the HC-05's VCC (5V power) pin.
> 6. The HC-05 LED will blink on and off at about 2 second intervals. Now the HC-05 is in AT command mode ready to accept commands to change
> configuration and settings.
> 7. To test if everything is wired correctly,  open the Serial Monitor from the 8. Arduino IDE and type "AT" and click SEND. You should see
> an "OK" If you don't see an "OK" check your wiring.

Next run this program on your Arduino

    /*

    AUTHOR: Hazim Bitar (techbitar)
    DATE: Aug 29, 2013
    LICENSE: Public domain (use at your own risk)
    CONTACT: techbitar at gmail dot com (techbitar.com)

    */

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup()
    {
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more
    }

    void loop()
    {

      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available())
        Serial.write(BTSerial.read());

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());
    }

Finally (the quotes aren't part of the command)

> To change device name from the default HC-05 to let's say MYBLUE
> enter: "AT+NAME=MYBLUE"


body:
Your options are:

 1. As you guessed, you could set the name with `AT+NAME=`, and only use the names matching some pattern. It would work if you're only user so you just want to ignore other BT devices, but is problematic if you're having multiple independent users (each with its different set of *HC05*s) who might be in range (you could set different pattern for each user, though).

 2. build a database of addresses (read-only with `AT+ADDR?`), and only access those devices that are belonging to that user. It would avoid problem above with multiple users, but would require some logistics on your part (for example, when you sell user the app and HC05s, in the registration process you'll need to assign exactly which HC05 address that user my access. Or you might want to allow user to pick which devices are his, by having him specify specify PIN for pairing set with `AT+PSWD=`)

 3. third way is to [use custom Inquire Access Code][1] instead of [GIAC][2] so only that set of devices is scanned. HC05 [allows setting it][3] with `AT+IAC=`. However, as it is more complex and nonstandard that (2), and you'd probably still need to registration to differentiate which user is allowed which IAC, I'd recommend you do (2) instead.

  [1]: https://stackoverflow.com/q/4827343/2600099
  [2]: https://www.bluetooth.com/specifications/assigned-numbers/baseband
  [3]: http://elecfreaks.com/store/download/datasheet/Bluetooth/HC-0305 serail module AT commamd set 201104 revised.pdf


message:
Arduino read PWM duty cycle value with input (analog / digital)

I am working on comparing autopilots like [Ardupilot][1], [CC3D][2], [KK2.1.5][3]. The comparision is about system reactions/behaviors that it gives during flight. For this purpose, I need to read the PWM duty cycle (like osilascopes - the PWM frequency can be vary from 50 to 430 Hz) values from autopilot card. There are 4 command input PWMs and 4 esc control PWMs for a typical quadrotor. **I have to read 8 duty cycle values with digital/analog input pins.** How do I measure duty cycle of 8 PWM signals?  Also, is digital or analogue measurement precise and faster?

*Note about **attachInterrupt** command: According to [arduino.cc][4] AtMega328 series have **2** interrupts, Arduino ATmega 2560 series have **7** interrupts.*

  [1]: http://ardupilot.org/
  [2]: http://www.dronetrest.com/t/cc3d-flight-controller-guide/830
  [3]: https://www.google.com.tr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjN7ubm7dfRAhVnIpoKHfF9DDQQFggZMAA&url=https://www.rcgroups.com/forums/showatt.php?attachmentid=6646802&d=1396466493&usg=AFQjCNG_tmyH1Ppv2sy7WixUytnVCPFHDA&sig2=pgugQ4brDIwro2KgWw1ziQ&bvm=bv.144224172,d.bGs
  [4]: https://www.arduino.cc/en/Reference/attachInterrupt

body:
if done in analog, run the pwm through a lpf and perform an adc on the output;

if done in digital, use a timer's capture function, or use external interrupt / pin change interrupt to capture the timing off a time base.


body:
The code shown in [my answer to question 18183](https://arduino.stackexchange.com/a/18221/3917), “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM.  It can easily be adapted to work with eight channels.  It has an ISR that runs when selected pins change.  It sorts out which channel(s) changed, and stores the value of `micros()` at each change.

Also see [my answer to question 19106](https://arduino.stackexchange.com/a/19109/3917), “Can external interrupts be OR'd together on the '328 (Uno)?”  That answer includes a sketch for generating appropriate ISR code.  [My answer to question 32572](https://arduino.stackexchange.com/a/32582/3917), “How to detect the direction of a rotary encoder?”, shows another instance.

Digital input, as used in the code mentioned above, takes under  <strike>a microsecond</strike> ten microseconds in the ISR.  As noted in dannyf's comment, unrolling the `for` loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs.  Note, ISR entry and exit still add several microseconds.

10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring.  So it isn't fast enough.  If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in [a webpage at microsmart.co.za](http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/) can get AD conversion time down to 20 μs.  This is around three times as long as digital input takes, so rather slow.


message:
Why adding a LED between Pin 3 and Ground causes LCD display not to show text?

For a project of mine I am programming an Arduino UNO to show information I get from some sensors on an LCD display.

As a first step I setup Arduino to show "Hello, world!" on the LCD, which worked.

[![LCD showing "Hello, world!"][1]][1]

For "decorative" reasons I wanted to add some LEDs between the resistors that I placed in series between PIN 3 (V0) of the LCD and ground (about 1.5K Ohm total resistance).

I first of all added one LED between the last resistor and ground. To my surprise this causes the LCD display not to show "Hello, world!" any more.
As you can see the current is flowing (the LED is lit), but I can't understand why the LCD does not show the text.

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

Can you help me understand what's going on? I know very little of electronics and I am learning it by doing, so I would appreciate an answer that is good for a beginner!

  [1]: https://i.stack.imgur.com/n9x7m.jpg
  [2]: https://i.stack.imgur.com/xwjCA.jpg

body:
In a [typical 1602 LCD pinout](https://www.openhacks.com/uploadsproductos/eone-1602a1.pdf), pin 3 or V0 is the contrast setting for the display.  It usually is set to a voltage near ground, often by using a 10K pot with ends connected to Vdd and Vss with wiper to V0.

By putting an LED in series with your resistors (that apparently go to ground) you've either disconnected V0 from ground or have raised its voltage by the LED voltage.  This reduces contrast to the point that characters aren't visible even though they are on the display.

The LED backlight remains on and at the same brightness as before because it is driven via pins 15 and 16, independent of all other display settings.

*Edit 1:* I haven't duplicated your circuit to take measurements, so at the moment don't know for sure; but (in resistors-only case) V0 from pin 3 on the 1602 LCD board apparently sources some small current through your 1500 Ω to ground.  When you add an LED it can disconnect V0 from ground or can raise its voltage by the LED voltage, as follows:  firstly, if the LED cathode faces V0 and V0 is positive, no current will flow through the diode, thus disconnecting V0.  Secondly, if the LED anode faces V0 and V0 is positive, current will flow through the LED.  If the LED lights at all, most of its Vf characteristic voltage (typically between 3 and 4 volts for a green LED) will appear across it.  Thus, V0 sits at close to Vf plus whatever drops across the resistors.

*The same as for other diodes, LED forward current increases exponentially with voltage ([Ref: wikipedia on LED physics](https://en.wikipedia.org/wiki/Light-emitting_diode#Physics)) hence voltage change is tiny over large changes in current when an LED is emitting light.  In other words, if the LED is lighting up, its voltage will be close (ie within a few dozen millivolts) to its characteristic band gap voltage.  See [petervis.com's led-resistor-calculator](http://www.petervis.com/electronics/led/led-resistor-calculator.html) for a "Chart by Colour" that shows characteristic Vf forward voltages.


body:
> Can you help me understand what's going on?

that pin controls the contrast and it needs to be 3.5 - 4.x volt (typical) below Vcc. an led in conduction would drop 2 - 3v, depending on the led, making that pin's potential much closer to Vcc -> minimum contrast so you cannot see the text being displayed.


message:
What does an arduino sketch translate to before compilation?

I've been experimenting with Arduino on both esp8266 and AVR chips. The structure of the `.ino` file usually looks like this:

    #include "Arduino.h"
    #include "ESP8266WiFi.h"
    ##Some includes

    void setup()
    {
    ...
    ##Will be only run once at the begining.
    }

    void loop()
    {
    ##Runs this code in a constant loop
    }

My assumption is that somewhere behind simplification, before the compilation takes place, there is a `full blown source file`. It includes the platform specific initialization and contains the calls to `setup()` and `loop()`. When I say `full blown source file` I mean something that can be passed to the compiler and will compile given that the dependencies are met.

My questions are:

* Is this assumption correct?
* If so, can someone share an example on how does the `full blown source file` look like, and where did you get it from?

body:
C++ (the actual language/compiler that is used) is a multiple-compilation-unit language. There is no single source file, but rather a bundle of compiled source files, that are linked together to create the executable (or downloadable image).

In you case the user sketch provides the `setup()` and `loop()` functions, which are called from another source file, which is provided by the Arduino IDE.


body:
The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like `digitalWrite` and so forth.

There is a `main.cpp` file that gets compiled which is pretty much nothing more than:

    #include "Arduino.h"

    int main(void) {
        //Initialise timers and things (internal)
        init();
        //Your initialisation stuff (setup)
        setup();
        //Loop forever
        for (;;) {
            //Calling your loop function
            loop();
        }
    }

In terms of what your `.ino` file becomes, it is basically just copied to a temporary build directory and renamed to `.cpp`. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.

This process is actually why if you use your own header file which has some `typedef` in it which you then use in a function call, the code will break because the declarations get added above the `#include` statements meaning the custom type is used before it is defined.

If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the `.cpp` file with the same name as your `.ino` file.


message:
Slowly increase speed using PWM arduino

I'm trying to control the speed of a DC motor using PWM. Here is my code so far:

    int motor = 9;
    int fadeValue = 5;

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

    void loop() {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
      if (fadeValue==245) {
        fadeValue=255;
        break;
      }
    }

I want the motor to slowly increase it speed then stay high. However, the loop keep repeating.

Thanks in advance guys.

body:
>However, the loop keep repeating.

That's the whole point of loop(). If you want some code to run only once after the program starts put it in `setup()`:

<!-- language: lang-cpp -->

    int motor = 9;
    int fadeValue = 5;

    void setup() {
      pinMode(motor, OUTPUT);

      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
        if (fadeValue == 245)
        {
          fadeValue = 255;
          break;
        }
      }
    }

    void loop() {
    }


body:
If you dont want the code to repeat at the maximum, just add a condition to the loop. Your solution could look like this:

    int fadeValue = 5;

    void loop()
    {
        if (fadeValue < 255)
        {
            if (fadeValue >= 245)
            {
                fadeValue = 255;
            }
            else
            {
                fadeValue++;
            }
            analogWrite(motor, fadeValue);
            delay(100);
        }

        //Other code here
    }

By setting `FadeValue` to another value, the fade will start again from the new value until the maximum.


body:
it can be put in the loop(): putting it in the setup(), if the speed-up period is long, isn't practical or feasible in some applications.

you can use a loop counter or time counter to slow down the ramp-up without tying down the mcu, like this:

      time_now = time(); //take a reading of current time. or millies()
      if (time_now < TIME_RAMPUP) { //still need to ramp it up
        if (time_now > time_prev) { //need to increment motor speed
          time_prev+=TIME_INC;
          motor_dc+=PWM_STEP;  // you may wish to bound the dc here
          analogWrite(MOTOR_PIN, motor_dc); //increase dc
        }
      }


body:
If you want void loop() to only run once and don't want to put your code into setup() for some odd reason, just as an infinite while loop at the end with a delay inside like this:

    void loop()
    {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10)
    {
        analogWrite(motor, fadeValue);
        delay(100);
      if (fadeValue==245)
    {
        fadeValue=255;
        break;
      }

    While(1)
        Delay(1000);

    }


body:
Could you also change the order the loop is in? So the code would look like this instead:

    void loop() {
      if (fadeValue == 245) {
        fadeValue=255;
        analogWrite(motor, fadeValue);  // motor will stay at highest value
        }
      else {
          for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
            analogWrite(motor, fadeValue);
            delay(100);
            }
      }
    }

So now, the loop will run until fadeValue == 245, at which point the loop will not advance to the for loop because the "if" in the if/else statement is satisfied. I'm not actually sure if this will work, but it's an idea.


message:
Delay between multiple analogReads

I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this [link][1]. I then tried to read the analog pins and I used the following code to display the time and the readings:

----------

    #define FASTADC 1
    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif
    double t = 0;
    void setup() {
      int start;
      int i;
      #if FASTADC
      // set prescale to 16
      sbi(ADCSRA, ADPS2);
      cbi(ADCSRA, ADPS1);
      cbi(ADCSRA, ADPS0);
      #endif

      Serial.begin(9600);
      Serial.print("ADCTEST: ");
      start = millis();
      for (i = 0 ; i < 1000 ; i++)
        analogRead(0);
      Serial.print(millis() - start);
      Serial.println(" msec (1000 calls)");
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // print out the value you read:
      t = millis() / 1000;
      Serial.print(t);
      Serial.print('\t');
      Serial.print(analogRead(A0)); delay(1);
      Serial.print('\t');
      Serial.print(analogRead(A1)); delay(1);
      Serial.print('\t');
      Serial.print(analogRead(A2)); delay(1);
      Serial.print('\t');
      Serial.println(analogRead(A3)); delay(1);
    }

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).

Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?

Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?

Here is the screenshot of the readings from the 4 channels (2V input).

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

Summarizing everything, I need to know the following:

1. The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.

2. How to find the best sampling frequency for every input and how to control it?

3. Will using Matlab to plot the data affect the sampling frequency?

Thanks.

  [1]: http://forum.arduino.cc/index.php?topic=6549.0
  [2]: https://i.stack.imgur.com/YUqjH.png

EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.

body:
I tried your program on my Arduino Uno with similar results : it prints
about 44 lines per second. Then I did the math:

Each line consists of 22 characters, including the CR and LF at the end.
Each character is transmitted as 10 bits (8 data bits, one start bit and
one stop bit). At 9600 bits/second, each bit takes 0.104 ms to be
transmitted. All this amounts to 22.88 ms per line (22 × 10 × 0.104), or
about 43.7 printed lines per second, on average.

Now, since you are using a Leonardo, things could be a little different,
as the Leonardo does not use a real serial port, but a virtual one. You
may still try to increase the baud rate to see if it makes any
difference.


body:
At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.

However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at [the CDC emulation source code](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/CDC.cpp) you will see that the baud rate you pass to the `begin` function is ignored.

So... Why is it still slow? Because you are using the `delay` function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the `delay` function breaks the timing - better use a timer - and 2) you are too slow.

Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):

    #define INTERVAL_LENGTH_US 1000UL

    unsigned long previousMicros;

    void loop()
    {
     unsigned long currentMicros = micros();

     if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
     {
      previousMicros += INTERVAL_LENGTH_US;

      int val_a0 = analogRead(A0);
      int val_a1 = analogRead(A1);
      int val_a2 = analogRead(A2);
      int val_a3 = analogRead(A3);

      Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
      Serial.print('\t');
      Serial.print(val_a0);
      Serial.print('\t');
      Serial.print(val_a1);

      Serial.print('\t');
      Serial.print(val_a2);
      Serial.print('\t');
      Serial.println(val_a3);
     }
    }

NOTE: The `millis()` function is replaced by `micros()` according to Edgar's and Nick's comments.

Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The `t` variable is not needed anymore.

Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).

<s>If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays.</s> Not needed anymore


body:
Two ways to sample at or near a given frequency:

1. Select the right ADC clock prescaler. This has some limitations and may not get you too the precise sampling frequency.

2. Use a timer to trigger the sampling. Can be done in either. Hardware or software. It is the most flexible way here, especially if coupled with the ADC isr.


body:
A few recommendations to get good performance out of the Arduino boards.

 - Maximize your analogResolution if the default is not already the max (as in the case of the Due.)
 - If possible, use a simple oscillator instead of a constant Voltage source.  If you can create a sine or triangle wave with its peaks within the Arduino's input voltage range, you can plot something more interesting than a straight line.
 - There is no need to do any analogReads in setup(), and you DON'T want to do anything with the Serial object in setup() except configure it.  (There is an under-the-hood reason for that.)
 - To get good sample rates from the Arduino boards, don't convert to text until MUCH later in the data flow.  TO try this SIGNIFICANT speed optimization, declare an array of 4 elements of type unsigned int, another array of 12 elements of type unsigned char, and an unsigned long to hold the time.
 - In loop(), start by assigning micros() to the unsigned long
 - Then **call the four analogReads in an uninterrupted sequence**, assigning them to the four elements of the unsigned int array.
 - Then copy the four bytes from the unsigned long and the eight bytes from the four unsigned ints into the 12 elements of the unsigned char array.  You will need to use the C++ shift right operator ">> 4" and the "(unsigned char)" type conversion to do this part.
 - Then, still in loop(), call Serial.write(byteArray, 12) once to send the time and digital representations all at once (in the byte order you specified) through the serial connection.
 - Place delayMicroseconds at the very end of the loop to get a higher resolution delay between loop iterations.
 - On the other side of the serial connection (the workstation or laptop) use dd or some other low level transfer program (instead of a terminal emulator) to copy from the binary 12-byte sample vectors from the serial device that your workstation or laptop uses to access the serial connection to a binary file.

The above eliminates several bottlenecks typical of the newbie example programs.  The issue remaining is that, to optimize speed, you never converted the raw binary data vectors to a tab-delimited text file that MATLAB or GnuPlot can read with ease.

A simple C, Java, or Python program can then read the 12 byte vectors and convert the byte groups of 4, 2, 2, 2, and 2 back into the 32 bit time stamp and the four 16 bit unsigned channel values in a loop.  The byte order is what you chose in your Arduino sketch.  You will need to use the left shift operator and bitwise and and or operations to reconstruct the time stamp and four channel values.  At the end of this loop, you can write these values as a single tab-delimited line coresponding to the current binary input vector.  Iterate through all the vectors to get a complete tab-delimited data file.

You can experiment with different delayMicrosecond values to get different sample rates, and you can calculate our baud rate to stay ahead of the sampling so that the program could theoretically run indefinitely without backing up the Serial buffer on the Arduino side.  Each Arduino analogRead and Serial object has its own maximum speed, which you can find by experimentation.


message:
Confusion with storage of declared variables and volatile

I read that **volatile** is used when we want to store variables in SRAM.

But aren't all the variables in a code are stored in SRAM anyway?

And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?

body:
That's just plain incorrect.

The `volatile` keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.

If you don't use `volatile`, the compiler may choose to make an optimisation.

Consider this code:

    int b = 7;
    a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it.  The compiler may choose to optimise this to the equivalent of

    a = 14;

But if you do this:

    volatile int b = 7;
    a = b + b;

then the compiler MUST read `b` twice from memory.

Why would you want to do that?  Perhaps you have an interrupt which might change the value of `b`.  Perhaps your interrupt changes the value of 'b' every time you press a button.  You need the code to really check the value of `b` every time it calculates `a`, and not rely on it always being 7.

[Here][1] is a fuller explanation.

  [1]: http://barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword


body:
Technically, variables can be stored anywhere, in SRAM, eeprom or enev flash.

However, without doing anything special, variables are stored in SRAM.

Thee votike attribute is just that, it tells the compiler that the variable could change its value and the compiler shouldn't assume that values obtained from prior access is valid now. This forces the compiler to re-read the variable on demand.


message:
Where is Arduino.h on a Mac? Can I download a copy if missing?

I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.

If it is built in to the tools can I download a copy of this file(s)?

body:
I've don't have a Mac, so I can't test this, but on the Arduino Forum they say find the file `Wiring.h` and create an empty file called Arduino.h in the same folder.

I don't know if that's the right approach, but it should get you to the next error, which may well be some system constant is not defined. If it does work you could go to github for the IDE (don't know exactly where that is) and download `Arduino.h` from there and stick it alongside `Wiring.h`.


body:
Generally, if you need to find a file you can open a terminal and type

    locate myfile.dat

This looks in a database (rather than searching the disk), which you may need to update by typing

    sudo updatedb                       // on linux
    sudo /usr/libexec/locate.updatedb   // on Mac


body:
On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.

You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.

You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under `hardware/arduino/avr`

On your Mac you may find them as `/Applications/Arduino.app/Contents/Resources/hardware/arduino/avr` or somewhere similar (not entirely sure where it puts it within the app).


body:
There simply is no "Arduino.h" file. Basically there are multiple platforms (the most common in Arduino world is the Arduino AVR platform). Each platform can contain multiple cores (but mostly only contains 1) and each core contains a "Arduino.h" file.

So to find the Arduino.h file you need to identify the board. The board gives you the platform and the core. Based on those the Arduino.h file is in the folder [platform installation folder]/cores/[core].

The [platform installation folder] is dependent on how the platform was installed on your system. For instance arduino avr comes with the Arduino IDE and as such it is installed in the app like majenko explained.

If it is installed by the boards manager on Linux, the Arduino IDE uses `~/.arduino15/packages/[provider]/hardware/[architecture]/[version]` and if I'm not mistaken the same location is used on Mac.

You can also point to a folder location where additional hardware is installed.

A word on Eclipse and Arduino. There are quite a few options to run compile Arduino sketches in Eclipse. Depending on the tool it goes from easy to pretty complex.

I personally advise to use Sloeber from sloeber.io as I am the developer.


message:
How to increase sensitivity of Capacitive Touch Switch?

I am working with `Capacitive Touch Sense` technology.In that I am using `TTP224` Touch detector IC. I am getting good sensitivity when I am using Touch pad without putting any non electric material over it and able to switch ON/OFF connected led.But when I put any non electric material like `Acrylic Sheet` of `2mm` thickness I am not able to get any signal through pad or not able to ON/OFF connected led.

So, How can I increase sensitivity of Touch pad?

[I have bought TTP224 module from here.][1]

And what can be the alternatives for `TTP224`???

  [1]: http://www.ebay.in/itm/172493711487?aff_source=Sok-Goog

body:
According to [the datasheet](http://www.tontek.com.tw/download.asp?sn=373) (if you can name it that):

> The capacitance Cs0~Cs3 can be used to adjust the sensitivity. The value of Cs0~Cs3 use smaller, then the sensitivity will be better. The sensitivity adjustment must according to the practical application on PCB. The range of Cs0~Cs3 value are 0~50pF.

So, reduce the capacitances Cs0 to Cs3 and you will get better sensitivity.


body: Sometimes things just ****. In my case, where 0.5 mm more of gap make the TTP223 unable to work, because I designed such a small pad. My solution? Remove the paint in the PCB, put a lot of solder in to make the pad taller. Work like a charm.


body: remove all c3 to c10 capacitors of 22pf. This will increase sensitivity and will sense through 5 mm sheet also .


message:
At what frequency/rate does the digitalRead function read an input?

Consider the following code:

    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      }
      else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

The line **buttonState = digitalRead(buttonPin);** checks the input voltage.

But how is that checked internally?

I mean at what rate the input is checked?

body:
That depends on the frequency your Arduino runs at.

It's basically once per iteration of the loop, and that depends on everything that is happening in the loop.

You can examine the assembly language output of the compiler (disassemble the .elf file using `avr-objdump -h -S <elf file>`) and count the number of clock cycles per iteration (the datasheet has the number of clock cycles per instruction). However that is tedious.

If you want to read the input at a specific frequency then you should do it using a timer interrupt.


body:
> When I get time, I will provide more definitive answers.

I did follow through with this, and the result is here, towards the end of the page: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/

the short answer is: digitalRead() takes 4.9us to execute on a 16MIPS Arduino Uno, or 79 ticks (=instructions).

the fastest you can read digitalRead() is then 200KHz (= 1/4.9us).

Hope it helps.


body:
It read a port just like it reads memory (to which it's mapped.) So speed is how fast an instruction can read memory.  EEPROM is a different animal.

Might get it a little faster by replacing

buttonState = digitalRead(buttonPin);
    with
buttonState = PORTB & _BV(buttonPin);

Assuming it's PORTB that you are using. This will alleviate at least one function call, I would think, and will generate a single instruction to read the port into the variable. It may require an instruction to load the variable address, but that's up to the compiler.  The replacement may be more trouble porting to other micros.  Normally you don't see a variable as a parameter although legal, usually a constant in a #define.

 _BV(INPUT_PIN_X) is a macro (BV is for 'bit value') that expands to
(1 << INPUT_PIN_X)

dannyf times seem quick to me, but it sounds like he's done the testing. Is he taking into account the complete function call as part of the time?  I run at 1Mhz normally, so it's more difficult to relate.

Take Majenko advice and start reading the generated assembler :)

Best of luck.


message:
Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield

I'm running the Uno board and want to connect the BLE Bluetooth shield (http://redbearlab.com/bleshield/) to control the Braccio Arm I have.

When I sit the Braccio Arm Shield on the Uno everything works - I can control the Arm.

When I sit the Bluetooth Shield on the Uno, everything works I can find the device and connect to it using the IOS App.

When I sit all 3 together, I can still control the arm but can no longer find the Bluetooth device.

Any ideas as to why this is?

body:
Be aware that the BLE Shield is using  a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from [BLEshield][1]
Therefore the BLE shield uses 6 pins e the [Braccio][2] uses almost all Arduino Uno pins.
Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.

You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example

  [1]: http://redbearlab.com/bleshield/
  [2]: http://www.arduino.org/products/tinkerkit/arduino-tinkerkit-braccio


message:
Strange characters after typing an AT command in serial monitor

I'm trying to test AT commands (I am working with an  Arduino Uno and a GSM/GPRS SIM900  shield; my system is ubuntu 14.10) . Yesterday when I was testing , all  ran well.. For example after typing AT+SAPBR=3,1,"APN","ooredoo" in the serial monitor it  showed me OK.. but But now it  shows me strange  characters.

This is my code

        #include <SoftwareSerial.h>
        SoftwareSerial GPRS(2,3);

    void setup() {
      // put your setup code here, to run once:
     GPRS.begin(9600);
      Serial.begin(9600);
     Serial.write("start");

    }

    void loop() {

      // put your main code here, to run repeatedly:
         while(GPRS.available())
         Serial.write(GPRS.read());

      while(Serial.available())
        GPRS.write(Serial.read());

    }

And this it is the result of AT+SAPBR=3,1,"APN","ooredoo" typed in the serial monitor

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

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

Thank you for helping me

body:
for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :

    GPRS.begin(2400);
    Serial.begin(9600);

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere

    GPRS.begin(2400);
        Serial.begin(2400);

and don't forget to change also  the speed on the serial monitor to 2400
I hope this will help someone


message:
Teensy lc linker script question

I am under the impression that the origin of RAM on a Cortex M is 0x20000000.  However, in the linker file for it, the ORIGIN of RAM is set to 0x1FFFF800.  Is that an error, or is there a reason for the discrepancy?

body:
The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.

In the case of the [MKL26Z64VFT4](https://www.pjrc.com/teensy/KL26P121M48SF4RM.pdf) used on the Teensy LC:

> The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM_L, and 3/4 is allocated to SRAM_U. Regardless of the block size, the SRAM is implemented such that:
>
> * SRAM_L is anchored to 0x1FFF_FFFF and occupies the space before this ending address.
> * SRAM_U is anchored to 0x2000_0000 and occupies the space after this beginning address.
>
> Valid address ranges for SRAM_L and SRAM_U are then defined as:
>
> * SRAM_L = [0x2000_0000–(SRAM_size/4)] to 0x1FFF_FFFF
> * SRAM_U = 0x2000_0000 to [0x2000_0000+(SRAM_size*(3/4))-1]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.


message:
Mains-Frequency Clock Library

I have an arduino thing, and the hardware I plan to connect to it (a triac zero-crossing based dimmer) provides a synchronization signal from the mains power phase it connects to.

Main power does of course vary some from the nominal 60Hz, however the exact frequency gets adjusted over the course of the day to ensure there are almost exactly 5184000 cycles per day and pretty much exactly 36288000 cycles per week, and is used by mains-powered wall clocks to keep time.

Since my application will need to keep accurate time-of-day across weeks or months without adjustment, it would be advantageous to be able to use this time source.

I can of course write my own code to increment a counter every time the arduino receives a pulse, but if a library that can handle this already exists, I would prefer to use that, in particular since then I won't have to write code to track days and months, handle DST, or any of that stuff.

What libraries exist (if any) to handle timekeeping based on a fixed-pulse-rate input source?

body: Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use [TimeLib.h](https://github.com/PaulStoffregen/Time) to convert seconds since 01/01/1970 to an actual time.  Or just do simple division to convert seconds (`count/50`) into minutes, hours, whatever division you want.


message:
What is the best board for setting up an SSH protocol to an Arduino?

I currently have a project using an Arduino R3, set up across the room from my computer. This has become quite annoying, as every time I want to push something to the Arduino I have to get up and move either the computer or the Arduino to another location, plug it in, and hope my code works the first time, lest I have to repeat the test over and over again. I am trying to set up an SSH server between my Raspberry Pi 2 and computer so I can just push new sketches over SSH, however, I use my Pi 2 for other projects occasionally and want to purchase a second board specifically for this purpose. Is there a good, cheap, board with wifi built in (besides the Pi 3) that I could use for this? Any suggestions?

body: Sounds like you want an [Arduino Yun](https://www.arduino.cc/en/Main/ArduinoBoardYun) instead of an Uno.  Or a [Dragino Yun Shield](http://www.dragino.com/products/yunshield/item/86-yun-shield.html) that turns your Uno into a Yun.


body:
If you get it working on the Pi2, could you just drop in a Pi Zero ($5) and a cheap USB network adapter ($2)?

Note that your question title asks for "best", but you don't define your criteria.  Reading between the lines I suspect "cheapest and adequate" is what you mean.


body: You could swap out the Arduino for a ESP012, not sure it meets your I/O needs. The new ESPs support over wifi firmware uploads.


message:
Wiring a potentiometer to control a 9V battery powering 2 LEDs in series

I am trying to build an array of LEDs where their brightness is controlled by a potentiometer.  The LCD will display the percentage of brightness based on the potentiometer.  I am able to successfully control the brightness of a circuit with only one LED.  However, I am having trouble with 2 two LEDs in series (which are in parallel with other sets of 2 LEDs in series).  And I believe the problem is that the Arduino is only supplying enough voltage to power one LED (maybe < 5V).  How can I properly wire a 9V battery to this circuit in which the potentiometer can control the amount voltage coming from this battery?  Are Arduinos only capable of controlling <5V with a potentiometer?

Here is my code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int potPin = A0;
    int ledPin = 6;
    int potValue = 0;

    void setup() {
      pinMode(potPin, INPUT);
      pinMode(ledPin, OUTPUT);
      lcd.begin(16, 2);
      lcd.print("Potentiometer");
    }

    void loop() {
      potValue = (analogRead(potPin)/10.02);
      analogWrite(ledPin, potValue);
      lcd.setCursor(0,1);
      lcd.print(potValue);
      lcd.print("%");
      delay(100);
      lcd.print(" ");
      delay(1);
    }

And here is a picture of my circuit setup:

[![LED array with potentiometer, LCD, and Arduino][1]][1]

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

body:
Yes, Arduino is a 5V microcontroller, meaning it can directly control 5V circuits only. You might incur in problems also trying to deal with 3.3V circuits, even if Arduino is pretty friendly to 3.3V counterparts.

That does not mean though you cannot control higher voltage circuits, just not directly. Actually if anything above 6V is connected to an Arduino PIN you will blow that pin and potentially others which are logically connected within the MCU, so be aware.

To control higher voltage circuits you have multiple options, in your case you are probably interested into using a BJT transistor, an 2N2222 might do.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/iToMV.png)

<!-- End schematic -->

Please note the values of R1 and R2 must be adjusted to the LEDs you are using depending on their Vf (forward voltage drop) and the maximum current you want to provide.


message:
Do I need to use the PWM pins in order to control brushless motors Arduino Uno?

I am building a quadcopter with this schematic:
[![enter image description here][1]][1]

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

It works very good but i have the pins on 3,5,6,9 = PWM pins. Is it possible to use "regular" pins instead? I will add more modules later on so i will most likely run out of PWM pins.

I could of course try it right now but i want to ask first so i could potentially avoid to destroy any items!

body:
No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.

In some non critical conditions (ESCs **are** critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.


message:
Fading LED Lights

How do you make a fading led with 8 different colors I already made a blinking led every 1 second. Can you give me an idea how am I going to fade it every time it switch?

    const int red = 5;
    const int green = 6;
    const int blue = 9;

    void setup() {
        // put your setup code here, to run once:
        pinMode(red, OUTPUT);
        pinMode(green, OUTPUT);
        pinMode(blue, OUTPUT);
    }

    void loop() {
        lightMe(red);
        lightMe2(red, green);  // yellow
        lightMe(green);
        lightMe2(green, blue);  // cyan
        lightMe(blue);
        lightMe2(blue, red);  // magenta
        lightMe3(red, green, blue); // white
    }

    void lightMe(int pin){
        digitalWrite(pin, HIGH);
        delay(1000);
        digitalWrite(pin, LOW);
        delay(500);
    }

    void lightMe2(int pin1, int pin2) {
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        delay(1000);
        digitalWrite(pin1, LOW);
        digitalWrite(pin2, LOW);
        delay(500);
    }

    void lightMe3(int pin1, int pin2, int pin3) {
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(pin3, HIGH);
        delay(1000);
        digitalWrite(pin1, LOW);
        digitalWrite(pin2, LOW);
        digitalWrite(pin3, LOW);
        delay(500);
    }

body:
You could look at this example, which fades an LED using PWM.

https://www.arduino.cc/en/Tutorial/Fading

Basically you use `analogWrite` to control the output of the pins with finer resolution, 0-255 rather than 0-1.  Only certain pins support PWM, they should be marked on your board.  You just need to extend the example to support your LED.  (Put the resistor on the common pin)


message:
Can I use Arduino to generate a 0 to 15V analog output?

Is it possible to use the analog output pin with some circuit to generate a 0 to 15V analog output?

body:
The Arduino does not have any "analog output pin". There are analog inputs, and you can generate a variable output with `PWM` pins.

Whether the latter meets your needs depends on your (unstated) requirements.


body:
The Arduino cannot directly produce anything more than 5V.

You can use PWM and a Low-Pass Filter to produce an analog waveform between 0 and 5V, which you can then amplify using a suitable non-inverting buffer with 3x gain (op-amp), which will boost the voltage to 15V. Whether that is suitable for your needs, though, since the current will generally be quite low (most op-amps have a high output impedance) is unknown.

If you want a cleaner waveform you can attach or create a DAC which produces discrete output voltages (again between 0 and 5V) which you then amplify similarly.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/glYNj.png)

<!-- End schematic -->

R3 and C1 form the low-pass filter and should be sized according to the frequency ranges you want to filter and keep. Note that many op-amps that can cope with the higher voltages you need aren't *rail-to-rail* which means you will have to use a higher power supply voltage than you want to output to leave some headroom. Similarly the 0V will be clipped and will never go below a certain voltage. If you want to get right down to 0V you will need a negative power supply to feed the V- supply of the op-amp (which is currently connected to ground in this schematic). That would allow the output to drop right down to 0V.


message:
Flash Esp-01 and Esp-12 using NodeMCU module

I am building a test IOT architecture. At the moment I do have a NodeMCU "Amica" V1 module (more will come) and some ESP-01. I have not yet tried to flash the ESP-01 because the MCU is just so user friendly, while buying 6 MCU is more pricey than .

I was wondering, if I do de-solder the ESP-12 from the NodeMCU and then connect a female receptacle for the ESP-01 to the now empty MCU breakout board, would i be able to flash the ESP-01 from the Arduino IDE?
Would it maintain the automatic Reset and Flash pulls (as on the stock ESP-12)?
Will it also work with a pogo-pin assembly to flash other ESP-07/12 ?

Approximate answers and thoughts are well accepted, thank you very much.

body:
On [this site][1] there's a description of how to use a USB-serial adapter to flash a ESP-01 with the Arduino IDE. I'm not very familiar with the NodeMCU boards, but I imagine that they contain a USB-serial chip, and thus it _is_ possible to desolder the ESP-12 and connect a ESP-01 (with cables or an adapter with pogo-pins) and program it that way. I'm not sure about the Reset/Flash pulls, but I imagine that it could be possible, study the pinouts for the ESP-12 and ESP-01 and circuitry for flashing (see the link). I did flash my ESP-01 this way, before I got other ESP8266 boards.

I would only do this operation if I was very handy with a soldering iron and the NodeMCU/ESP-12 was something that could go to waste if anything went wrong.

I think picking up a 3.3V LDO and USB-serial (3.3v!) breakout much easier, and more failproof, so that's what I'd recommend.

  [1]: https://www.hackster.io/rayburne/esp8266-01-using-arduino-ide-67a124