body:
I have a problem with my Arduino Uno and my [AS5311 position sensor ](https://ams.com/ger/content/download/17954/325059/file/AS5311_Datasheet_EN_v6.pdf)

I am trying to get incremental output as described in Section 7 but I don't really know how to do it. It says that there are three outputs: A, B, and index. A and B will change states 512 times per 2mm of magnetic band (256 pulses) and index will produce a pulse every 2mm. It says that A "leads" B when the magnet is moving from right to left and B "leads" A when the magnet is moving from left to right.

What is the right way to get this information? I suppose it's using interrupts on A, B, and index but I'm not sure how.

Here is what I have so far (absolute position works fine):

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

    const int A_Pin = 2;
    const int B_Pin = 3;
    const int Index_Pin = 8;
    const int CSn_Pin = 5;
    const int CLK_Pin = 6;
    const int DO_Pin = 7;
    int Bit;
    int Position;
    int Pow2[12] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
    int OCF, COF, LIN, MagINC, MagDEC, EvenPAR;
    volatile int ACount = 0;
    volatile int BCount = 0;
    volatile int IndexCount = 0;

    void fA(){
      ACount++;
      //What should I do here?
    }

    void fB(){
      BCount++;
      //What should I do here?
    }

    ISR(PCINT0_vect){
      if(digitalRead(Index_Pin) == 1) IndexCount++;
    }

    void setup(){
      //For incremental output
      pinMode(A_Pin, INPUT_PULLUP);
      pinMode(B_Pin, INPUT_PULLUP);
      pinMode(Index_Pin, INPUT);
      attachInterrupt(digitalPinToInterrupt(A_Pin), fA, RISING);
      attachInterrupt(digitalPinToInterrupt(B_Pin), fB, RISING);
      digitalWrite(Index_Pin, HIGH);

      //For absolute position
      pinMode(CSn_Pin, OUTPUT);
      pinMode(CLK_Pin, OUTPUT);
      pinMode(DO_Pin, INPUT);
      digitalWrite(CSn_Pin, HIGH);
      digitalWrite(CLK_Pin, HIGH);

      Serial.begin(9600);

      cli();
      PCICR = 1;
      PCMSK0 = Pow2[Index_Pin - 8];
      sei();
    }

    void loop(){
      //Absolute position
      //delay(1);
      digitalWrite(CSn_Pin, LOW);
      //delay(1);

      Position = 0;
      for(int z0 = 0; z0 < 12; z0++){
        digitalWrite(CLK_Pin, LOW);
        //delay(1);
        digitalWrite(CLK_Pin, HIGH);
        //delay(1);
        Bit = digitalRead(DO_Pin);
        Position += Bit * Pow2[11 - z0];
      }

      digitalWrite(CLK_Pin, LOW); //delay(1);
      digitalWrite(CLK_Pin, HIGH); //delay(1);
      OCF = digitalRead(DO_Pin);
      digitalWrite(CLK_Pin, LOW); //delay(1);
      digitalWrite(CLK_Pin, HIGH); //delay(1);
      COF = digitalRead(DO_Pin);
      digitalWrite(CLK_Pin, LOW); //delay(1);
      digitalWrite(CLK_Pin, HIGH); //delay(1);
      LIN = digitalRead(DO_Pin);
      digitalWrite(CLK_Pin, LOW); //delay(1);
      digitalWrite(CLK_Pin, HIGH); //delay(1);
      MagINC = digitalRead(DO_Pin);
      digitalWrite(CLK_Pin, LOW); //delay(1);
      digitalWrite(CLK_Pin, HIGH); //delay(1);
      MagDEC = digitalRead(DO_Pin);
      digitalWrite(CLK_Pin, LOW); //delay(1);
      digitalWrite(CLK_Pin, HIGH); //delay(1);
      EvenPAR = digitalRead(DO_Pin);

      digitalWrite(CSn_Pin, HIGH);

      Serial.print(Position);
      Serial.print(", ");
      Serial.print(OCF);
      Serial.print(", ");
      Serial.print(COF);
      Serial.print(", ");
      Serial.print(LIN);
      Serial.print(", ");
      Serial.print(MagINC);
      Serial.print(", ");
      Serial.print(MagDEC);
      Serial.print(", ");
      Serial.print(EvenPAR);
      Serial.print(", ");

      //Incremental output
      Serial.print(ACount);
      Serial.print(", ");
      Serial.print(BCount);
      Serial.print(", ");
      Serial.println(IndexCount);
    }

The first problem is that after a while `ACount` and `BCount` drift apart so sometimes interrupts appear to be overlooked. The second problem is that I don't know how to tell which output "leads" the other one. How can I get this information (direction of movement) consistently?

Update:
I tried what was suggested in the comments and it works most of the time. The problem is that sometimes I seem to get a false reading. When A goes up I check the state of B to see if I have left or right movement. I save the movement into a boolean variable (Left) which I then use in the function that is called when index is up. If Left is true I decrease the index counter, otherwise I increase it. But after some time the index counter differs by two from its true value which means that I had a false direction of movement when index is up. Here is my new code:

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

 const int A_Pin = 2;
 const int B_Pin = 3;
 const int Index_Pin = 8;
 const int CSn_Pin = 5;
 const int CLK_Pin = 6;
 const int DO_Pin = 7;
 int Bit;
 int Position;
 int Pow2[12] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
 int OCF, COF, LIN, MagINC, MagDEC, EvenPAR;
 bool Error = false;
 volatile int ACount = 0;
 //volatile int BCount = 0;
 volatile bool Left = true;
 volatile int IndexCount = 0;

 void fA(){
   if(digitalRead(B_Pin) == HIGH){
  Left = true;
  ACount--;
   }
   else{
  Left = false;
  ACount++;
   }
 }

 //void fB(){
 //  BCount++;
 //}

 ISR(PCINT0_vect){
   if(digitalRead(Index_Pin) == 1){
  if(Left) IndexCount--;
  else IndexCount++;
   }
 }

 void setup(){
   pinMode(A_Pin, INPUT_PULLUP);
   pinMode(B_Pin, INPUT_PULLUP);
   pinMode(Index_Pin, INPUT);
   attachInterrupt(digitalPinToInterrupt(A_Pin), fA, RISING);
   //attachInterrupt(digitalPinToInterrupt(B_Pin), fB, RISING);
   digitalWrite(Index_Pin, HIGH);
   pinMode(CSn_Pin, OUTPUT);
   pinMode(CLK_Pin, OUTPUT);
   pinMode(DO_Pin, INPUT);
   digitalWrite(CSn_Pin, HIGH);
   digitalWrite(CLK_Pin, HIGH);

   Serial.begin(4800);

   cli();
   PCICR = 1;
   PCMSK0 = Pow2[Index_Pin - 8];
   sei();
 }

 void loop(){
   //delay(1);
   digitalWrite(CSn_Pin, LOW);
   //delay(1);

   Position = 0;
   for(int z0 = 0; z0 < 12; z0++){
  digitalWrite(CLK_Pin, LOW);
  //delay(1);
  digitalWrite(CLK_Pin, HIGH);
  //delay(1);
  Bit = digitalRead(DO_Pin);
  Position += Bit * Pow2[11 - z0];
   }

   digitalWrite(CLK_Pin, LOW); //delay(1);
   digitalWrite(CLK_Pin, HIGH); //delay(1);
   OCF = digitalRead(DO_Pin);
   digitalWrite(CLK_Pin, LOW); //delay(1);
   digitalWrite(CLK_Pin, HIGH); //delay(1);
   COF = digitalRead(DO_Pin);
   digitalWrite(CLK_Pin, LOW); //delay(1);
   digitalWrite(CLK_Pin, HIGH); //delay(1);
   LIN = digitalRead(DO_Pin);
   digitalWrite(CLK_Pin, LOW); //delay(1);
   digitalWrite(CLK_Pin, HIGH); //delay(1);
   MagINC = digitalRead(DO_Pin);
   digitalWrite(CLK_Pin, LOW); //delay(1);
   digitalWrite(CLK_Pin, HIGH); //delay(1);
   MagDEC = digitalRead(DO_Pin);
   digitalWrite(CLK_Pin, LOW); //delay(1);
   digitalWrite(CLK_Pin, HIGH); //delay(1);
   EvenPAR = digitalRead(DO_Pin);

   digitalWrite(CSn_Pin, HIGH);

   if(LIN == HIGH || MagINC == HIGH || MagDEC == HIGH) Error = true;

   Serial.print(Position);
   Serial.print(", ");
   Serial.print(OCF);
   Serial.print(", ");
   Serial.print(COF);
   Serial.print(", ");
   Serial.print(LIN);
   Serial.print(", ");
   Serial.print(MagINC);
   Serial.print(", ");
   Serial.print(MagDEC);
   Serial.print(", ");
   Serial.print(EvenPAR);
   Serial.print(", ");

   Serial.print(ACount);
   Serial.print(", ");
   Serial.print(Left);
   Serial.print(", ");
   //Serial.print(BCount);
   //Serial.print(", ");
   Serial.print(IndexCount);
   Serial.print(", ");
   Serial.println(Error);
 }

Update 2: Maybe the problem comes from the hysteresis described in section 7.2? If the change of direction is directly at the index pulse, wouldn't I get a false direction of movement?

title: Two outputs: which one "leads" the other?

Answers: 1

body:
Using ad hoc methods to handle quadrature inputs (ie, the kind of signals you have) can lead to missed pulses and accumulated error.  However, it's possible to handle fairly fast quadrature input pulse trains using pin-change-interrupts on an Arduino.

In [my answer](https://arduino.stackexchange.com/a/32043/3917) to the question [How to read RPS for fast rotation with status change method in Arduino?](https://arduino.stackexchange.com/q/32037), you will find links to several previous answers that include code to process quadrature inputs at reasonable data rates; for example, *[Reading from a KY-040 rotary encoder with Digispark](https://arduino.stackexchange.com/a/16420/3917)*.

---

*Edit 1, part 1:* Ad hoc methods (such as just checking the state of input B whenever input A has a rising edge), while often simple to implement, can cause extra counts or missing counts.  Extra counts may occur if A bounces and has several rising edges in a short interval.  Missing counts may occur if rising edges of A occur faster than they are handled, particularly if the ad hoc code includes delays to deal with contact bounce.

Typical [finite state machine](https://en.wikipedia.org/wiki/Finite-state_machine) methods for  [handling quadrature inputs](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1458&bih=870&q=quadrature+state+machine&oq=quadrature+state+machine&gs_l=img.3...1609.1609.0.2900.2.2.0.0.0.0.73.73.1.1.0....0...1ac..64.img..1.0.0.0.cOQYO_fL20Q), by contrast, automatically debounce A and B inputs, either by ignoring cases where a set of inputs repeats, or by counting an equal number down and up transitions as bouncing occurs.  See for example the diagrams in [reply #17 in “easy rotary encoder implementation”](http://www.eevblog.com/forum/projects/easy-rotary-encoder-implementation-good-easy-to-implement-code/msg504575/#msg504575) at eevblog.com – from which the first diagram below is taken – and in [Omapl137 linux eqep driver](http://processors.wiki.ti.com/index.php/Omapl137_linux_eqep_driver) at ti.com, where the second diagram is from.  Both those sources provide substantial detail about processing quadrature inputs.

[![eevblog state machine with debounce][1]][1]
[![ti state machine][2]][2]

---

*Edit 1, part 2:* Besides using a correct model of the quadrature process, encoder software should be fast, delay free, and asynchronous to other processing.

Slow handling of events (that is, of changes on encoder inputs) is caused by lengthy code or indirect IO, inter alia.  Slow event handling cannot keep up with as many events per second as fast event handling; if code is really slow, users will notice that they have to turn or move an encoder at a snail's pace to avoid missing menu items or location steps.

Trying to handle events synchronously, eg via polling, also limits the rate at which software processes events.  Unless a processor is quite fast or is dedicated to quadrature input, it is likely to miss occasional transitions on inputs.  Using [interrupts](http://www.gammon.com.au/interrupts) usually is a better choice when dealing with asynchronous transitions like encoder inputs.

By “indirect IO” I mean use of functions like [`digitalRead()`](https://www.arduino.cc/en/Reference/DigitalRead) and [`attachInterrupt()`](https://www.arduino.cc/en/Reference/AttachInterrupt) which result in massive overhead for IO processing.

`digitalRead()` takes between 3 and 4 μs to read one bit of input.  Directly reading a port takes one instruction cycle, 62.5 ns (1/16 μs) on a typical Uno or Nano.  If two encoder inputs are wired to the same port, one port read is enough, vs two `digitalRead()` calls.  Note, this comparison assumes encoder pin numbers are known at compile time, that the target MCU is known, etc.  With direct port IO, the programmer is responsible for making the software conform to the MCU, instead of having `digitalRead()` taking care of details like which port bit corresponds to which Arduino digital input.

`attachInterrupt()` adds about 5 μs of overhead to interrupt processing.  [See the section  “How long does it take to execute an ISR?” in [Nick Gammon's *interrupts*](http://www.gammon.com.au/interrupts) page.]  This is on top of about 2.6 μs of ordinary software overhead (for interrupts on Arduino Uno, Nano, etc.).

Note, some of the example code in previous answers uses `attachInterrupt()` and `digitalRead()`, but is concise enough to still get reasonable input rates.  Using those functions leads to better code readability and portability.   However, for faster input rates, you might use code as shown below.  This code probably could be improved (shortened, made faster, made more clear) but anyhow functions ok for up to a few hundred counts per second.  To adapt this code for other input pins, replace `abNew = PINC & 3;` by code to set the low two bits of `abNew` equal to the input bits; and adapt `setup_rotocoder()` accordingly.  See (eg) [Arduino Pin Change Interrupts](https://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/) and [Simple Pin Change Interrupt on all pins](http://playground.arduino.cc/Main/PinChangeInterrupt) for further information about setting up pin change interrupts.

    // The following three vars should be visible to loop(), which
    // can find out if an encoder changed by testing rotoInt.
    static   byte roABold;          // A,B states for rotor
    volatile uint16_t roCount;      // current rotary count
    volatile byte rotoInt;          // Rotary-interrupt flag (change flag)

    // jiw (c) 2015  Offered without warranty under GPL v3 terms as at http://www.gnu.org/licenses/gpl.html

    ISR(PCINT1_vect) { // This plus Arduino overhead of 2.6 us probably takes ca 5 us total per interrupt
      enum { upMask = 0x66, downMask = 0x99 };// up & down are complements
      byte roABnew = PINC & 3; // Read pins  14, 15, which are A0, A1
      byte criterion = roABnew ^ roABold;
      if (criterion==1 || criterion==2) {
        if (upMask & (1 << (2*roABold + roABnew/2))) // Embeds state transition rules
          ++roCount;
        else --roCount;             // upMask = ~downMask
      }
      roABold = roABnew;            // Save new state
      rotoInt = 1;                  // Say something happened
    }

    // For rotary encoder initialization, in setup(), say:   setup_rotocoder();
    void setup_rotocoder() {
      rotoInt = roABold = 0;
      roCount = 32768;              // Start with a middle count
      pinMode(A0, INPUT_PULLUP);    // pin 14, A0, PC0, for pin-change interrupt
      pinMode(A1, INPUT_PULLUP);    // pin 15, A1, PC1, for pin-change interrupt
      PCMSK1 |= 0x03;
      PCIFR  |= 0x02;             // clear pin-change interrupts if any
      PCICR  |= 0x02;             // enable pin-change interrupts
    }

  [1]: https://i.stack.imgur.com/DViQi.png
  [2]: https://i.stack.imgur.com/j16tw.jpg


body:
I manage to control a brushless motor using a 4x3 keypad. I am able to key in the speed (using a servo value of 0-180) and the time for the motor to run. Besides that, while the motor spins according to the speed and time entered, I am using an Infrared Obstacle Avoidance Sensor module to calculate the RPM. However, I cannot seem to be getting the RPM to display on the LCD screen. I copy-pasted the Infrared Obstacle Avoidance Sensor module code from https://www.instructables.com/id/Simple-Motor-Speed-Tester-Tachometer/.

I have tried the code from the link on my sensor and it works very well. However, when I incorporate the IR coding from the link with my speed and time control coding, the code from the link does not seem to work.

So, why does the code from the link cannot function when I combine it with my code? How do I resolve this problem?

Below is the code, I am hoping for any guidance and advice from the experts. Thanks in advance. Any suggestion or changes are welcome.

    #include <Keypad.h>
    #include <Wire.h>  // Comes with Arduino IDE
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>
    Servo myservo;
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    // Set the LCD I2C address

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns
    char keys[ROWS][COLS] =
    {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
    byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const int dataIN = 2; //IR sensor INPUT
    unsigned long prevmillis; // To store time
    unsigned long duration; // To store time difference
    int rpm; // RPM value
    boolean currentstate; // Current state of IR input scan
    boolean prevstate; // State of IR sensor in previous scan

    void setup() {
      pinMode(dataIN,INPUT);
      Serial.begin(9600);
      lcd.begin(20,4);
      myservo.attach(11);
      prevmillis = 0;
      prevstate = LOW;
      lcd.setCursor(4,1);
      lcd.print("SPIN COATER");
      lcd.setCursor(6,2);
      lcd.print("MACHINE");
      delay(5000);
      lcd.clear();
      lcd.setCursor(3,1);
      lcd.print("S = speed(sv)");
      lcd.setCursor(3,2);
      lcd.print("T = time(sec)");
      delay(5000);
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Servo value (sv):");
      lcd.setCursor (3,2);
      lcd.print("Between 103-180");
      delay (10000);
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("S=");
      lcd.setCursor(0,1);
      lcd.print("T=");
      lcd.setCursor(0,2);
      lcd.print("S=");
      lcd.setCursor(0,3);
      lcd.print("T=");
      lcd.setCursor(10,0);
      lcd.print("S=");
      lcd.setCursor(10,1);
      lcd.print("T=");
      lcd.setCursor(10,2);
      lcd.print("RPM");
    }

    void loop() {
      // RPM Measurement
      currentstate = digitalRead(dataIN); // Read IR sensor state
      if(prevstate != currentstate) {
        // If there is change in input
        if(currentstate == HIGH) {
          // If input only changes from LOW to HIGH
          duration = ( micros() - prevmillis );
          // Time difference between revolution in microsecond
          rpm = (60000000/duration);
          // rpm = (1/ time millis)*1000*1000*60;
          prevmillis = micros();
          // store time for nect revolution calculation
        }
      }
      prevstate = currentstate;
      // store this scan (prev scan) data for next scan
      lcd.setCursor(10,3);
      lcd.print(rpm);
      int stage1speed = getTheNumber();
      lcd.setCursor(2,0);
      lcd.print(stage1speed);
      lcd.print("sv");
      int stage1time = getTheNumber();
      lcd.setCursor(2,1);
      lcd.print(stage1time);
      lcd.print("sec");
      int stage2speed = getTheNumber();
      lcd.setCursor(2,2);
      lcd.print(stage2speed);
      lcd.print("sv");
      int stage2time = getTheNumber();
      lcd.setCursor(2,3);
      lcd.print(stage2time);
      lcd.print("sec");
      int stage3speed = getTheNumber();
      lcd.setCursor(12,0);
      lcd.print(stage3speed);
      lcd.print("sv");
      int stage3time = getTheNumber();
      lcd.setCursor(12,1);
      lcd.print(stage3time);
      lcd.print("sec");
      if (stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage2speed > 0 && stage2time > 0) {
        myservo.write(stage1speed);
        delay(stage1time*1000);
        myservo.write(stage2speed);
        delay(stage2time*1000);
        myservo.write(stage3speed);
        delay(stage3time*1000);
        myservo.write(0);
        stage1speed = 0;
        stage1time = 0;
        stage2speed = 0;
        stage2time =0;
        stage3speed = 0;
        stage3time =0;
      }
    }

    int getTheNumber() {
      char buffer[4];
      // Input up to 3 numbers until we find a * or #
      int i=0;
      while (1) {
        char key = keypad.getKey();
        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3) {
          buffer[i] = key;
          i++;
        } else if ('#' == key && i > 0) {
          // If it's a * or #, end
          // Null terminate
          buffer[i] = 0;
          int value = atoi(buffer); // Convert to an integer
          break;
        }
      }
      return atoi(buffer);
    }

title: Why isn't the RPM displayed on the LCD?

Answers: 1

body:
What LCD library are you using? Based on what is online, the *LiquidCrystal_I2C.h* instantiates with 3 arguments (+ 1 optional):

> LiquidCrystal_I2C(uint8_t lcd_addr, uint8_t lcd_cols, uint8_t
> lcd_rows, uint8_t charsize = LCD_5x8DOTS);

So an example of creating an object of it would look like this:

> LiquidCrystal_I2C(0x3F,16,2);

Whereas for *LiquidCrystal.h*, it instantiates with either 6, 7, 11 or 10 arguments:

> LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


body:
I am doing an aquarium light sunrise/sunset. Till now programming wise I only did the sunrise. After running the code the light starts to rise up fine, than  at full brightness, it turns off. I want to keep it on after it reaches the 100% pwm and than starts decreasing when it's time to get off. Any help on how to leave the pwm at 100% and than starts to dim when it's time to turn off? I am still new to coding arduino, so explanation need to be for a beginner :P Thanks before hand.

    #include <DS3231.h>

    //Set Variables
    int fadeTime = 15; //Fade Time
    int onHour = 12; //Light On Hour
    int onMin = 00; //Light On Minute
    int offHour = 19; //Light On Hour
    int offMin = 00; //Light On Minute
    int led = 9; //Set pinout with with PWM

    DS3231  rtc(SDA, SCL);
    Time t;
    void start();

    void setup()
    {
      pinMode(led, OUTPUT);
      rtc.begin();
    }

    void loop()
    {
      t = rtc.getTime();

      // Send Day-of-Week
      Serial.print(rtc.getDOWStr());
      Serial.print(" ");

      // Send date
      Serial.print(rtc.getDateStr());
      Serial.print(" -- ");

      // Send time
      Serial.println(rtc.getTimeStr());

      if (t.hour == onHour && t.min == onMin) //Check Time
      {
        start();
      }

    }

    void start()
    {
      // Fade script
      for (int i = 0 ; i <= 255; i++)
      {
        analogWrite(led, i);
        delay(((fadeTime * 60000)/306));
      }

    }

title: Arduino leave PWM on

Answers: 1

body:
Why not create a global brightness variable (e.g. *cBrightness*) so that you can adjust the brightness accordingly when the time comes? With a global variable, you can still maintain the brightness of the LED even after it exits the *start()* function.

For the *start()* function, you can include one argument (*int/bool* type variable) in the function to determine when to perform the brightening or dimming of the light depending on the RTC timing.

    void start(int st)
    {
      if(st==0)
      {
         //Brightness decrement function here
      }else if(st==1)
      {
         //Brightness increment function here
      }
    }

For the brightness decrement function, it is the opposite of the increment function:

    for (int i = 255 ; i >= 0; i--)
    {
        analogWrite(led, i);
        delay(((fadeTime * 60000)/306));
    }

To summarize, the code could look something like this:

    #include <DS3231.h>

    //Set Variables
    int fadeTime = 15; //Fade Time
    int onHour = 12; //Light On Hour
    int onMin = 00; //Light On Minute
    int offHour = 19; //Light On Hour
    int offMin = 00; //Light On Minute
    int led = 9; //Set pinout with with PWM
    int cBrightness = 0;  //Current brightness

    DS3231  rtc(SDA, SCL);
    Time t;
    void start(int st);

    void setup()
    {
      pinMode(led, OUTPUT);
      rtc.begin();
    }

    void loop()
    {
      t = rtc.getTime();

      // Send Day-of-Week
      Serial.print(rtc.getDOWStr());
      Serial.print(" ");

      // Send date
      Serial.print(rtc.getDateStr());
      Serial.print(" -- ");

      // Send time
      Serial.println(rtc.getTimeStr());

      if (t.hour == onHour && t.min == onMin) //Check Time
      {
        start(1);
      }else if (t.hour == offHour && t.min == offMin)
      {
        start(0);
      }
      //Maintains brightness
      analogWrite(led, cBrightness);

    }

    void start(int st)
    {
      if(st==0)     //Will decrement in brightness
      {
       for (int i = 255 ; i >= 0; i--)
       {
        analogWrite(led, i);
        delay(((fadeTime * 60000)/306));
       }
       cBrightness = 0;

      }else if(st==1)   //Will increment in brightness
      {
       for (int i = 0 ; i <= 255; i++)
       {
        analogWrite(led, i);
        delay(((fadeTime * 60000)/306));
       }
      cBrightness = 255;
      }
    }


body:
I am quite new to Arduino and DigiSparkKeyboard so I don't know much about them. I am trying to get by DigiSpark to open CMD in administrator mode but it just doesn't work. I know that I need to get it to press control, shift and enter at the same time in order for it to run as administrator but it doesn't work.
At the moment my code looks like:

    #include "DigiKeyboard.h"
    #define MOD_SHIFT_LEFT      (1<<1)  //00000010
    #define MOD_GUI_LEFT        (1<<3)  //00001000
    #define MOD_CONTROL_LEFT    1
    #define KEY_ENTER   40
    #define KEY_C       6
    #define KEY_M       16
    #define KEY_D       7
    void setup() {
      // put your setup code here, to run once:
      DigiKeyboard.update();
      DigiKeyboard.sendKeyStroke(0);
      DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
      DigiKeyboard.delay(1000);
      DigiKeyboard.sendKeyStroke(KEY_C);
      DigiKeyboard.sendKeyStroke(KEY_M);
      DigiKeyboard.sendKeyStroke(KEY_D);
      DigiKeyboard.delay(1000);
      DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER);
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

title: Opening a program in administrator with Arduino (DigiSpark/DigiSparkKeyboard)

Answers: 3

body:
Looking at the code, the first argument should be the key, and the second the modifiers. So `DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER); ` should become:

    DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT + MOD_SHIFT_LEFT);`

body: Please use DigiKeyboard.print(cmd);

body:
You can use this code :

Explanation of the code

Opens the side menu, then searches for CMD, then right-click on it to open it as administrator
A window will appear Open as administrator Yes or No
It will go to the Yes button

```
  DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
  DigiKeyboard.delay(1500);
  DigiKeyboard.print("c;d");
  DigiKeyboard.delay(1500);
  DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT | MOD_SHIFT_LEFT);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(0);
  DigiKeyboard.sendKeyStroke(KEY_ARROW_LEFT);
  DigiKeyboard.delay(500);
  DigiKeyboard.sendKeyStroke(KEY_ENTER);

```


body:
When uploading my sketch to my Genuino Micro with the Arduino IDE, everything works perfectly. This is the command issued:

    C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/bin/avrdude
    -CC:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf
    -v -patmega32u4 -cavr109 -PCOM10 -b57600 -D
    -Uflash:w:C:\Users\<user>\AppData\Local\Temp\arduino_build_31080/KeyboardBase.ino.hex:i

All just working like it should (except that the com-port selected is actually COM6, not COM10).

But, if I try to use that exact same command from the command line, avrdude gets stuck for minutes and the arduino is still executing the sketch I've put on it.

    C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/bin/avrdude
    -CC:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf
    -v -patmega32u4 -cavr109 -PCOM6 -b57600 -D
    -Uflash:w:C:\Users\<user>\AppData\Local\Temp\arduino_build_31080/KeyboardBase.ino.hex:i

    avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf"

             Using Port                    : COM6
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .^C

avrdude needs to be run from cmd because I'm building a sketch with partly modified libraries, so it's built and uploaded manually with `make`.

I already tried running cmd as administrator, using `-v -v` to get more info, and changing the baud-rate, plugging the Arduino into a different USB port and restarting my machine (the same problem occurred yesterday but I didn't manage to fix it) none of that helped. What else can I try?

title: Upload of sketch with avrdude stuck only outside of IDE

Answers: 1

body:
@per1234 was correct:

> Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it

*From [Arduino.cc][1]*

In practise, this means that avrdude first has to be executed like so:

    $ avrdude -patmega32u4 -cavr109 -PCOM6 -b1200

Where `COM6` is the same serial port the arduino is being displayed on in the Arduino IDE. The exit code of this will not be 0 and display a lot of error messages (even with `-q -q`), but it does exactly what it should.

After a short delay (in a makefile, use `sleep 1`), the Arduino will reconnect, ready to be programmed. That's when the actual programming command has to be issued:

    $ avrdude -v -patmega32u4 -cavr109 -PCOM10 -b57600 -D -Uflash:w:mysketch.ino.hex:i

Notice that the serial port is now a different one! That's why the Arduino IDE actively searches for a new Arduino instead of using the same serial port set in the "Tools" menu, as I pointed out in my question.

  [1]: https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro#toc12


body:
I need some help with programming Arduino with EMG signals to control the solenoid pressure valve.
I wrote some program which is setting high and low state on the output pin, but it's not working properly.
First I create a plot to observe the signal level. And the plot looks like in the picture which I attached.

The basics concept of program is setting the high signal on the output when I flex muscles and when I relax the muscle it's should write low state on the output. My idea was based on triggering the on-off signals at the moment when the muscle is flexed, the value of signal is above 600 (now the diode should be ON and stay in ON state) and it drops and when I relax muscles the value rises once again to value around 600 more or less (now the diode should be OFF) and drops under 100.

    const int ledPin=13;

    const int sensorPin= 0;

    int level;

    const int threshold1=400;

    const int threshold2 =500;

    void setup() {

        pinMode (ledPin, OUTPUT);

        pinMode (sensorPin, INPUT);

        Serial.begin(9600);
        }

    void loop(){

        level= analogRead(sensorPin);

        if (level > threshold1){

        digitalWrite(ledPin, HIGH);

        if (level > threshold2)

        digitalWrite(ledPin, LOW);

        }

I wrote new code, but I still have problems with proper sending of an ON and OFF     signal to the output.

When I flex the muscle I have high state on the output causing by first peak (LED is ON) but when I relax the muscle the second peak won't set the low state on the output. But when I flex the muscle once again the output change state to low and the diode is OFF. Do you have any suggestions what part of the code do I need to improve?

Here's the code:

    const int ledPin=13;

    const int sensorPin= 0;

    int level;

    int flex= 0;

    int PreviousState = 501;

    const int threshold1=600;

    void setup() {

        pinMode (ledPin, OUTPUT);

        pinMode (sensorPin, INPUT);

        Serial.begin(9600);
    }

    void loop() {

        level= analogRead(sensorPin);

              if (level > threshold1 && PreviousState < threshold1){

              {

                flex =!flex;

              }

              if (flex == 1)
              {

                digitalWrite(ledPin, HIGH);

              }

              else

              {
                digitalWrite(ledPin, LOW);

              }

              PreviousState = level;

            }

        }

    }

[![the state of muscle funcionality - signal from muscle ][1]][1]

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

title: EMG control of solenoid valve

Answers: 2

body:
I see this problem more profound than just some if and else. As you may observe, there may be two peaks in flex and always there is one in relax.

What makes difference is the width of the pulse: flex is wide and relax is narrow.

You should detect the width. It can be measured by amount of times, when you detect a value in input that is over the treshold.

When the amount is less than some value when signal is very low again, you detected a LOW for output and if it is more than some value it means HIGH.

in setup

    unsigned int times = 0;
    unsigned int threshold = xxx;
    unsigned int low = xx;
    unsigned int high = yyy;

    ...

in loop

    ...
    if (level > high) {
          times = times + 1;
    } else if (level < low) {
         if (times > threshold) {
              digitalWrite(ledPin, HIGH);
         } else {
              digitalWrite(ledPin, LOW);
         }
         times = 0;
    }

body:
I'd use a https://en.wikipedia.org/wiki/CUSUM to filter the level data and track the idle, flexing, flexed, relaxing states and transitions separately:

    ...

    int state = 0 ; // idle >> flexing >>flexed >> relaxing
    long int cumsum = 0;

    void loop() {
      level= analogRead(sensorPin);
      cumsum=max(0,cumsum+level-threshold);

      switch(state) {
      case 0 : // idle
          if (cumsum > 50*4) {state = 1 ;  // wait for long pulse
             flex =1;
             digitalWrite(ledPin, HIGH);
          }
          break;
      case 1 : // flexing
          if (cumsum ==0 ) state = 2 ;
          break;
      case 2 : // flexed
          if (cumsum > 50*2 ) state = 3 ;  // wait for shorter pulse
          break;
      case 3 : // relaxing
          if (cumsum == 0 ) {
            state = 0;
            flex = 0;
            digitalWrite(ledPin, LOW);
          }
          break;
      }
    }

You might want to add an extra cumsum filter with a lower threshhold to potentially transition out of flexed if there is an exceptional period of low level.  e.g.:

    ...

    long int cumsum2 = 0;
    ...
    cumsum2 = max(0,cumsum2+level-200);
    ...

    case 2:
       ...
       if (cumsum2 == 0) state=3; // missed a relaxing signal
       ...


body: Can I use the TX/RX on pins 0, 1 (to a serial slave device) while also having the USB port dedicated PC communication?

title: Can Arduino Leonardo use USB port and RX TX serial pins at the same time?

Answers: 1

body: 32u4 is multi-serial uC. USB connection works on default serial communication which can be used via **Serial**.print("somevalue"). On the other hand if you want to use RX/TX on pins 0, 1 which are actually RXD1 and TXD1. So, if you use **Serial1**.print("somevalue"). So the answer is a yes. You can use USB and RX/TX (hardware serial) at the same time.


body:
I am planning to make a POV (persistence of vision) display using ATmega328 with 5 red LEDs for display.
Below are my aims:

- I want to power it with cr2032 coin cell, so power consumption has to be taken care, I am ready to keep single or 2 coin cell in parallel to meet current requirement.

 1. Using 8MHz clock instead of 16MHz can help
  - Does it require separate boot-loader to be installed?
  - During boot-loading do I require to put external 16MHz clock?
  - How to ask controller to use the internal 8MHz clock?
 2. Supply voltage of 3V instead of 5V can also help, and cr2032 gives out 3V
  - What care should I take while using it at 3V?
  - Any mechanism to set the threshold for controller to stop working?

- To reduce the weight of whole circuit so I can rotate the board using small toy motor (I don't have a gear box).
I am planning to control the speed of motor using LM317 voltage regulator as a constant current source.
I will mount the LEDs on straw, keep the controller and the coin cells at the center. (Guessing that will reduce the torque required by the motor as `torque=Force*radius` and weight being at center reduced the radius)

- I am okay, if this circuit works for just few hours OR days.

title: POV using ATmega328 powered with cr2032 cell

Answers: 2

body:
Not exactly an answer, but too big to place into the "comments" area.

**Clock**
For the 8MHz vs 16MHz, you should be able to run your project at 1MHz. Just use a bare AVR MCU with the Internal 8MHz oscillator divided by 8 - search for AVR Fuses. You can program it using an ISP (or and Arduino as ISP)

**Battery**
About the CR2032 or coin-cells in general are not designed to constantly supply current. You can use it for very low currents, up to 2-4mA or in pulses. Otherwise you damage the cell, reducing it's total usable capacity. Maybe have a look on sub AAA batteries instead of coin-cells.

**Motor**
For the motor, have a look on the micro coreless dc motors. They are really tiny and should offer an excellent efficiency. [Motor example][1]

**Motor Driver**
Not sure about the LM317. You don't want any kind of regulation as it would waste energy. To drive the motor a small Mosfet should do the trick. You can control the Mosfet using PWM, which will define the motor speed. Don't forget to implement some kind of rotary encoder to count the motor RPM so you can precise speed control - a tiny magnet and a hall-sensor should be enough.

  [1]: http://www.ebay.com.au/itm/10pcs-4mm-Micro-DC-3V-70000RPM-high-Speed-Hollow-Cup-Coreless-Motor-RC-Drone-/331995488567

body:
**1.** You said you wanted to use your Atmega328 at minimal power usage so you asked how can I use my Atmega at 8mhz. So for doing that first you need to [bootloader your Atmega with a 8mhz Bootloader](https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard) so that it could work with its internal 8mhz source.

**2.** You said you wanted to use coin cells. But coin cells provide a very low amount of power and they are used for small projects. So instead you could use Lithium Ion batteries or AAA batteries.

**3.** You said you will probably look forward to use LM317 as motor controller and a small toy DC motor. Well if you would use LM317 i.e. Voltage regulator you would ended up with a lot of power consumed by it. So I would probably say you to use a MOSFET as Talk said. Now for the motor it's ok upto when you are okay with it. Now I can't say you specifically which motor you looking for as there are many motors with many shapes and features. And that could be done by just searching on Google.


body:
I am trying to create a software serial connection between Arduino Uno & Adafruit Feather M0 Bluefruit LE.

I am getting the following error in the M0 sketch:

    Arduino: 1.8.1 (Windows 10), Board: "Adafruit Feather M0"

    atcommand:60: error: 'SoftwareSerial' does not name a type

     SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

     ^

    atcommand:62: error: 'bluefruitSS' was not declared in this scope

     Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,

                                   ^

    exit status 1
    'SoftwareSerial' does not name a type

Here are the modifications I did to the atcommand sketch (in Adafruit BluefruitLE nRF51 library) before uploading to the M0:

    #include <Arduino.h>
    #include <SPI.h>
    #if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
      #include <SoftwareSerial.h>
    #endif

    #include "Adafruit_BLE.h"
    #include "Adafruit_BluefruitLE_SPI.h"
    #include "Adafruit_BluefruitLE_UART.h"

    #include "BluefruitConfig.h"

    // Create the bluefruit object, either software serial...uncomment these lines

    SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

    Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,
                          BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);

    /* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */
    // Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);

    /* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */
    //Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

    /* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
    //Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
    //                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
    //                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

I  tried to comment the if statement before `#include <SoftwareSerial.h>`, I got the following error:

    Arduino: 1.8.1 (Windows 10), Board: "Adafruit Feather M0"

    C:\Users\hadeel\AppData\Local\Temp\arduino_modified_sketch_612073\atcommand.ino:18:30: fatal error: SoftwareSerial.h: No such file or directory

       #include "SoftwareSerial.h"

                                  ^

    compilation terminated.

    exit status 1
    Error compiling for board Adafruit Feather M0.

What is the problem?

title: 'SoftwareSerial' does not name a type in Adafruit Feather M0 Bluefruit LE

Answers: 0


body:
I want to Control Android Mobile Camera shutter using Arduino over Bluetooth. So i can click photos using arduino.

I have HC-05 Bluetooth Module and **Arduino Nano/Arduino leonardo**.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/3uH4h.jpg
The Connection as shown in figure.

The Android mobile successfully connected to Bluetooth Module but i am not found any code to control camera or any button on android mobile.

title: Control Android Camera using Arduino over Bluetooth

Answers: 1

body:
I am trying out [Camera Pro][1]. It allows shutter control on Android over Bluetooth. I just got an Uno R3 and and HC-05 so I have not wired it up to try it.

There are example sketch and detailed docs [here][2].

  [1]: https://play.google.com/store/apps/details?id=com.teapps.camerapro&hl=en
  [2]: http://www.tequnique.com/camerapro.php


body:
I want to connect a TGAM module (detecting brainwaves) to an Arduino Uno. I know little of electronics, can someone advise me? To which pin of the Arduino should I connect the TGAM? How to get the right electrical supply from the Arduino to the TGAM? Here is data about the TGAM module: http://www.seeedstudio.com/document/pdf/TGAM Datasheet.pdf

The R pin on the TGAM module is providing digital data as an asynchronous serial stream of bytes: http://developer.neurosky.com/docs/doku.php?id=thinkgear_communications_protocol

title: Arduino connection to brainwave analyzing module

Answers: 1

body:
As per the datasheet you provided, it is quite straight forward.
It can be connected to RX (pin 0) and TX (pin 0) pins of the Arduino Uno.
But, the pins have to be crossed;

Arduino RX (0) <> TGAM T (TX)

Arduino TX (1) <> TGAM R (RX)

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

Good luck.


body: If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?

title: Can an interrupt function call a regular function?

Answers: 4

body:
Yes, you can. You just have to make sure your function is [reentrant][].
If it accesses no memory beyond its parameters and (non `static`) local
variables, you should be fine. If it accesses global variables, hardware
registers, or `static` locals, it is unlikely to be, and only detailed
analysis will tell you for sure.

Beware also of the library functions you call: some of them are not
themselves reentrant and should therefore be avoided. See for example
[the manual of `strtok()`][strtok], which explicitly addresses the
reentrancy problem.

[reentrant]: https://en.wikipedia.org/wiki/Reentrancy_(computing)
[strtok]: http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#ga6ace85338eafe22a0ff52c00eb9779b8

body:
Yes you may.

Yet keep the function in question short, you don't want to spend too much time in interruption.

Another way is to set up a variable state in the interruption, and call the function in question in the normal cycle when the variable is in the desired state.

body:
You can do that, but it will increase the complexity of your program.
Often when entering an interrupt service routine, the first thing you do is disabling interrupts - the make sure the callback completes reliably.
This is something you will have to consider if you want to use the same routine for a 'regular' scenario

body:
> If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?

The right answer is yes and no.

The issue here is reentrancy : whether a function can be interrupted while it's being called by another. Not all functions are re entrant so the safer assumption is that they are.

Another issue with calling a function from within the isr is overhead.

The typical solutions are:

1. Make sure that the function called from the isr is re entrant.
2. The simplest way to assure that is to a. Limit your calling of that from the isr. Or b. Create two versions of the same function. And call them separately.

Btw, I routinely call functions from within isr. In my case through function pointers.


body:
I'm working on a project that uses an Atmega328p as the primary controller. I am using the Arduino libraries for programming.

I currently have an SD card in the project. I've done quite a bit of studying on current consumption of SD card and it turns out they're quite power hungry during read/write operations. However, when an SD card is not being interacted with, I believe it should go into an idle mode in which the power consumption is much less.

Now I've noticed that when I start using the Arduino SD library, specifically SD.begin(), the current consumed is approximately 20mA. This is a continuous 20mA without any read/write operations being used. Simply selecting SD.begin().

So I've got a few questions:
- Does this seem high for an SD card that is essentially doing nothing?
- What exactly does SD.begin do? I assume it configures some pins but does it do anything else? If it's just set up, shouldn't it 'set up' and be done? Why the continuous high current?

title: SD.begin() causes SD card to pull 20mA in idle mode. Seem high?

Answers: 1

body:
You should look [here][1] and see if it helps. Basically:

 - Ensure that `SD.begin()` returns `true` because the card won't sleep if not properly initialized.
 - I don't know if it's been fixed but the `SD` library may still have a bug that prevents it from letting SD cards sleep. So try the `SdFat` library instead.
 - Try another SD card, from a reliable source.
 - Connect external pullups or use the Arduino's internal pull-ups with the MOSI, SCK and SS pins so they don't float.

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


body: I'm working on the wifi uploading to Arduino over ESP shield (eg. ESP-12). When uploading over USB Arduino IDE resets the boards first (using DTR) and then interacts with the bootloader. How can i control ESP's GPIOs to reset Arduino board with ESP?

title: How to reset Arduino with ESP shield?

Answers: 0


body:
Background:

A few days ago I received a 23LC1024 1Mbit SRAM chip, which works like a charm.
However, before I ordered that one, I ordered a LP621024D-70LL which also is a 1 Mbit SRAM but in DIP32 format, meaning LOTS of pins.

Now I made a breadboard setup with 3 shift registers 74HC595 to be able to set the address (tested with LEDs but should work).

However, when trying use a shift register for the data which can be read or write, I don't think I can use a 74HC595 since it is only for output. However, I also don't think a 74HC165 (shift in register) would work (if I had one).

Questions:

1. What kind of shift register would I need, one that can do both input and output? I read about I2C registers but that seems to be a bit of overkill.

2. I only have 74HC595 shift registers for setting the address, would that slow down SRAM? I mean are there faster registers? Not that I want to buy it, but just curious.

Here is a picture of a working LP621024D-70LL ... too bad the chip is barely visible , on the left are 2 74HC595s and right are also 2 (right one not used), these 3 shift registers take care of the address (17 bits -> 3 bytes). The SRAM itself is hidden under the center of the cables.

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

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

title: What shift register would I need for input OR output?

Answers: 2

body:
since you already have input, use an [74HC165](http://assets.nexperia.com/documents/data-sheet/74HC_HCT165.pdf)  8-bit parallel-in/serial out shift register. They are [cheap](http://www.ebay.com/itm/141975802074).

another cheap option with I/O is an expander like the [PCF8574](http://www.ti.com/lit/ds/symlink/pcf8574.pdf), which are [almost cheap](http://www.ebay.com/itm/141975859541)

body:
From the [web page about the 23LC1024](http://www.microchip.com/wwwproducts/en/23LC1024):

>  The memory is accessed via a simple Serial Peripheral Interface (SPI) compatible serial bus.

Using the SPI hardware on your Uno will be a *lot* faster than using software-based shifting. See [my page about SPI](http://www.gammon.com.au/spi).


body:
I'm working on creating a circuit where I'm trying to have the ability to switch multiple strands of [LED rope][1] on and off at a time using an Arduino and a [multiplexer][2].

With my current configuration, I have the a circuit and a sketch that will cycle through the various LED rope strands, turning them on and off.

What I'm not sure how to do is modify my sketch / circuit so that I can turn ALL of the rope strands on and off, as well as individually.

Below is my current Arduino sketch:

    //Mux control pins
    int s0 = 8;
    int s1 = 9;
    int s2 = 10;
    int s3 = 11;

    //Mux in "SIG" pin
    int SIG_pin = 3;

    int testValue = 255;

    void setup(){
      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);

      pinMode(SIG_pin, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);

    }

    void loop(){

      //Loop through and read all 16 values
      //Reports back Value at channel 6 is: 346
      for(int i = 0; i < 9 ; i ++){
        delay(1000);
        writeMux(i);
      }
    }

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3};

      int muxChannel[10][4]={
        {0,0,0,0}, //channel 0
        {1,0,0,0}, //channel 1
        {0,1,0,0}, //channel 2
        {1,1,0,0}, //channel 3
        {0,0,1,0}, //channel 4
        {1,0,1,0}, //channel 5
        {0,1,1,0}, //channel 6
        {1,1,1,0}, //channel 7
        {0,0,0,1}, //channel 8
        {1,0,0,1}, //channel 9
        {0,1,0,1}, //channel 10
        {1,1,0,1}, //channel 11
        {0,0,1,1}, //channel 12
        {1,0,1,1}, //channel 13
        {0,1,1,1}, //channel 14
        {1,1,1,1}  //channel 15
      };

      //loop through the 4 sig
      for(int i = 0; i < 4; i ++){
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }

      //read the value at the SIG pin
      analogWrite(testValue, SIG_pin);

      //return the value
      return 0;
    }

I'm using two multiplexers to control multiple rope strands. Here's roughly what that looks like:

[![enter image description here][3]][3]

I'm still a bit new to electronics prototyping (coming from software development); so I'm not sure if what I want to do is possible with a multiplexer

Happy to start offer a bounty to a helpful answer.

Thank you

  [1]: https://www.adafruit.com/products/2440
  [2]: http://bildr.org/2011/02/cd74hc4067-arduino/
  [3]: https://i.stack.imgur.com/iOGPn.jpg

title: Working with multiplexers for constant voltage output

Answers: 1

body:
Even I am new to this and I also find it a bit challenging with the available setup and desired output. Though it seems tough, I want you to just try out this code (it is a little modification to the one posted by you) and check whether it matches the expected result.

        //Mux control pins
    #define s0 8;
    #define s1 9;
    #define s2 10;
    #define s3 11;

    //Mux in "SIG" pin
    #define SIG_pin 3;

    #define testValue 255; //maximum value for analogWrite() function

    void setup()
    {
      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);

      pinMode(SIG_pin, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
    }

    void loop()
    {
      //Loop through and read all 16 values
      for(int i = 0; i < 16 ; i ++)
      {
        delay(1000);
        writeMux(i);
      }
    }

    int writeMux(int channel)
    {
      int controlPin[] = {s0, s1, s2, s3};

      int muxChannel[16][4]=
      {
        {0,0,0,0}, //channel 0
        {1,0,0,0}, //channel 1
        {0,1,0,0}, //channel 2
        {1,1,0,0}, //channel 3
        {0,0,1,0}, //channel 4
        {1,0,1,0}, //channel 5
        {0,1,1,0}, //channel 6
        {1,1,1,0}, //channel 7
        {0,0,0,1}, //channel 8
        {1,0,0,1}, //channel 9
        {0,1,0,1}, //channel 10
        {1,1,0,1}, //channel 11
        {0,0,1,1}, //channel 12
        {1,0,1,1}, //channel 13
        {0,1,1,1}, //channel 14
        {1,1,1,1}  //channel 15
      };

      //loop through the 4 sig
      for(int i = 0; i < 4; i ++)
      {
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }

      //read the value at the SIG pin
      for(int i_testValue = 0; i_testValue < testValue; i_testValue++)
      {
     analogWrite(i_testValue, SIG_pin);  //incresing intensity slowly with delay of 100ms
     delay(100);
      }

      //return the value
      return 0;
    }


body:
How can I use delimiter/split serial input in a loop function? I want to use each word from the input and check a database, to check availability.

    #include SoftwareSerial.h>
    #define MAX_WORD_LENGTH 15

    char messageArray[5][MAX_WORD_LENGTH + 1];
    SoftwareSerial BT(10, 11);
    String command = "";
    char message[] = "";

    void setup() {
      BT.begin(9600);
      Serial.begin(9600);
      while (BT.available()) {
        delay(10);
        char c = BT.read();
        command += c;
      }

      if (command.length() > 0) {
        Serial.println(command);
        char message[] = {command};
        for (int i = 0; i < 5; i++) {
          // you can 'reset' the array by writing a null to the first element of each
          messageArray[i][0] = '\0';
        }
        sscanf(message, "%s %s %s %s %s", messageArray[0], messageArray[1], messageArray[2], messageArray[3], messageArray[4]);
        for (int i = 0; i < 5; i++) {
          Serial.println(messageArray[i]);
          delay(1000);
        }
      }
    }

    void loop() {
      for (int i = 0; i < 5; i++) {
        // you can 'reset' the array by writing a null to the first element of each
        messageArray[i][0] = NULL;
      }
      command = "";
    }

Answers: 0


body:
I want to play video from SD card   by using arduino mega 2560 and TFT 3.2" touch screen is it possible ?

if yes please tell me.

thanks in adavance

title: Arduino Video player?

Answers: 1

body:
An ATMEGA2560 has no enough computational power to perform on-the-fly decoding, even at resolutions as low as 160x128 pixels and low frame rates.

The best you can hope for is a 20 fps, 16 bpp, 160x128 pixel video, directly streamed from the SD card, uncompressed (800kB/s), if the MCU runs at 16MHz. Even with such low specs, you'll have to use a trick, to implement a direct peripheral to peripheral transfer.

We made a guide here for the Arduino Uno (i.e. ATMEGA328P), but it should work also for ATMEGA2560 with little modifications: https://next-hack.com/index.php/2017/08/14/how-to-play-a-video-on-arduino-uno-46-playing-a-20-fps-animation-from-sd-card/

On the same link you'll find also the youtube links for a video guide.


body:
**Questions:**

 1. Does the conversion of the ADC count to voltage depend on the actual voltage of the +5 V pin?
 2. If yes, what is the accepted method of getting that voltage from the board?

**Background/Detail:**

I have a circuit in which I have an Arduino Nano (clone) running from a USB connector (from a hub). The job of the Arduino is to measure the voltage on a battery which will drive a second circuit switched on/off by the Nano. For reference it is a battery tester.

[![Test circuit][1]][1]

There is a Nokia 5110 screen which displays the voltage from the very simple sketch below.

    void setup() {
      Serial.begin(9600);
      display.begin();
      // Init done

      // You can change the contrast around to adapt the display
      // for the best viewing!
      display.setContrast(50);

      // Text display tests
      display.setTextSize(1);
      display.setTextColor(BLACK);
    }

    void loop() {
      display.clearDisplay();   // Clears the screen and buffer
      display.setCursor(0,0);
      display.print("Vin=");
      int rawVIN = analogRead(VIN);
      float floatVin = (rawVIN*4.75)/1023.0;
      display.println(floatVin);
      Serial.println(rawVIN);
      display.display();
      delay(1000);
    }

 - I measured the voltage of the battery using a DVM and it is 4.13 V, yet
   the Nano reports 4.35 V.
 - I have a common ground between the battery and Arduino.
 - Because the connection to test the voltage can float, I have a pulldown resistor to stop wild fluctuations (>10 kΩ)

After some investigation I found that the +5 V was actually outputting 4.75 V and changed my sketch from

    float v = (rawVIN*5.0)/1024.0;

to

    float v = (rawVIN*4.75)/1024.0;

and the voltage reading on the Arduino was now correct. I did this not because I understand what I did, I did it because I had a hunch it might change the value to the correct one.

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

title: Does ADC conversion to a voltage rely on the actual value of the +5 V pin?

Answers: 4

body:
The ADC inside the Arduino does not measure voltage, but rather a
voltage _ratio_. Namely the ratio from the voltage at the analog input
to the voltage at the Vref pin.

In the default configuration, the Vref pin is internally tied to the
+5 V line. You can select to use instead [an internal reference as
Vref](https://www.arduino.cc/en/Reference/AnalogReference):

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

    analogReference(INTERNAL);

This reference  is about 1.1 V, and is is quite immune to
fluctuations on the +5 V. The problem is that you cannot measure
voltages higher than the reference.

For your battery tester, if you want some sort of “absolute”
measurement, you could use the internal reference and a voltage divider
to ensure the measured voltage is below 1.1 V.

**Edit**: Another option which does not require a voltage divider is to
use Vcc as a reference to measure _both_ the analog input and the
internal 1.1 V “bandgap“ reference. Measuring the 1.1 V
against Vcc is an indirect way to measure Vcc. This is not supported by
the Arduino core library, but you can do it by programming directly the
control registers of the ADC:

    // Return the supply voltage in volts.
    float read_vcc()
    {
        const float V_BAND_GAP = 1.1;     // typical
        ADMUX  = _BV(REFS0)    // ref = Vcc
               | 14;           // channel 14 is the bandgap reference
        ADCSRA |= _BV(ADSC);   // start conversion
        loop_until_bit_is_clear(ADCSRA, ADSC);  // wait until complete
        return V_BAND_GAP * 1024 / ADC;
    }

Beware that the very first reading after boot may be bogus.

body:
A USB-powered Arduino Nano will have an ADC voltage reference which can't be relied on, due to the +/- 5% tolerance of the incoming USB voltage. On top of that, the Nano has an MBR0520 Schottky diode (D1) that will drop between 0.1 and 0.5 V depending on its own manufacturing tolerances, its temperature, and the current draw of your board.

**What can you do about it?**

The MCU on-board the Arduino Nano is an ATmega328P. The Nano's ADC can scale its analog voltage readings according to several available references (and you can choose the one that suits you better). You can do this through the `analogReference (type)` function, and chose among the following reference `type`s:

>  - DEFAULT: the default analog reference of 5 volts (on 5 V Arduino boards) or 3.3 volts (on 3.3 V Arduino boards)
>  - INTERNAL: An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on
> the Arduino Mega)
[...]
>  - EXTERNAL: the voltage applied to the AREF pin (0 to 5 V only) is used as the reference.

Source: [analogReference][1]

This is the ADC schematic for what's inside the ATmega328 so you can see what's going on there:

[![ATmega328P ADC block][2]][2]

Source: [ATmega328 datasheet][3]

So the straightforward solution is building a weak voltage divider to get the voltage you want to measure below the INTERNAL 1.1 V reference, and then configure `analogReference` accordingly.

The voltage divider needs to be weak (high R values) so you don't draw too much current out of the battery, but not too weak as to be loaded by the ADC input impedance.

**Bonus**

However, if you need a voltage reference higher that the internal 1.1 V bandgap reference of the ATmega328 you're still out of luck. A option would be to use the 3.3 V LDO regulator output from the on-board FT232RL, which is available to you at pin 14 of the header, but I don't think it's reliable either. The [FT232RL datasheet][4] specifies it at 3.0 - 3.6 V (nominal 3.3 V)

So a universal solution would be to build an external voltage reference based on a cheap [TL431][5]. That could give you a reliable reference up to 4.0 - 4.25 V with a +/-1% accuracy.

The external voltage reference circuit would be something as easy as this, (and the TL431 is available in the breadboard friendly TO-92 package!):

[![TL431-based shunt voltage regulator][6]][6]

  [1]: https://www.arduino.cc/en/Reference/analogReference
  [2]: https://i.stack.imgur.com/o2rVt.png
  [3]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [4]: http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf
  [5]: https://www.onsemi.com/pub/Collateral/TL431-D.PDF
  [6]: https://i.stack.imgur.com/vBhnXm.png

body:
> Does the conversion of adc count to voltage depend on the actual voltage of the +5v pin?

yes and no: the adc module cares about Vref, which can be supply via Vdd, internally, or externally.

> If yes what is the accepted method of getting that voltage from the board?

by configuring the adc module. the device datasheet should have registers / bits that need to be set up for that.

body:
I have a [page about the ADC converter on the Atmega328P](http://www.gammon.com.au/adc). Somewhat [down the page](http://www.gammon.com.au/forum/?id=12779&reply=3#reply3) I describe voltage references. You can use the TL431 chip to provide assorted reference voltages, for example 4V:

[![4V voltage reference][1]][1]

By changing the resistors you can get other voltages (it looks like you want around 4.2V).

The output voltage is not influenced by the input voltage (5V in this case).

The linked page describes how you might choose resistor values.

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


body:
The example program is from here: https://www.arduino.cc/en/Reference/attachInterrupt

When I paste in the code and run it, the LED is on all the time (It's supposed to blink):

    const byte ledPin = 13;
    const byte interruptPin = 2;
    volatile byte state = LOW;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(interruptPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
    }

    void loop() {
      digitalWrite(ledPin, state);
    }

    void blink() {
      state = !state;
    }

This is my setup:

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

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

title: Arduino Interrupt example not working

Answers: 3

body:
I think you misunderstood this example: it is not expected to automatically blink!

The LED is suposed to change state at every change of level on pin 2. This supposes that you wired something (e.g. a push button) to pin 2 and that this will make pin 2 change level when something happens (e.g. you press the button or you release it).

On your diagram, there is nothing wired on pin 2, so what you observe is just normal.

If you want to see `attachInterrupt` in practice, then connect pin 2 to a button with the other button lead connected to `GND`.

Then you can observe what happens when you play with that button.

body:
if you want to blink your LED by giving interrupt by push button then you can try this..

    int pushButton = 2;
    int LED = 13;
    volatile bool flag = false;
    volatile byte state = LOW;

    void setup()
    {
        pinMode(pushButton, INPUT_PULLUP);
        pinMode(LED,OUTPUT);
        attachInterrupt(digitalPinToInterrupt(pushButton), &setFlag, FALLING);
    }

    void loop()
    {
        if (flag)
        {
            digitalWrite(LED, state);
            delay(100);
            state = !state;
        }
    }

    void setFlag()
    {
        flag = true;
    }

body:
to expand on my comments to Prayuktibid's code,  here is what I would propose in the loop:

    void loop()
    {
        if (flag)
        {
            //blink the led
            digitalWrite(LED, !digitalRead(LED)); //digitalWrite(LED, state);
            //delay(100);
            //reset the flag
            flag = false;       //state = !state;
        }
    }

the rest remains unchanged.

here is how it works:

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

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

it works as you would expect, without resorting to delays.

edit: btw, the approach shown above (of setting a flag in the isr, processing that flag in the main loop, and resetting the flag after the processing) is a fairly standard way of utilizing interrupts - pretty much the #1 choice unless you have some special reasons to deviate from it.

edit2: to just follow up on that state above (about trying to process the flag in the main loop).

for something this simple, you can also do it in the isr, making the code much closer to your original code:

    void loop()
    {
      digitalWrite(LED, flag);    //digitalWrite(LED, state);
    }

    void setFlag()
    {
        //flip the flag
        flag = !flag;        //flag = true;
    }

the code above produced the same waveform as the code posted earlier.

the lessons learned: there is more than one way to solve a problem, as long as you do it right, :)


body:
Yesterday I played with a SRAM 621024 SRAM 1 Mbit IC and since I use a lot of pins, digitalReads and digitalWrites are needed including shift registers (see [Example][1]

Since it took a long time for reading/writing one byte, I checked for faster ways and found some posts, one of them was using digitalWriteFast:
[Library][2]

However, it did not make any difference... is it possible that the (fast) digitalWrite is already implemented in the default Arduino IDE/library?

  [1]: https://arduino.stackexchange.com/questions/36853/what-shift-register-would-i-need-for-input-or-output/36854#36854
  [2]: https://code.google.com/archive/p/digitalwritefast/

Update: I found out I made a stupid mistake and the library was not used.

Now I get different values:

- Writing 397.880 us per byte
- Reading 386.524 us per byte

Without the fast library:

- Writing 502.152 us per byte
- Reading 483.752 us per byte

Note, there is also a digitalReadFast, but this does not affect the speed.

I did some more testing and found out that a digitalReadFast/digitalWriteFast cost just about 8-12 us, a pinModeFast is 0 us (negligable), however a shiftOut for setting the address cost 120-124 us ... since 3 shifts are needed to set an address, this results in 360-372 us. Subtracting this from the measured times above, writing takes around 25-38 us and reading 15-27us. I possibly can maybe optimize the bit operations a little bit.

However, the end result for using this RAM chip with enough speed is to either change the shift register to a faster one or remove the shift registers at all. This would mean about 30 pins needed for the SRAM only. The conclusion is: better use a 3K256, 23LC1024 or similar variant.

(Note: I tried a ShiftOutFast file), which reduces a shiftout to 36 us but 3 times 36 is still over 100 us, too much to compare to a 3K256/23LC1024 solution.

title: Is the DigitalWriteFast library still needed?

Answers: 1

body:
I just tried to time `digitalWrite()` against direct port access with
the following code:

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

    void setup()
    {
        uint16_t overhead, start, end;

        Serial.begin(9600);
        TCCR1A = 0;
        TCCR1B = 1;

        // Time digitalWrite().
        overhead = 7;
        cli();
        start = TCNT1;
        digitalWrite(2, HIGH);
        end = TCNT1;
        sei();
        Serial.print("digitalWrite(): ");
        Serial.print(end - start - overhead);
        Serial.println(" cycles");

        // Time direct port access.
        overhead = 4;
        cli();
        start = TCNT1;
        PORTD &= ~_BV(PD2);
        end = TCNT1;
        sei();
        Serial.print("direct port access: ");
        Serial.print(end - start - overhead);
        Serial.println(" cycles");
    }

    void loop(){}

The result was:

    digitalWrite(): 78 cycles
    direct port access: 2 cycles

I used an old Arduino core (1.0.5), but that function has not changed
since. You can try with your current core and see.

**PS**: In this program, the correct value for `overhead` can only be
determined by examining the generated assembly. It's a count of the
cycles you are measuring but do not directly belong to the operation you
really want to measure.


body:
 I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.

I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.

So, my question is, how do I implement the elapsed millis as my timer for my spinning motor?
please, guys, help me with this... Just guide me through and give me guidance.

This is my code that I have tried using elapsed millis. Any suggestion is welcome.

    #include <elapsedMillis.h>
    #include <Keypad.h>
    #include <Wire.h>  // Comes with Arduino IDE
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>
    Servo myservo;
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
    elapsedMillis timeElapsed;

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns
    char keys[ROWS][COLS] =
    {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
    byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup()
    {

      Serial.begin(9600);
      lcd.begin(20,4);
      myservo.attach(11);

       lcd.setCursor(0,0);
      lcd.print("S=");
      lcd.setCursor(0,1);
      lcd.print("T=");
      lcd.setCursor(0,2);
      lcd.print("S=");
      lcd.setCursor(0,3);
      lcd.print("T=");
      lcd.setCursor(10,0);
      lcd.print("S=");
      lcd.setCursor(10,1);
      lcd.print("T=");
      lcd.setCursor(10,2);
      lcd.print("RPM");

    }

     void loop()

    {

      int stage1speed = getTheNumber();
      lcd.setCursor(2,0);
      lcd.print(stage1speed);
      lcd.print("sv");
      int stage1time = getTheNumber();
      lcd.setCursor(2,1);
      lcd.print(stage1time);
      lcd.print("sec");

      int stage2speed = getTheNumber();
      lcd.setCursor(2,2);
      lcd.print(stage2speed);
      lcd.print("sv");
      int stage2time = getTheNumber();
      lcd.setCursor(2,3);
      lcd.print(stage2time);
       lcd.print("sec");

      int stage3speed = getTheNumber();
      lcd.setCursor(12,0);
      lcd.print(stage3speed);
      lcd.print("sv");
      int stage3time = getTheNumber();
      lcd.setCursor(12,1);
      lcd.print(stage3time);
      lcd.print("sec");

       if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
            && stage3time > 0 )

       {

        if(timeElapsed <= 1000*stage1time)

        {

         myservo.write(stage1speed);

         }

        if(timeElapsed <= 1000*stage2time)

        {

         myservo.write(stage2speed);

         }

        if(timeElapsed <= 1000*stage3time)

        {

         myservo.write(stage3speed);

         }
      }

    }

    int getTheNumber()
    {
        char buffer[4];
        // Input up to 3 numbers until we find a * or #
        int i=0;
        while (1)
        {
            char key = keypad.getKey();

            // If it's a number AND we have space left, add to our string
            if ('0' <= key && key <= '9' && i < 3)
            {
                buffer[i] = key;
                i++;
            }
            // If it's a * or #, end
            else if ('#' == key && i > 0)
            {
                // Null terminate
                buffer[i] =0;
               int value = atoi(buffer);  // Convert to an integer
                break;
            }

        }
        return atoi(buffer);
        }

title: How to implement elapsed millis as the timer for my motor spinning time?

Answers: 1

body:
`delay()` is only the tip of the iceberg. The problem with `delay()` is
that it is a _blocking_ function: nothing else can be done during the
delay. If you want to control your motor and at the same time be
responsive to the user, you must avoid blocking your program. This means
not only getting rid of `delay()`, but also getting rid of _any blocking
function_.

Here your problem is on `getTheNumber()`. This function blocks until the
user is done typing the number. Try to rewrite it in a non-blocking
fashion. For example, it could return `-1` on every call as long as the
user is not done typing the number. On the first call after the user is
done it would return the valid value. If you manage to write everything
non-blocking, then you `loop()` will restart very often, and the program
will work with no significant latency.

As for managing the servo stages, simplest thing  would be to write a
[finite state machine][FSM]. I would write it with four states: IDLE,
STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 →
IDLE would be time-based, using the `elapsedMillis` object to track the
time spent in each state. The transition IDLE → STAGE1 would be
triggered by the user input.

    static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
    switch (state) {
        case IDLE:
            if (userRequestedToStartAgain()) {
                myservo.write(stage1speed);
                state = STAGE1;
                timeElapsed = 0;
            }
            break;
        case STAGE1:
            if (timeElapsed >= stage1time) {
                myservo.write(stage2speed);
                state = STAGE2;
                timeElapsed = 0;
            }
            break;
        case STAGE2:
            if (timeElapsed >= stage2time) {
                myservo.write(stage3speed);
                state = STAGE3;
                timeElapsed = 0;
            }
            break;
        case STAGE3:
            if (timeElapsed >= stage3time) {
                myservo.write(idleValue);
                state = IDLE;
            }
            break;
    }

[FSM]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


body:
I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.

      long duration;
      digitalWrite(trigger, LOW);
      delayMicroseconds(2);
      digitalWrite(trigger, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger, LOW);
      duration = pulseIn(echo, HIGH);
      distance = (duration/2) / 29.1;

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that `delayMicroseconds()` pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.

    class distSensor{
       int trigPin;
       int echoPin;
       int distance;

       //Will be used in timer
       unsigned long previousMillis;

       public:
       distSensor(int tPin,int ePin){
       trigPin = tPin;
       echoPin = ePin;

       pinMode(trigPin, OUTPUT);
       pinMode(echoPin, INPUT);

       previousMillis = 0;
     }

     int calculateDistance(){

      //records time since program start
      unsigned long currentMillis = millis();

      long duration;
      digitalWrite(trigPin, LOW);

      //check if the previous time the method was called is greater than the interval of 2
      if(currentMillis - previousMillis > 2){
        digitalWrite(trigPin, HIGH);
        previousMillis = currentMillis;
      }

      //check if distance between current time and previous time it was called is greater than interval of 10.
      if(currentMillis - previousMillis > 10){
          digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      }
      return distance;
     }
    };

In the `calculateDistance()` method I am trying to do the same thing as the first code but without `delay()` and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?

title: HC-SR04 distance measuring without delay?

Answers: 3

body:
[`delay()`][1] causes the processor to do nothing but wait.  You need to switch to [`millis()`][2].

In your code, you need to "grab" the current time using `millis()` and store it in a variable.  Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what `millis()` returns.  When your stored value and `millis()` match, it is time to execute the code that would normally come after the `delay()` call.

Here, [Arduino Playground - How and Why to avoid delay()][3], `delay()` and `millis()` are discussed in detail.

So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop.  Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.

  [1]: https://www.arduino.cc/en/reference/delay
  [2]: https://www.arduino.cc/en/reference/millis
  [3]: http://playground.arduino.cc/Code/AvoidDelay

body:
    enter code here
    #define ECHO 5        // Pin received echo pulse
    #define TRIGGER 6     // Pin sends shot pulse

    int distance; // the distance in cms
    unsigned long previousMicros = 0; // will sotre last time TRIGGER was updated
    long OnTime = 10; //microseconds of on-time
    long OffTime = 2; //microseconds of off-time
    unsigned long previousMillis = 0; //will store last time viewTime was updated
    int triggerState = LOW; // triggerState used to set it up
    long duration;
    void setup()
    {
      Serial.begin(9600);
      pinMode(ECHO, INPUT);
      pinMode(TRIGGER, OUTPUT);
    }

    void loop()
    {
      // check to see if it's time to change the state of the TRIGGER
      unsigned long currentMicros = micros();
      if((triggerState == LOW) && (currentMicros - previousMicros >= OffTime))
       {
         triggerState = HIGH; // turn it on
         previousMicros = currentMicros; // remember the time
         digitalWrite(TRIGGER, triggerState); // update the actual trigger
       }
       else if((triggerState == HIGH) && (currentMicros - previousMicros >= OnTime))
       {
         triggerState = LOW; // turn it off
         previousMicros = currentMicros; // remember the time
         digitalWrite(TRIGGER, triggerState); // update the actual trigger
       }

    duration = pulseIn(ECHO,HIGH  );
    Serial.println(distance);
    distance = ((duration*0.034)/2);
    Serial.print("distance: ");

    }

**this will run your code without delay but the problem is you will get a zero every time resulting from pulseIn() which from there on I dont know how to fix it yet**

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

    unsigned long currentMillis = micros();
    digitalWrite(Trig, LOW);

    if (currentMillis - previousMillis > 4) {
      digitalWrite(Trig, HIGH);
      previousMillis = currentMillis;
    }

    if (currentMillis - previousMillis > 12) {
      digitalWrite(Trig, LOW);
      previousMillis = currentMillis;
    }

    impulseTime = pulseIn(Echo, HIGH);
    distance_sm = impulseTime / 58; // convert to centimeters
    distance = distance_sm;


body:
I am trying to create a code which prints to the LCD a message once a certain time is passed.

    #include <Time.h>
    #include <TimeLib.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2);
      setTime(02, 10,00, 14, 03, 2016);

      //pinMode(13, OUTPUT);
      pinMode(2, INPUT);
      digitalWrite(2, LOW);
      attachInterrupt(0, blink, CHANGE);
    }

    void loop() {
      lcd.setCursor(0, 1);
      char time_out[16];
      sprintf(time_out, "u:u:u",hour(),minute(),second());//use %x to get hex
      lcd.print(time_out);

      int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
      lcd.print(totalSeconds);
      if(totalSeconds > 7806) {
        digitalWrite(2, HIGH);
      }
    }

    void blink() {
      lcd.print("time passed");
    }

The `setup` uses the Time lib to set a date. It also  sets `pin 2` as an `INPUT` and sets it it `LOW`. The `attachInterrupt` checks if `pin 2 (0)`, changes, then function `blink` should execute.

In the loop, I am creating a string that prints out the time and displaying it to the LCD. I am also converting the time to seconds, so that I can easily compare two times. After 6 seconds (the timer starts at 7800), I am changing the value of `pin 2` to `HIGH`.

This should indicate a change in its state and should and trigger `blink`, but it does not. Can anyone spot the mistake I made? Thanks in advance.

title: Make action happen after time is passed using interrupts

Answers: 2

body:
Since I don't have enough reputations to comment on your question I am going to drop my two cents here.

Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the `attachInterrupt` function. I am going to suppose that there is no need to use timers' interrupts as well.

Have a look at the following code:

    #include <Time.h>
    #include <TimeLib.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2);
      setTime(02, 10,00, 14, 03, 2016);
    }

    void loop() {
      char time_out[16];
      lcd.setCursor(0, 1);
      sprintf(time_out, "u:u:u",hour(),minute(),second());//use %x to get hex
      lcd.print(time_out);

      int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
      lcd.print(totalSeconds);
      if(totalSeconds > 7806) {
        blink();
      }
    }

    void blink() {
      lcd.print("time passed");
    }

You should know the following:

Commands inside `void loop()` is going to be executed for ever again and again. Especially `lcd.print(time_out);`. You had better refresh the LCD every 1 second.

After 6 seconds `blink()` is going to be executed many times (maybe forever) since it is inside the loop and `if(totalSeconds > 7806)` is going to be always true.

If you have any question let me know in the comment section.

body:
1.  To do what you want, pin 2 would need to be an output.  As an input you have no control over its state when you write it low.  It may be hanging there floating in a high state and when you write high to it and turn on the pullup that may or may not actually be a change of state.

2.  Doing a print to the LCD may not work in an ISR.  Remember that during the ISR all other interrupts are disabled and depending on how your lcd library works it may not print anything from inside the ISR.

3.  Even if it does print "time passed" upon being triggered by the line at the end of loop, a few microseconds later loop would repeat and that would be overwritten by the stuff that loop writes to the screen.  So even if it did work you'd never know.

Instead of having your ISR print something to the screen, have it turn on an led or something so you know it actually triggered.

Try this instead and see if it is closer to what you want: (uncompiled and untested as I don't have the libraries)

    #include <Time.h>
    #include <TimeLib.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    boolean passed = false;

    void setup() {
      lcd.begin(16, 2);
      setTime(02, 10, 00, 14, 03, 2016);

      //pinMode(13, OUTPUT);
      pinMode(2, OUTPUT);
      digitalWrite(2, LOW);
      attachInterrupt(0, blink, CHANGE);
    }

    void loop() {
      if (passed) {
        lcd.setCursor(0, 1);
        lcd.print("time passed");
        while(1);  // freeze here time is up
      }
      else {
        lcd.setCursor(0, 1);
        char time_out[16];
        sprintf(time_out, "u:u:u", hour(), minute(), second()); //use %x to get hex
        lcd.print(time_out);

        int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
        lcd.print(totalSeconds);
        if (totalSeconds > 7806) {
          digitalWrite(2, HIGH);
        }
      }
    }

    void blink() {
      passed = true;
    }


body:
I'm attempting to start a timer lasting a specific interval when the ultrasonic distance sensor measures a distance lower than 25 cm. Once that occurs, I want the speaker to make sound if the distance goes above 25 cm whilst the timer is running. I am attempting to use an interrupt to do this, but I'm having trouble.

This is what I have so far:

    void setup() {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(interruptPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin), sensor, CHANGE);
    }

    int makeSound() { // This function creates the sounds
      ...
    }

    int echo() { // This function gets the distance the sensor is measuring
      ...
    }

    void loop() {
      distanceCm = echo();
      if (distanceCm < 25) {
        Timer();
      }
    }

    int Timer() {
      half_hour_millis = millis();

      while (millis() < half_hour_millis + interval) {
        // Here goes the code that I haven't written and was hoping you could help me with
      }
    }

    // My interrupt function
    void sensor() {
    }

title: Play sound with speaker inside interrupt while a timer runs

Answers: 1

body:
Andrew,

I think I see what you're trying to accomplish. I would try something like the following, and I'll explain afterward:

    boolean timerRunning = false;
    unsigned long start_millis;
    unsigned long end_millis;

    boolean tripped() //was int Start()
    {
      dist = echo1();
      if (dist < 25 && dist > 0) {
        return true;
      else
        return false;
    }

    void loop()
    {
      if(tripped())  //check for < 25cm
      {
        //if tripped and timer not running, start
        //keeping track of time
        if(!timerRunning)
        {
          timerRunning = true;
          start_millis = millis();
          end_millis = start_millis + half_hour;
        }
        //if timer already running, print millis
        else
        {
          Serial.println(millis()); //or Serial.pringln(millis()-start_millis);
                        // for time since timer started
        }
      }
      else  //not < 25cm, not tripped
      {
        //if not tripped and timer running, time for sound
        if(timerRunning)
        {
          timerRunning = false; //might as well stop timer
          alert();
        }
        //if timer not started and not tripped nothing to do
      }

      //finally, lets check time, if past half hour, stop tracking
      //elapsed time
      if(timerRunning)
      {
        if(millis > end_millis)
        {
          timerRunning = false;
        }
      }
    }//end void loop()

In general, you don't want to block the loop() from looping. Some of the Arduino functions do their processing outside that loop (the interrupt pin possibly too).

I know I'm not using the interrupt, but for a couple reasons. First, it looks like the pin can only change if you call your echo1() function, as you have to trigger the ultrasonic transmitter. Secondly, the state of the pin will not reflect the distance, only that it's receiving sound. As an aside, for what it looks like you were trying to do, you would have wanted to attach the interrupt and detach the interrupt only when the timer started or ended, as opposed to in the setup. Otherwise it could interrupt at any time, such as everytime the echo1() was called.

Hopefully my code comments help explain the flow. Basically I'm keeping track of the state of things, mostly with 'timerRunning'. Based on whether the timer is running and the ultrasonics are tripped (measuring less than 25cm), the appropriate actions are taken. The only way to stop the timer is the elapsing of half an hour, or the alert condition.

Double check my math, but i think there are 1,800,000 milliseconds in half an hour, so you will want to change your constant. Also, I don't know how long you plan on having your device run, but the millis() function will rollover back to 0 after about 50 days. Your end time will end up calculating out to less than the current time and the timer will not be able to run properly (will immediately stop) for that last half hour until rollover. Just something to keep in mind.

Hope this helps and good luck!


body:
    int temp=A0;
    #include<stdlib.h>
    #include <SoftwareSerial.h>

    #define SSID "rab"
    #define PASSWORD "rakesh1234"
    #define IP "184.106.153.149" // thingspeak.com
    String GET = "GET /update?key=B8B8E4FC1K541QZQ&field1=";
    SoftwareSerial monitor(0, 1); // RX, TX
    SoftwareSerial mySerial(5, 6); // RX, TX
    int p1=0,p2=0,p3=0;
    int i=0;
    int j=0;

    void setup() {
      pinMode(A0,INPUT);
      Serial.begin(115200);
      monitor.begin(115200);
      mySerial.begin(9600);
      sendDebug("AT");
      delay(2000);
      if(Serial.find("OK")) {
        monitor.println("RECEIVED: OK");
        Serial.println("RECEIVED: OK");
      }
      connectWiFi();
    }

    unsigned char buf[50];

    void loop() {
       while(!mySerial.available());
       if(mySerial.read() == '#') {
         for(int i=0;i<12;i++) {
           while(!mySerial.available());
           buf[i] = mySerial.read();
         }
         buf[3] =0;
         buf[7]=0;
         buf[11]=0;
         p1 = atoi((const char *)&buf[0]);
         p2 = atoi((const char *)&buf[4]);
         p3 = atoi((const char *)&buf[8]);
         delay(1000);
       }

       long int SensorValue=analogRead(temp);
       SensorValue=SensorValue*5000;
       SensorValue=SensorValue/1024;
       SensorValue=SensorValue/10;
       SensorValue=SensorValue*9;
       SensorValue=SensorValue/5;
       SensorValue=SensorValue+32;
       String tempF=String(p1);
       String tempFF=String(p2);
       String tempFFF=String(p3);
       String tempFFFF=String(SensorValue);

       for(int j=0;j>-1;j++) {
         **j= Serial.read(int p1, int p2, int p3);**
       }
       while(Serial.available()==j)
         updateTemp(tempF,tempFF,tempFFF,tempFFFF);
       while(1) {}
     }

     void updateTemp(String tempF1 ,String tempF2, String tempF3,  String tempF4) {
       String cmd = "AT+CIPSTART=\"TCP\",\"";
       cmd += "api.thingspeak.com";
       cmd += "\",80";
       sendDebug(cmd);
       delay(1000);
       if(Serial.find("Error")) {
         monitor.print("RECEIVED: Error");
         Serial.print("RECEIVED: ERROR");
         return;
       }
       cmd = GET;
       cmd += tempF1;
       cmd += "&field2=";
       cmd += tempF2;
       cmd +="&field3=";
       cmd +=tempF3;
       cmd +="&field4=";
       cmd +=tempF4;
       cmd += "\r\n";
       Serial.print("AT+CIPSEND=");
       Serial.println(cmd.length());
       if(Serial.find(">")) {
         monitor.print(">");
         monitor.print(cmd);
         Serial.print(cmd);
       } else {
         sendDebug("AT+CIPCLOSE");
       }
       if(Serial.find("OK")) {
         monitor.println("RECEIVED: OK");
       } else {
         monitor.println("RECEIVED: Error");
       }
     }

     void sendDebug(String cmd) {
       monitor.print("SEND: ");
       monitor.println(cmd);
       Serial.println(cmd);
     }

     boolean connectWiFi() {
       Serial.println("AT+CWMODE=1");
       delay(2000);
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASSWORD;
       cmd+="\"";
       sendDebug(cmd);
       delay(1000);
       if(Serial.find("OK")) {
         monitor.println("RECEIVED: OK");
         return true;
       } else {
         monitor.println("RECEIVED: Error");
         return false;
       }
     }

This is my code. I am getting an error as "exit status 1
expected primary-expression before 'int'"

Please help me.

Thank you.

Answers: 2

body:
You are doing Serial.read() wrong with:

    Serial.read(int p1, int p2, int p3);

`Serial.read()` takes no parameters per https://www.arduino.cc/en/Serial/read

Maybe you want to try `parseInt()` instead?

body:
Your problem is that your are using asterisks ("*")

       for(int j=0;j>-1;j++) {
         **j= Serial.read(int p1, int p2, int p3);**
       }

The asterisk in C/C++ is the **pointer operator**. You use to get the value pointed by a pointer.

The expression `**j` means that `j` is a pointer to a pointer that points something. That's is meaningless here.

Then, the last `**` is readed as another pointer to a pointer, and the compiler is expecting a variable or expression that give the value for the pointer, but found "}", which is an error.

You probably tried to comment out that line of code after the compiler barks at the `Serial.read()`, which, as Dave X pointed out, is illegal, because `Serial.read()` takes no arguments.

And, the syntax `function(int x)` is only use for declaring a function, not for calling one.