message:
How to write a code to detect how many times the IR detector has detected an IR signal.... HELP

I am trying to write a code so that I can detect how many times the IR detector has detected the IR signal from the IR transmitter.

body:
Its quite simple:

    IRDetectorLibraryObject ir;
    int counter = 0;

    void setup()
    {
        ir.setup();
    }
    void loop ()
    {
        if (ir.detectedSignal())
        {
          ++counter;
        }
    }


sender: user

message:
Two pots controlling 2 servos -- odd behavior

I'm trying to control 2 servos with 2 pots. I thought I could just amend the tutorial code by adding in the extra pot on a1 and extra servo on d8 (am using a Nano).

    #include <Servo.h>

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

    int potpin = 0;  // analog pin used to connect the potentiometer
    int potpin_2 = 1;
    int val;    // variable to read the value from the analog pin
    int val_2;

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      myservo_2.attach(8);
    }

    void loop() {
      val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
      val_2 = analogRead(potpin_2);
      val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
      val_2 = map(val_2, 0, 1023, 0, 180);
      myservo.write(val);                  // sets the servo position according to the scaled value
      myservo_2.write(val_2);
      delay(15);                           // waits for the servo to get there
    }

...but the servos only respond to one of the pots (on a0) & both move to the same position regardless of what value is on a1.

Am I missing something really obvious? Why is the value on a1 ignored & why is the value mapped from a0 sent to both d8 & d9?

I have swapped out the pot on a1 just in case it was faulty but I get the same behavior.

EDIT: Added schematic

[![Dual servo schematic][1]][1]

EDIT: I swapped out the Nano for another Nano but that failed to upload the sketch. So I put the original back in & now evrything is working fine!

Darn'd if I can get my head around it, possibly a bad connection with the bread board?

Anyway all working now thanks for your suggestions.

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

sender: assistant

body:
I have no idea whats wrong with your system, but this might help you diagnose it.

    #include <Servo.h>

    static const size_t MaxServos = 2;    // The number of pots and servos attached
    const int servoPins[MaxServos] = {9, 8};  // The pins that the servos are controlled through
    const int potpins[MaxServos] = {A0, A1};  // analog pin used to connect the potentiometer
    Servo myservo[MaxServos];      // create servo object to control a servo

    void setup ()
    {
     for (size_t index = 0; index < MaxServos; ++index)
     {
      myservo[index].attach (servoPins[index]);
     }
    }

    void loop ()
    {
     for (size_t index = 0; index < MaxServos; ++index)
     {
      readAndSet (potpins[index], myservo[index]);
     }
     delay (15);                           // waits for the servo to get there - might want to multiply a value by the number of degrees turned to give a better value.
    }

    // \brief Read the specified analog pin and set the server proportionally
    // \param The analog pin that the pot is connected to.
    // \param The servo that will be moved
    void readAndSet (const int& pin, Servo& servo)
    {
     const int value = analogRead (pin);            // reads the value of the potentiometer (value between 0 and 1023)
     const int mappedValue = map (value, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
     servo.write (mappedValue);                  // sets the servo position according to the scaled value
    }

I have refactored your code to eliminate the duplication.  This means you will get more test coverage and you should find the bug quicker.  You could add a `Serial print` statement to the `readAndSet` function to ensure that you are passing and calculating the right values, but I suspect you are.

There appears to be nothing wrong with the code, so is it possible that there is some hardware limitation?  Is there a short between the lines that causes the pot on A1 to be bypassed?


message:
if/else statements without comparison operators and curly braces

I recently came across this code in a tutorial. The code works, but this form of syntax seems to differ quite a bit from https://www.arduino.cc/reference/en/language/structure/control-structure/if/, as it's lacking comparison operators and curly braces for statements. Can someone please run down why this works?

    for (int i = 0; i < 15; i++)
    {
    lcd.setCursor(i, 1);
    if (pressed[i])
      lcd.print("X");
    else
      lcd.print(" ");

    if (justpressed[i])
      digitalWrite(led, HIGH);
    else
      digitalWrite(led, LOW);
     }

body:
About the missing conditions, e.g.:

    if (pressed[i])

If is supposed to be a boolean, this is the prefered way, as long as the boolean has value zero (0) when false and nonzero when true. It is the same as writing:

    if (pressed[i] != 0)

It is not usual to do this for integers, only for booleans.

About the brackets: If you have only one statement the brackets can be omitted. But it is quite a bad programming practice, since sooner or later you add a statement, without the brackets added and you have a bug introduced.

If you really want to shorten it than instead of

    if (justpressed[i])
      digitalWrite(led, HIGH);
    else
      digitalWrite(led, LOW);

use

    digitalWrite(justpressed[i] ? HIGH : LOW);

This is called the [Ternary operator][1].

  [1]: https://en.wikipedia.org/wiki/?:#C

**update**

Using the remark of wondra but with the ternary operation your code can be

    for (int i = 0; i < 15; i++)
    {
        lcd.setCursor(i, 1);
        lcd.print   (     pressed    [i] ? "X"  : " ");
        digitalWrite(led, justpressed[i] ? HIGH : LOW);
    }


body:
1. **if (something)** is the same as **if(something!=0)**, if condition is a non-zero value, it is considered as [fulfilled condition](https://www.le.ac.uk/users/rjm1/cotter/page_37.htm), read about the [Conditionals - The true or false story](http://www.cplusplus.com/forum/articles/3483/)
2. For single line statements you don't need to use curly braces. But using the braces makes the code more readable and the code is [less prone to errors](https://stackoverflow.com/questions/12193170/whats-the-purpose-of-using-braces-i-e-for-a-single-line-if-or-loop)


message:
Arduino IDE loses programmer after installing Visual Micro

I had this added to programmers.txt

    mysmartusb.name=mySmartUSB light
    mysmartusb.communication=serial
    mysmartusb.protocol=stk500v2
    mysmartusb.program.protocol=stk500v2
    mysmartusb.program.tool=avrdude
    mysmartusb.program.extra_params=-P{serial.port}

And was getting so annoyed with the loading time of Arduino IDE 1.8.5 so I tried Visual Micro but that didn't go well either. Now, Arduino IDE can no longer see my programmer. Tried rebooting, did a search for all programmer.txt files on the C: and deleted/updated as I thought appropriate. Has anyone else ever had that issue and if so, how did they solve it?

body: Uninstalled and installed 1.9.0 as I heard that fixes the launch time (it does). I'm aware it's beta but it fixed my issue. I assume reinstalling 1.8.5 would've also gotten me my programmer back.


message:
Powering USB cable that powers Arduino with regulated 5V

I am having an issue with external loads causing the computer I have my Arduino connected to to momentarily drop out, which causes the Arduino to lose USB power momentarily and the port drops out and won't reconnect unless I physically remove and reconnect the USB cable. Since I need the USB connected in order to send and receive serial data to/from the Arduino, I was wondering if I could physically open the USB cable, cut the 5V line, and supply it via and external regulated 5V supply. I wouldn't cut the ground wire, but would tie it to the external 5V supply. I have read conflicting information on this (something about handshaking) but was wondering if that applied to Arduino's specifically.

body:
If you are drawing more than 500mA from your PC then that is why it is happening.

I suggest, rather than butchering a cable, you get yourself a "wallwart" (Mobile phone charger) and use that to power the board.  You really should work out how much current you are pulling before deciding on what PSU to use.

A problem with wall warts is earthing, you need to make sure that your PC and wall wart are connected to the same earth connection, so that they share a common ground.

If the current being drawn us only for a very short time then it might be possible to provide additional power using a capacitor in the power line.  But plugging a charger in is much easier.


body: I solved this problem by using a laptop instead. It is immune to these power fluctuations


message:
ESP8266 with Arduino Uno and HTTP POST

Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.

My problem with it is how can I program the esp with arduino uno? Do I do something like this
>https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??

Thanks for helping

body:
Yes, the library

* https://github.com/bportaluri/WiFiEsp

Is suited for your task because it implements talking to a ESP8266 over a software serial. On this serial connection, AT+ commands will be sent. This also means that you must have the AT firmware flashed onto your ESP-01.

If that is not the case you can download the binary image [here][1] and flash it with a serial adapter, as instructed with the tools on that page. You can check whether your ESP8266 has the firmware flashed by attach a UART adpater to the TX output. It should print a "ready" on bootup.

For your wire-up, you will just have to add VCC (+3.3V), GND, TX and RX connections to the ESP-01 board, preferable with a big capacitor between VCC and GND, as the ESP8266 draws a lot of power when sending data over WiFi.

  [1]: http://www.electrodragon.com/w/ESP8266_AT-Command_firmware


message:
External power vs usb power

I built a sample of my project on a breadboard using little 700mh leds and other components that easily ran off my computers usb. Now I’m building my project to full size.  This includes 12 7w leds, soundboard and amps. It’s still going to be controlled by a arduino mega, obviously, the power consumption is substantially higher than the usb or even the arduino can provide. I’m using a high amp power supply that can drive everything including the arduino.

The question is... how will I be able to alter my sketch later???  Is it feasible to use a panel mount usb cord modified to only allow tx and rx, (cut the red and black)?  Or will I have to isolate the mega each time I need to send a change to it?

body: You can modify a USB cable by cutting the power (red) wire. You'll still need the ground wire with RX and TX.


body: Using an altered USB cable and a separate power supply will work but isn't really necessary. I usually put a connector on my high-current devices like LEDs and whatnot so I can remove them from the equation while I upload code, and for debugging I leave the external power supply attached and use a regular USB cable to the PC (see https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage?rq=1).


message:
Configuring Accelerometer on BNO055 sensor

I'm using the BNO055 9DOF Adafruit sensor to measure the acceleration/orientation. How can I change the configuration of the accelerometer from 4G (default) to 16G?

What I already know:

The datasheet : https://cdn-shop.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf

From point 3.5.2 from page 27, I need to change xxxxxx01b to xxxxxx11b in the configuration file (that is the library). I use https://github.com/adafruit/Adafruit_BNO055 but I could not find any information on what to change and where in the .h file.

Any ideas?

Thank you

body:
This was partly discussed as an issue on the library's github

* https://github.com/adafruit/Adafruit_BNO055/issues/48

Here's how I understand it:

The library doesn't configure the registers you want. I don't see a reference to writing to the `ACC_CONFIG` register (address 8). Not even defined in the header.

The sensor has two register-pages (0 and 1) [refer page 50]. I.e. if you select page 0 then the register at address X means something, at page 1 it means something else.

We want to write to `ACC_Config` at address `0x08` on Page 1.

Page 77 tells us that, regarding writing to the register: "Write: can only be changed in sensor mode, see section 3.5.2"

In code, you could hack something in there:

* https://github.com/adafruit/Adafruit_BNO055/blob/master/Adafruit_BNO055.cpp#L115

After changing to the sensore mode, you could then write to the register as

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

    //values taken from section 3.5.2 page 27
    #define BNO055_ACC_CONFIG_2G (0) //0B00
    #define BNO055_ACC_CONFIG_4G (1) //0B01
    #define BNO055_ACC_CONFIG_8G (2)  //0B10
    #define BNO055_ACC_CONFIG_16G (3)  //0B11

    //bandwidth definitions
    #define BNO055_ACC_BW_7_81_Hz (0)
    #define BNO055_ACC_BW_15_63_Hz (1)
    #define BNO055_ACC_BW_31_25_Hz (2)
    #define BNO055_ACC_BW_62_5_Hz (3)
    #define BNO055_ACC_BW_125_Hz (4)
    #define BNO055_ACC_BW_250_Hz (5)
    #define BNO055_ACC_BW_500_Hz (6)
    #define BNO055_ACC_BW_1000_Hz (7)

    //powermode definitions
    #define BNO055_ACC_PWRMODE_NORMAL (0)
    #define BNO055_ACC_PWRMODE_SUSPEND (1)
    #define BNO055_ACC_PWRMODE_LP1 (2)
    #define BNO055_ACC_PWRMODE_STANDBY (3)
    #define BNO055_ACC_PWRMODE_LP2 (4)
    #define BNO055_ACC_PWRMODE_DEEP_SUSPEND (5)

    #define BNO055_ACC_CONFIG_ADDR 0x08

    //Select page ID 1 to write to the right register
    write8(BNO055_PAGE_ID_ADDR, 1);
    //build the config value with bitshifts
    //see page 77
    //use all standard values except 16G parameter
    uint8_t acc_config = (uint8_t)((BNO055_ACC_PWRMODE_NORMAL << 5)
                       | (BNO055_ACC_BW_62_5_Hz << 2)
                       | BNO055_ACC_CONFIG_16G);
    //write new accelerometer config
    write8(BNO055_ACC_CONFIG_ADDR, acc_config);

    //change back to page ID 0 (or whatever was before there)
    //Otherwise we read sensor data from the wrong page with entirely different meaning
    write8(BNO055_PAGE_ID_ADDR, 0);

Since I don't have that sensor here I have no way to test it. So this is just the basic idea. You can also read registers with `read8`, with which you can verify that before you write anything to the register, it has some standard (or expected) value. E.g., `ACC_CONFIG` should read as `0B00001101` = `0x0d`. And after you write a value there you should be able to read the same value back, otherwise the chip didn't let you execute the write and you have to investigate why.

Yes, you mostly have to do the hard work by yourself. Changing from 4G to 16G might also have the implication that some other calculations on the raw data has to be done different, however I am not sure of that.


message:
trouble getting out of a for loop in a function and go back to a FSM with a button

I have a finite state machine that goes to a function called patternOne, I can't seam to get out of this function though once I am in it and get back to the finite state machine. When I press a button my serial port shows it's been pressed but still stays in the function patternOne, I don't know how to get out of it and why this is happening. My code is below:

    #include <SPI.h>
    SPISettings settingsA(2000000, MSBFIRST, SPI_MODE1);
    #include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
    #include <Wire.h>  // Include Wire if you're using I2C
    volatile unsigned long prevTime = 0;

    int time_interval_for_chip = 5;
    int blinking_interval = 500;
    unsigned long current_time = 0;
    #define PIN_RESET A6  // Connect RST to pin 9

    #define DC_JUMPER 0

    MicroOLED oled(PIN_RESET, DC_JUMPER);// I2C declaration

    const int buttonpin = A8;
    volatile int buttonState = 0;   // variable for reading the pushbutton status
    volatile int buttonState2 = 0;
    int buttonstate3 = 1;
    const int buttonpin2 = A7;

    enum State {flip, intro, option1, pattern1, intro_flip, option1_flipped, pattern1_flipped, pattern2, pattern3};
    //enum is the data type that consists of user defined varaibles ie like the words pattern, intro, ext
    State state = flip; //telling the intial state to start at intro

    unsigned int column_pattern1[] = {0b0000000100000100, 0b0000001000001000,0b0100000010000010};
    //unsigned int column_off_pattern1[]={0b0000000000000100, 0b00000000000001000,0b0100000000000010};
    const int css1 = 10;
    const int css2 = A0;
    void setup() {
      oled.begin();    // Initialize the OLED
      oled.clear(ALL); // Clear the display's internal memory
      //  oled.display();  // Display what's in the buffer (splashscreen)
      //  delay(1000);     // Delay 1000 ms
      oled.clear(PAGE); // Clear the buffer.
      //

      pinMode(css1, OUTPUT);
      pinMode(css2, OUTPUT);
      Serial.begin(9600);
      SPI.begin();
      SPI.beginTransaction(settingsA);

      pinMode(buttonpin, INPUT_PULLDOWN);
      pinMode(buttonpin2, INPUT_PULLDOWN);
      // watermark generates this interrupt
      attachInterrupt(buttonpin, button_pressed, FALLING); // interrrupt 1 is data ready
      //attachInterrupt(buttonpin2, button_pressed2, FALLING); // interrrupt 1 is data ready

    }

    void loop() {

      // blinking output 4 and 8 while using a finite state machine to change from intro to a patter
      //turning off the desplay when a pattern is chosen

      switch (state) {
        case flip:
        oled.setFontType(1);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print(" Flip  Screen?");
      oled.setFontType(0);
      oled.setCursor(0, 30);
      oled.print("yes");
      oled.setCursor(40, 30);
      oled.print("no");
      oled.circle(10, 43, 3.5);
      oled.circle(50, 43, 3.5);
      oled.display();
      buttonState = 0;

      if (digitalRead(buttonpin2) == HIGH) {
            oled.circleFill(50, 43, 3.5);
            oled.display();
            oled.clear(PAGE); // Clear the buffer.
            delay(500);
            //buttonstate3=0;
         state=intro;
      }
       if (digitalRead(buttonpin) != buttonState) {
        oled.circleFill(10, 43, 3.5);
         oled.display();
            oled.clear(PAGE); // Clear the buffer.
            delay(500);
            state=intro_flip;
       }
      break;

        case intro:

          oled.setFontType(1);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("choose pattern");
          oled.circle(10, 40, 7);
          oled.display();
          buttonState = 0;

          if (digitalRead(buttonpin) != buttonState) {

            buttonState = 0; //reset button state
            oled.circleFill(10, 40, 7);
            oled.display();
            delay(500);
            state = option1;

          }
          break;

        case option1:
          oled.clear(PAGE); // Clear the buffer.

          //delay(300);
          oled.setFontType(0);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("Pattern 1");
          oled.setCursor(0, 10);
          oled.print("next");
          oled.setCursor(40, 10);
          oled.print("yes");
          oled.circle(10, 40, 7);
          oled.circle(50, 40, 7);
          oled.display();

          if (digitalRead(buttonpin2) == HIGH) {
            Serial.println("right button pressed");

            oled.circleFill(50, 40, 7);
            oled.display();
            delay(500);
            state = pattern1;

          }
          break;
            case pattern1:
          oled.clear(PAGE);
          oled.display();

          patternONE();
          buttonState=0;
          if (digitalRead(buttonpin) != buttonState) {
            Serial.println("left button pressed");
            //         //delay to register that the button was pressed
            delay(500);
            //
            state = intro;
          }
          break;

    ////////////////////////////////////////////////////////
    ///////////FLIPPED FINITE STATE MACHINE/////////////////
    ////////////////////////////////////////////////////////

    case intro_flip:
      oled.flipVertical(true);
        oled.flipHorizontal(true);
         oled.setFontType(1);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("choose pattern");
          oled.circle(50, 40, 7);
          oled.display();
          buttonState = 0;

          if (digitalRead(buttonpin) != buttonState) {

            buttonState = 0; //reset button state
            oled.circleFill(50, 40, 7);
            oled.display();
            delay(500);
            state = option1_flipped;

          }
          break;

          case option1_flipped:
    oled.flipVertical(true);
        oled.flipHorizontal(true);
          oled.clear(PAGE); // Clear the buffer.

          //delay(300);
          oled.setFontType(0);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("Pattern 1");
           oled.setCursor(0, 10);
          oled.print("yes");
          oled.setCursor(40, 10);
          oled.print("next");
          oled.circle(10, 40, 7);
          oled.circle(50, 40, 7);
          oled.display();

          if (digitalRead(buttonpin2) == HIGH) {
            Serial.println("right button pressed");

            oled.circleFill(10, 40, 7);
            oled.display();
            delay(500);
            state = pattern1_flipped;

          }
          break;

           case pattern1_flipped:
          oled.clear(PAGE);
          oled.display();

          patternONE();
    //      buttonState=0;
          if (digitalRead(buttonpin) != buttonState) {
            Serial.println("left button pressed");
            //         //delay to register that the button was pressed
            delay(500);
            //
            state = intro_flip;
          }
          break;

      }
    }////////////////////////////////////////////////////////
    ///////////Pattern/////////////////
    ////////////////////////////////////////////////////////
    void patternONE() {
    buttonState = 0;
       unsigned int chip1 = 0;
      unsigned int chip2 = 0;
      byte inbyte = 0;
      byte inbyte2 = 0;

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

        digitalWrite(css2, LOW);
        chip2 = SPI.transfer16(column_pattern1[i]);
        Serial.print("chip2 column off=");
        Serial.println(chip2, BIN);
        digitalWrite(css2, HIGH);

        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0001010000000000);
        Serial.print("chip1 row 8 on high driver= ");//not the chip is a look behind so the print statments are the previous output
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        delay(1);
        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0100000100000000);
        Serial.print("chip1 row 4 and 6 on low driver= ");
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        delay(2000);

        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0001010001010000);
        Serial.print("chip1 row 8 on low driver= ");
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        delay(1);

        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0100000100000100);
        Serial.print("chip1 row 4 and 6 on high driver= ");
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        digitalWrite(css2, LOW);
        chip2 = SPI.transfer16(column_pattern1[i]);
        Serial.print("chip2 column on high driver= ");
        Serial.println(chip2, BIN);
        digitalWrite(css2, HIGH);

        //turn off the previous column
    //    digitalWrite(css2, LOW);
    //    chip2 = SPI.transfer16(column_off_pattern1[i]);
    //    Serial.print("chip2 column on high driver= ");
    //    Serial.println(chip2, BIN);
    //    digitalWrite(css2, HIGH);
    //
        delay(2000);

      }

    }

    // watermark generates this interrupt
    void button_pressed()
    {
      cli();
      //confirmitng that the button was pressed and that its not just like a bounce"
      if (millis() - prevTime > 50) {
        Serial.println("left button pressed");
        buttonState = 1;
      Serial.println("buttonState =");
      Serial.println(buttonState);
      }

      sei();
      prevTime = millis();

    }

body:
From your question, it sounds like you are expecting PatternONE() to return on a button press but I don't see any code in the function that refers to a button or acts on one. The function defines a local variable `buttonState` and initializes it to 0, but never refers to it again.

I suspect you meant that as a declaration of the global `buttonState`, but you have two problems: 1) the function never uses buttonState to initiate a return; and 2) the local definition `buttonState` hides the global one while it is in scope; i.e., while the function is executing.


message:
Fast PWM working with int main(void) but not with void setup()

board: Arduino Mega (ATMEGA2560)

I want to generate pulses using timer1 configured as Fast PWM, this is my code which works fine:

    #include <avr/io.h>

    int main(void)
    //void setup()
    {

      DDRB |= (1 << DDB5) | (1 << DDB6); // PWM outputs

      ICR1 = 0x7FFF;  // TOP
      OCR1A = 0x3FFF; // 50% of ICR1
      OCR1B = 0x3FFF; // 50% of ICR1

      TCCR1A |= (1 << COM1A1) | (1 << COM1B1);
      TCCR1A |= (1 << WGM11);
      TCCR1B |= (1 << WGM12) | (1 << WGM13);
      TCCR1B |= (1 << CS10);

    }

    void loop() {

    }

I don't understand why it doesn't work if I use `void setup()` instead of `int main(void)`. I'm working with arduino IDE 1.8.2 and always used void setup(), in this case I used int main(void) because it is used in some turorials I found like this one: [https://www.youtube.com/watch?v=O_Yqf_cugwE][1]

  [1]: https://www.youtube.com/watch?v=O_Yqf_cugwE

EDIT: When I say that it doesn't work, what happens is that instead of having PWM signals I just have a constant 5V output in both OC1A and OC1B pins

body:
If you don't define your own `main()`, your program will be linked with
the `main()` provided by the Arduino core library, which roughly looks
like this (I am simplifying a little bit):

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

    int main(void)
    {
        init();      // Arduino core initialization
        setup();     // user's initialization
        for (;;)
            loop();  // user's main loop
    }

The [core's `init()` function][init] configures Timer 1 for 8-bit phase
correct PWM at 490 Hz, which means that, by the time your `setup()`
runs, the timer's control registers are not in their default state
anymore, and some of their bits are already set to 1. If you then
update these registers using the `|=` operator, you end up with a mix of
the core's configuration and your own.

This can be fixed either by zeroing these registers first or, more
simply, by setting their values with the `=` operator, which has the
effect or setting _every_ bit of those registers to the value you want.

The following works whether you use or not the Arduino core library:

    #ifdef NOCORE
    int main(void)
    #else
    void setup()
    #endif
    {
        DDRB   = _BV(PB5) | _BV(PB6);
        TCCR1A = _BV(COM1A1)
               | _BV(COM1B1)
               | _BV(WGM11);
        TCCR1B = _BV(WGM12)
               | _BV(WGM13)
               | _BV(CS10);
        ICR1   = 0x7fff;  // TOP
        OCR1A  = 0x3fff;  // 50% of ICR1
        OCR1B  = 0x3fff;  // 50% of ICR1
    }

    #ifndef NOCORE
    void loop(){}
    #endif

Note that:

1. The control registers are _set_ (`=`) rather than just modified with
`|=`
2. The mode is set before the output compare registers. This is because
setting the output compare registers does not work well when the timer
is in an 8-bit mode.

[init]: https://github.com/arduino/Arduino/blob/1.8.2/hardware/arduino/avr/cores/arduino/wiring.c#L241


message:
Change values of timer using I2C

I'd like to alter the "LED_T_ON" values using an I2C enabled device (i.e. RPi)

Code for Arduino Mega slave:

    //slave

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x08

    const int PWR_LED = 43;
    int LED_TinH_ON = 18;
    int LED_T_ON = 5000;
    int LED_T_OFF = 5000;

    String inString = "";    // string to hold input
    byte LastMasterCommand = 0;
    int Mval;

    char user_input;

    class Relay {
      int relayPin;
      long OnTime;     // milliseconds of on-time
      long OffTime;    // milliseconds of off-time

      // These maintain the current state
      int relayState;                 // pumpState used to set the PUMP
      unsigned long previousMillis;   // will store last time PUMP was updated

      // Constructor - creates a Timer and initializes the member variables and state
      public:
      Relay(int pin, long on, long off)
      {
        relayPin = pin;
        pinMode(relayPin, OUTPUT);

        OnTime = on;
        OffTime = off;

        relayState = LOW;
        previousMillis = 0;  //ORIGINALLY 0
      }

      void Update()
      {
        // check to see if it's time to change the state of the TIMER
        unsigned long currentMillis = millis();

        if((relayState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
          relayState = LOW;  // Turn it off
          previousMillis = currentMillis;  // Remember the time
          digitalWrite(relayPin, relayState);  // Update the actual LED
        }
        else if ((relayState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
          relayState = HIGH;  // turn it on
          previousMillis = currentMillis;   // Remember the time
          digitalWrite(relayPin, relayState);   // Update the actual RELAY
        }
      }
    };

    Relay relay3(PWR_LED, LED_T_OFF, LED_T_ON);

    void setup() {
     // initialize serial communication with computer:
      Serial.begin(9600);

      Wire.begin(SLAVE_ADDRESS);

      Wire.onReceive(receiveData);
      Wire.onRequest(slavesRespond);

      pinMode(PWR_LED, OUTPUT);
    }

    void loop() {
      delay(1000);

      Serial.print("LED_T_ON=");
      Serial.println(LED_T_ON);
      Serial.print("LED_T_OFF=");
      Serial.println(LED_T_OFF);
      Serial.println();

      relay3.Update();

      switch (Mval) {
        case 1 ... 25:
          LED_TinH_ON = Mval;
          Serial.print("LED time on: ");
          Serial.print(LED_TinH_ON);
          Serial.println("h");
          LED_T_ON = LED_TinH_ON*1000;//*60*60;
          LED_T_OFF = (24-LED_TinH_ON)*1000;//*60*60;
        break;
      }
    }

    void receiveData(int byteCount) {
      LastMasterCommand = Wire.read();
      while (Wire.available()) {
        int msg = Wire.read();

        if (isDigit(msg)) {
          inString += (char)msg;
        }
      }
      Mval = inString.toInt();
      //Serial.println(LastMasterCommand);
      inString = "";
      //Serial.println(Mval);
    }

    void slavesRespond() {
    }

When I change the value on the RPi the Arduino receives and displays the correct value but the timed relays don't actually use the updated values.

Am I missing something?

body: Your updating `LED_T_ON` and `LED_T_OFF` but those values were already passed into the constructor and changing them will not change the object. you need to update  `relay3.OnTime` and `relay3.OffTime`


message:
I2C Read Operation in TCA9539

I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

[![Image of the Address Byte][1]][1]

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

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?

For second question:

Based on the device spec for read operation:

> Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave,
the master must first instruct the slave which register it wishes to read from. This is done by the master starting
off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0
(signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this
register address, the master sends a START condition again, followed by the slave address with the R/W bit set
to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA
bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the
master-receiver, and the slave becomes the slave-transmitter.
The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data.
At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for
more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the
slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,

    Wire.begin();
    Wire.beginTransmission(0x74); // start i2c transmission as write addr
    Wire.write(0x01)              // the register i need to read from
    Wire.beginTransmission(0x75); // start i2c transmission as read addr given

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?

body:
The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.

So begin transmission 0x74

Write 0x01

End transmission

Begin transmission 0x74

Read n

End transmission


body:
You have misunderstood, how the `Wire` library works. It is doing all the things with the direction bit for you.

**Write Operation:**

 - `Wire.beginTransmission()` takes a 7-bit address as a parameter. The direction bit is automatically and internally set to write operation.
 - `Wire.write()` writes a value to the library-internal buffer, but is not doing anything on the actual I2C bus
 - Finally you call `Wire.endTransmission()` to finally do the write operation on the actual I2C bus. Prior to this function call the library doesn't do anything on the bus. So you have to call it, so that the data can reach the slave device

**Read Operation:**

- For reading from a slave device there is an extra function: `Wire.requestFrom()`. It takes the (7-bit) address and the number of requested bytes as parameters and it returns the number of bytes, that were actually read from the slave device (is important if the slave is sending less data, than requested). After a call to this function, the read bytes are now lying in the library-internal buffer.
- To get the received bytes from the library-internal buffer, you have to use `Wire.read()`. Again it does not do anything on the I2C bus. It just reads from the internal buffer.

---
So for your code you need to send a command byte to the slave, that says, what registers of the slave (determinded by the lowest three bytes, as the datasheet says) you want to access next. After that you can either send more bytes (in order to write the chosen registers) or you can start a request, so that the slave will send you the current state of the selected register.

Look at this images from pages 23 and 24 of the datasheet:
[![enter image description here][1]][1]

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

These are showing exactly, what you have to send. Note that the address byte is automatically send by the `Wire` library, so you don't have to do it. I will put it in code for you:

**Write operation:**

    Wire.begin();
    Wire.beginTransmission(slave_address);
    Wire.write(register_address);
    Wire.write(new_register_data);
    Wire.endTransmission();

The register address is documented in the datasheet. In this case it is the register with address 0x01 (Though this makes no sense, since this is a read-only register).

**Read operation**

    Wire.begin();
    Wire.beginTransmission(slave_address);
    Wire.write(register_address);
    Wire.endTransmission();
    if(Wire.requestFrom(slave_address,1) > 0 ){
        byte data = Wire.read();
    }

Here we first do a write operation to tell the slave, what register we want to access. Then we request the data in this register with `Wire.requestFrom()`. To transfer from the internal buffer to our program is done with the `Wire.read()` function (but only, if there was actually something received).

---
For the address of the slave device: This depends on how you have set the pins A0 and A1. You can find a table with the corresponding addresses at page 21 of the datasheet. Note that these are NOT including the data direction bit. When you are using the `Wire` library, you don't have to bother about it.

  [1]: https://i.stack.imgur.com/iOk9e.png
  [2]: https://i.stack.imgur.com/9JEGM.png


message:
Binary addressing and coding to control a 96 input mux matrix

I’m trying to wrap my head around using binary addresses in a mux. Failing miserably.
For the circuit I have six 16 channel analog multiplexers CD74HC4067 as slaves to an eight channel multiplexor CD54HC4051 master.
They are bringing in 96 sensor readings (IR receiver diodes through Op Amps) into an array
that, in turn,  is used to constantly update lotsa LEDs through a series of shift registers (TLC5940) using the Arduino TLC5940 Library.

I’ve included the possible wiring scheme that the code is trying to control.
It probably needs work too.[![enter image description here][1]][1]

Question: I’ve seen, and SEMI-understand matrixes that address 32 inputs
(4 x 8 bits) but not quite understanding how I can address the six mux chips
with 96 inputs. Or if I can even do it this way. Example from this forum: https://arduino.stackexchange.com/questions/28134/how-to-code-for-cascading-multiplexers
Is it possible with this matrix of 96 inputs, and how? Am I barking up the wrong tree?

Code so far:

        #include <Tlc5940.h> //Arduino TLC5940 Library controls the individual LEDs - "Pixels"

    int ledCount = 96; //change  LED "PIXEL" count in matrix...also number of IR sensor inputs

    int thresh = 10; //value for usable distance reading from IR

    // main structures to hold LED Pixel array on/off state, IR reciever readings
    byte dsply_state[ledCount];    //pixel on-off grid, need for tlc5940
    uint_16  recv_state[ledCount];           // IR Readings - FROM mux set-up

    // Master IR -mux sensor pins for Arduino Pro MINI
    #define  M_S0 2
    #define  M_S1 4
    #define  M_S2 5
    // Slave IR mux sensor pins
    #define  S_S0 6
    #define  S_S1 7
    #define  S_S2 8
    #define  S_S3 12

    //  ANALOG PIN :
    #define  InputFromMux A0

    void setup() {
        //Serial.begin(9600);

        //tlc5940 Arduino library
        Tlc.init(0);

        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);
        pinMode(S_S3, OUTPUT);
        pinMode(InputFromMux, INPUT);

    }

    void loop() {
        // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER and SLAVES.

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

        digitalWrite(M_S2, i & 0b1000000);
        digitalWrite(M_S1, i & 0b0100000);
        digitalWrite(M_S0, i & 0b0010000);
        digitalWrite(S_S3, i & 0b0001000);
        digitalWrite(S_S2, i & 0b0000100);
        digitalWrite(S_S1, i & 0b0000010);
        digitalWrite(S_S0, i & 0b0000001);

        delay(2);

        //edited as per @Gerben. thanks so much

        //get an individual sensor reading from IR receiver/opAmp mux, store it in a variable
         int IRstate = analogRead(InputFromMux);

        //populate receiving array with a reading
         recv_state[i] = IRstate;

        //populate display array for tlc5940 to push out
         dsply_state[i] = recv_state[i];

    } //end for(i...) loop

          //run through display state array to check if the stored reading is greater than a threshold number
          //if yes, then turn on the "pixel". If not, set it to zero
          //

           for (int x = 0; x < ledCount; x++)
              if (dsply_state[x] >= thresh ) {

                   Tlc.set(dsply_state[x], 4000);

                 //or if reading from mux is zero
              } else if (dsply_state[x] < thresh) {

                  Tlc.set(dsply_state[x], 0);
                  }

                //tlc5940 Arduino library - update() clocks the chips
                // move update(); outside the for(x...) loop for speed?
            Tlc.update();
            delay(10);

          } //end For(x..) Loop

    }//endMainLoop

  [1]: https://i.stack.imgur.com/zcnUZ.gif

body:
OK. First, how the multiplexer works. I have [a page about multiplexers](http://www.gammon.com.au/forum/?id=11976) in which there is this example of the 74HC4051:

 [![CD4051][1]][1]

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.

So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).

In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.

The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.

Thus your method would be:

* Loop from 0 to 5 on the master multiplexer (the 54HC4051). This selects which of the 6 16-input multiplexers you are interested in right now.

* For each of those, loop through 0 to 15 on S0/S1/S2/S3 so that the currently-selected CD74HC4067 routes its input through to its output.

* Read the resulting value

Those two loops will give you 96 inputs, which is what you are trying to read.

This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

---

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).

The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.

This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

---

> Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern?

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:

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

    const int MUX_CHIPS = 6;
    const int LEDS_PER_CHIP = 16;
    const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
    // Master IR -mux sensor pins for Arduino Pro MINI
    const byte  M_S0 = 2;
    const byte  M_S1 = 4;
    const byte  M_S2 = 5;
    // Slave IR mux sensor pins
    const byte  S_S0 = 6;
    const byte  S_S1 = 7;
    const byte  S_S2 = 8;
    const byte  S_S3 = 12;
    //  ANALOG PIN :
    const byte INPUT_FROM_MUX = A0;

    int  recv_state[TOTAL_IR_INPUTS];           // IR Readings - FROM mux set-up

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

        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);
        pinMode(S_S3, OUTPUT);
        pinMode(INPUT_FROM_MUX, INPUT);

        // set ADC prescaler of 32
        ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
        ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
    } // end of setup

    void loop() {

      unsigned long start = micros ();

      // read from IR diodes

      int whichLED = 0;
      for (byte master = 0; master < MUX_CHIPS; master++)
        {
        // select appropriate slave on the master MUX
        digitalWrite(M_S2, (master & 0b100) ? HIGH : LOW);
        digitalWrite(M_S1, (master & 0b010) ? HIGH : LOW);
        digitalWrite(M_S0, (master & 0b001) ? HIGH : LOW);

        // take each slave reading
        for (byte slave = 0; slave < LEDS_PER_CHIP; slave++)
          {
          digitalWrite(S_S3, (slave & 0b1000) ? HIGH : LOW);
          digitalWrite(S_S2, (slave & 0b0100) ? HIGH : LOW);
          digitalWrite(S_S1, (slave & 0b0010) ? HIGH : LOW);
          digitalWrite(S_S0, (slave & 0b0001) ? HIGH : LOW);

          // store this reading
          recv_state [whichLED++] = analogRead (INPUT_FROM_MUX);

          } // end of for each slave
        } // end of for each master

      // display results here ...

    } // of loop

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).

To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0_13 in which case you need to add 2 to the master value in the outer loop:

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

        // select appropriate slave on the master MUX
        byte master_plus_2 = master + 2;  // allow for not using input A0
        digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
        digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
        digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);

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


message:
Code output is not as expected

#include <LiquidCrystal.h>
    #include <SoftwareSerial.h>
    #include <Keypad.h>

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //three columns
    char keys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'E'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };
    int count = 0; char num[4];
    char key;
    byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

    char adhaar[4][4] = {
      {'1', '0', '8', '3'},
      {'9', '1', '6', '0'},
      {'5', '7', '6', '1'},
      {'6', '7', '9', '3'}
    };

    char adhaar0[4] = {'1', '0', '8', '3'};
    char adhaar1[4] = {'9', '1', '6', '0'};
    char adhaar2[4] = {'5', '7', '6', '1'};
    char adhaar3[4] = {'6', '7', '9', '3'};
    boolean check, control, adhar, tag_status;
    int i = 0, j, p, q;

    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
    void setup() {
      Serial.begin(9600);
      Serial.println(" enter your adhaar ");
    }

    void loop() {
      getkey();
      checkkey();
    }

    void getkey() {
      while (i < 4) {
        char key = keypad.getKey();
        if (key) {
          num[i] = key;
          Serial.print(num[i]);
          i++;
        }
      }
    }

    void checkkey() {
      if (i == 4) {
        control = true;
        for (p = 0; p < 4; p++) {
          for (q = 0; q < 4; q++) {
            if (adhaar[p][q] == num[q]) {
              check = true;
              Serial.println(num[q]);
            } else {
              check = false;
              Serial.println(" not eligile");
              break;
            }
          }
          if (check == true) {
            adhar = true;
            Serial.println(" cast your vote");
          }
        }
        i = 0;
      }
    }

My problem is once the adhaar matches with the values initialised in the array I have, it's going to "cast your vote" as expected, but after that it's again executing "not eligible" 3 times.

body:
First, a general remark: most of your variables are never used. You
should get rid of them, as they only serve to make your code more
obscure.

Then, the reason for the observed behavior is that you are comparing the
entered code with 4 predefined codes. Whatever the user enters, there
will be at least 3 non-matches, hence 3 times the program prints “not
eligile”.

To get the behavior you expect, I would get rid all all those boolean
variables that make the logic hard to follow, and instead break down the
problem into smaller chunks, each implemented in its own small function.
This makes it easier to write code that is easy to understand.

First, how do you tell whether two 4-character codes are the same? Like
this:

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

    // Do codes a and b match?
    bool match(char a[4], char b[4]) {
        for (int i = 0; i < 4; i++) {
            if (a[i] != b[i])
                return false;
        }
        return true;
    }

Then, given a code entered by the user, tell whether it matches
`adhaar[0]` or `adhaar[1]` or... or none of them:

    // Return the adhaar index matching the given key,
    // or -1 if there is no match.
    int matching_idx(char key[4]) {
        for (int i = 0; i < 4; i++) {
            if (match(key, adhaar[i]))
                return i;
        }
        return -1;  // no match
    }

Now your `checkkey()` function can be rewritten as follows:

    void checkkey() {
        if (i != 4) return;  // should never happen
        if (matching_idx(num) == -1)
            Serial.println(" not eligile");
        else
            Serial.println(" cast your vote");
        i = 0;
    }


message:
16*2 LCD display doesn't display my result

I am working on a project to calculate line frequency meter by reciprocal counting with Arduino. I am trying to print the the result on a 16*2 LCD but it is not displaying anything. It just gets on and stuck there. I got the project details from this website [Line Frequency Meter Based On Reciprocal Counting][1]

  [1]: https://electronicsforu.com/electronics-projects/line-frequency-meter-reciprocal-counting

I modified the stock program to interface the LCD but it's not working. Here is the code I am using:

    //To read and display the Line frequency
    //using Reciprocal counting method
    //clk for 'Time Counter'  is generated with 'Tone' function
    //'Time counter' is the physical counter T1
    // 'EVENT Counter' is a software counter
    #define Fin 6      // input pin for Line freq sig
    #define clk 7      // input to ' Time ' counter
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    boolean FState;   // status of the 50 Hz Signal
    int countS;       // Signal count
    int countC=0;     //  Clock count
    int LineFreq;     // Result

    void setup() {
      tone(8, 5000); // generates ref freq of 5000 Hz at Pin 8
      pinMode(Fin, INPUT); // set the Fin pin as INPUT
      pinMode(clk, INPUT); // set the clk pin as INPUT
      lcd.begin(16, 2);
    }

    void loop() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Frequency of signal");
      // to avoid partial cycles, first detect the rising edge
      while(digitalRead(Fin)) {
        //wait for '0' state of the Signal
        delayMicroseconds(10);
      }
      //here '0' state
      while(!digitalRead(Fin)) {
        //wait for '1' state
        delayMicroseconds(10);
      }
      //this is the rising edge of the Fin
      //counting can start from here
      // clear the TIME Counter T1
      counterStart1();
      //count 50 of the Line freq signals
      while(countS<50) {
        while(digitalRead(Fin)) {
          //wait for '0' state
          delayMicroseconds(1);
        }
        //here '0' state
        while(!digitalRead(Fin)) {
          //wait for '1' state
          delayMicroseconds(1);
        }
        // here '1' state
        // here one cycle is just over
        //increment the event counter
        countS=countS+1;
      }
      //here 50 Signal cycles over
      // read the contents of T1 & compute frequency
      countC = getCount1();
      LineFreq = 25000000/countC;

      //send to display
      lcd.setCursor(0,1);
      lcd.print(LineFreq);
      lcd.print(" Hz");
      delay(500);
      delay(100);
      // clear counter
      countS=0;
      // repeat
    }

    //The following code is obtained from on-line articles in the public domain
    void counterStart1() {
     // hardware counter setup,  for  the 16-bit Timer1 Timer/Counter
     TCCR1A=0; // reset timer/countern control register A
     TCCR1B=0; // reset timer/countern control register B
     TCNT1=0; // initialize the counter value to 0; this register holds the current count
      // set timer/counter1 hardware as a counter; it counts events on pin Tn (Arduino pin 5)
     TCCR1B = TCCR1B | 7; // Counter Clock source = pin Tn (Arduino pin 5) , start counting now
     // 7 in binary is 0111; OR-ing will set CS10,11,12 to 1's
    return;
    }

    // the following code is obtained from on-line articles in the public domain
    // Sub routine  to get the current count
    unsigned int getCount1() {
     unsigned int count; // this variable returns the current count from the counting register
     TCCR1B = TCCR1B & ~7; // Gate Off  / Counter T1 stopped,
     // this operation clears the bits (CS10,11,12)
     count = TCNT1; // read the counting register
     TCCR1B = TCCR1B | 7; // re-start counting by resetting the bits (CS10,11,12)
     return count; // return the retrieved count to the calling function
    }

I am getting a blank screen but the line at very first of the code "Frequency of signal" is printing accurately.

What is wrong with the code and what changes do I need?

Thanks in advance!

body:
Your variables are `int`, which on an Arduino is a 2-byte signed type by default, and has a range of `-32768` to `32767`.

When you execute:

    LineFreq = 25000000/countC;

is the result of the math a 2-byte `int`, or a 4-byte `long`? Regardless, you are possibly assigning a 4-byte value to an `int`.

You can declare `LineFreq` to be type `long`, and also append an `L` to the end of the constant value `25000000` to force `long` math, so that you have:

    long LineFreq;
    [...]
    LineFreq = 25000000L/countC;


message:
SPST switch - powered from pin output, or voltage regulator

I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.

The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.

Would a resistor be necessary for the digital in pin with either of these options?

body:
You could configure one of the digital pins as INPUT_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.

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

    const byte pinNumber = 3;

    void setup(){
      pinMode(pinNumber, INPUT_PULLUP);
    }

    void loop(){
    }


body: It is wasting of IO pins to use the digital output pin just to get +5V rail. But both options will work. Don't forget to use [pull/up or pull/down resistor](https://www.arduino.cc/en/Tutorial/Button), or activate [internal pull/up resistor](https://www.arduino.cc/en/Tutorial/DigitalPins) on the sensing pin. When the switch will be open, the input pin is not connected anywhere and will act as antenna, so it might pick up some noise.


message:
DHT22 Hanging Up Entire Program

In the process of learning and working on a larger project, I started by adding an `OLED` display (128x64, `SPI`). I wrote a simple script to update every 5 seconds and then display the number of seconds on both the `OLED` and the Serial port. This worked just fine and I even let it run for more than a day. Then I added a `DHT22`. This is where the issues started coming in. The `Arduino` `Mega` (clone) is powering both devices. I have a 10K resistor across the VCC and signal pins of the `DHT22`. The code should now update both the `OLED` and the serial port with the number of seconds and the temperature and humidity. This works, for awhile, and then the whole program freezes for some odd reason. The time before freezing is also at random intervals.

During my research it was suggested to add a 10uF capacitor across the ground and VCC. So I added a 10uF 50v cap and the results are still the same. Originally I had Serial.println(String(..... in the code, but I replaced all that to not use String(). I tried adding Serial.flush() at the end of the display code, but equal results.

Additional research also suggested waiting 30 seconds before trying to read the DHT22. I added this 30 second wait at the end of the setup function, but same results. I've tried checking for NaN, not checking for NaN and nothing has seemed to correct this issue.

I've also tried the program without the OLED. Same results. I've tried the program without the Serial output, but same results.

What is going on here and does anyone have any suggestions as to how to correct this?

Currently this whole thing is rigged up on a breadboard if that helps.

Below is the current code I'm trying:

    #include <Arduino.h>

    #include <SPI.h>
    #include <Wire.h>

    #include "DHT.h"

    #define DHTPIN 2
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);

    // Adafruit Libraries for the OLED display
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    // Setup the OLED variables
    #define OLED_MOSI   9 // D1 on the OLED
    #define OLED_CLK   10 // D0 on the OLED
    #define OLED_DC    11 // DC on the OLED
    #define OLED_CS    12 // CS on the OLED
    #define OLED_RESET 13 // RES on the OLED
    Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

    // Global variables
    unsigned long currentMillis;
    long previousMillis = 0;
    #define interval 5000

    float humidity;
    float fahrenheit;

    void setup(){
      // Start the serial port transmission
      Serial.begin(9600);

      // Start the OLED
      display.begin(SSD1306_SWITCHCAPVCC);

      dht.begin();

      // Clear the memory of the OLED
      display.clearDisplay();

      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setCursor(1,0);
      display.println("Madgayrah");
      display.display();

      while(millis()<2000);

      display.setCursor(0,16);
      display.println("Arduino");
      display.display();

      while(millis()<5000);
    //  while(millis()<30000);

      Serial.println("");
      display.clearDisplay();
    }

    void loop() {
      currentMillis = millis();

      if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;
        poll_and_display(currentMillis);
      }
    }

    void poll_and_display(long currentMillis){
        read_dht22();

        Serial.println(previousMillis/1000);

        if(!isnan(humidity) && !isnan(fahrenheit)){
          Serial.print(fahrenheit, 1);
          Serial.print("* ");
          Serial.print(humidity, 0);
          Serial.println("%");
        }

        display.clearDisplay();

        display.setCursor(0,0);
        display.println(currentMillis/1000);
        if(!isnan(humidity) && !isnan(fahrenheit)){
          display.setCursor(0,16);
          display.print(fahrenheit, 1);
          display.print("* ");
          display.print(humidity, 0);
          display.print("%");
        }
        display.display();

        Serial.println("");

        Serial.flush();
    }

    void read_dht22(){
        humidity = dht.readHumidity();
        fahrenheit = dht.readTemperature(true);

    //    while (isnan(humidity) || isnan(fahrenheit)) {
    //      unsigned long tempEnteredMillis = millis();
    //      while (millis() - tempEnteredMillis < 2500);
    //
    //      humidity = dht.readHumidity();
    //      fahrenheit = dht.readTemperature(true);
    //
    //      Serial.print("Result from NaN loop = ");
    //      Serial.print(fahrenheit, 1);
    //      Serial.print("* ");
    //      Serial.print(humidity, 0);
    //      Serial.println("%");
    //    }
    }

**UPDATE:**
After continuing to research on this I discovered that `Arduino` has a Watchdog Timer, or at least SHOULD have, and this SHOULD detect hang ups and restart the `Arduino`. So I tried a hardware version of the Watchdog Timer and a software version, but neither one seemed to work and/or correct the hang up/freeze issue. Below are the links I used for the software and hardware versions.

[https://circuits4you.com/2018/01/24/tutorial-on-arduino-watchdog-timer-setup/][1]

[https://blog.frogslayer.com/creating-an-arduino-watchdog-timer/][2]

  [1]: https://circuits4you.com/2018/01/24/tutorial-on-arduino-watchdog-timer-setup/
  [2]: https://blog.frogslayer.com/creating-an-arduino-watchdog-timer/

I then ran across another post about a different solution that I have implemented and it seems to be working, but I want to give it some more time just to be sure. More updates to come.

body:
Here is the solution. After searching last night I ran across this post [https://forum.arduino.cc/index.php?topic=517608.new][1] . Turns out, I was using the `Adafruit` DHT library and that seems to be what the issue was. I switched over to this [https://github.com/markruys/arduino-DHT][2] DHT library and it's been running for some 14 hours now with NO issues. Looking back through the Serial output I don't even see where it returned a NaN, not even once. I'm so excited to have this corrected and hopefully this will help out someone else stuck with this problem.

  [1]: https://forum.arduino.cc/index.php?topic=517608.new
  [2]: https://github.com/markruys/arduino-DHT


message:
Is there any way to group variables like group.variable as you can in Java/Delphi

I'm writing a sketch which does some calculations on measured variables, and it's based on a similar program written in Java like
c = A.Ux + B.Uz;
Where A&B have various parameters Ux,Uy,Uz etc
In Delphi this notation can be used either for parameters of classes or variables in a group. Looks like there's something similar in Java. It's a tidy way to organise and manipulate variables when there are lots of them and move them between methods without having huge numbers of arguments.

Is there any way to do this in the Arduino Wiring language? I don't seem to find anything online, but I'm probably phrasing the question wrong.
Thanks in advance, Brian

body:
What you are looking for is a `struct`:

    struct foo {
        uint8_t Ux;
        uint8_t Uy;
        uint8_t Yz;
    };

Then:

    struct foo A;
    struct foo B;

And:

    A.Ux = 3;
    B.Uz = 48;

    int c = A.Ux + B.Uz;

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:

    // By Reference
    int normal(struct foo &arg) {
        return (arg.Ux + arg.Uy + arg.Uz) / 3;
    }

    int avg = normal(A);

Or:

    // By pointer
    int normal(struct foo *arg) {
        return (arg->Ux + arg->Uy + arg->Uz) / 3;
    }

    int avg = normal(&A);

You can read more about structs [here](https://www.tutorialspoint.com/cprogramming/c_structures.htm).


message:
strtok() command with Serial communicaton

After I take a char* variable from serial communication, I use `strtok` to split variables with " ". But when I do that it acts like there is a " " after every character. I dont know why. How can I fix this ?

    void setup() {
      Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
      char* a = "The quick brown fox jumped over the lazy dog.";
      char* c = a3;
      char* b;
      b = strtok(c, " ");
      while (b != NULL) {
        Serial.println(b);
        b = strtok(NULL, " ");
      }
    }

    void loop() {
    }

outcome:

    The
    quick
    brown
    ...

This parsing code works perfectly, until I take it from serial ports. Serial code here, like this:

    #include <SoftwareSerial.h>
    #define bRSerial 9600
    #define bRmY 9600

    char vD[45];
    int i = 0;

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

    void setup() {
      Serial.begin(bRSerial);
      while (!Serial) {
        ;
      }
      mySerial.begin(bRmY);
    }

    void loop() {
      if (mySerial.available()) {
        //Serial.write(mySerial.read());
        vD[i]=mySerial.read();
        i++;
        if (i = 46) {
          char* a = vD;
          char* b;

          b = strtok(a, " ");
          while (b != NULL) {
            Serial.println(b);
            b = strtok(NULL, " ");
          }
          i=0;
        }
      }
    }

outcome:

    T
    h
    e
    q
    u
    i
    c
    k
    b
    r
    o
    w
    ...

Is there a way to fix this? i need to get it from serial and split on " ".

body:
only a syntax typo. the condition should be `if ( i == 46 ) {`

if this is not only a strtok test, the you do not need strtok. read in char c, and if `c == ' '`, print vD and reset i to 0

and I do not see where you set the terminating 0 of `vD` a.k.a. `a`


body:
As @Juraz mentioned, in the case you have a typo. Also I'd have suggestions as one who had spent a while coding reading process in terminal. When you need to read something from a serial port it is good to use the `while()` loop, instead of `if()`, so I recommend changing:

    while (mySerial.available()) {
      //Serial.write(mySerial.read());
      vD[i]=mySerial.read();
      i++;
      if (i == 46) {
        char* a = vD;
        char* b;

        b = strtok(a, " ");
        while(b != NULL) {
          Serial.println(b);
          b = strtok(NULL, " ");
        }
        i=0;
      }
    }


message:
Return mean of observations for a given sample time

new to this StackExchange site. I have an experimental setup with three inputs - two from a laser distance sensor to measure planar distance and one digital input from a set of callipers.

All sensors readings fluctuate over a small range (which is acceptable for my use case). Is it possible to have the Arduino record all inputs for a given period of time and output only the mean value for each sensor?

body:
I have this:

    int readElSens() {
      long sum = 0;
      int n = 0;
      long start_time = millis();
      while(millis() - start_time < 400) {
        sum += analogRead(ELSENS_PIN);
        n++;
      }
      return sum / n;
    }


message:
Getting error while uploading a sketch through Ardunio IDE

I recently used the Ardunio board and powered with the AVR pocket programmer along with the AVR ISP cable and it worked just fine and no issues were experienced. However now that i switch back to the default method of powering Ardunio board with USB, getting this error while trying to upload the sketch.

There are forums available on Arduino platform but no definitive resolution.

The board is recognized by the IDE.

[![Board ID Information][1]][1]

[![Snap Shot of the ERROR][2]][2]

  [1]: https://i.stack.imgur.com/gy982.png
  [2]: https://i.stack.imgur.com/aJXb1.png

body:
Reinstall the bootloader using your ISP programmer.

Installing a sketch using ISP first wipes the chip clean, and that includes the bootloader. Without the bootloader the USB interface won't be able to communicate with the main MCU.


message:
Custom function like yield

As far as I understand, `yield()` is used when you have long code (e.g. loop) so the background processing required by the esp8266 is not suspended for long time.

I have application where some sound should be running all the time and in the same time the program has to do other things which may includes long loops (that I call `yield()` inside them). Those long loops cause the sound to be discontinues.

What is the best idiomatic way of imitating the `yield()` function in my program so I do some thing like this:

    for(int i=0;i<10000;++i){
        yield();
        customeYield();
        someFunction(i);
    }
Where `customeYield()` contains the necessary instruction for playing the sound. It is exactly like this (I am using ESP8266Audio):

    if (mp3_->isRunning()) {
        if (!mp3_->loop()) {
            mp3_->stop();
            return true;
        }
        return false;
    }
    return true;

Of course, I can just call it like I did (making it global or something). However, I was wondering if there is a standard way for such a task.

body:
Without any hint, what you are actually doing in your long loops, it is difficult to say, what way would be the best for your case. I don't believe, there is a standard way of doing this, but there are basically only two ways of multitasking on a microcontroller:

 1. **Interrupt driven:** You can set a timer interrupt, that occurs regularly to call the `AudioGenerator::loop()` function (which fills the buffer with the next data).
 2. **Non-blocking code:** If you are using non-blocking code, you can first do one thing and then do another in sequence, so fast, that both codes are executed often enough. Thats exactly what the library you use is designed for (according to the README file).

If you are using more than one of these long loops in your `loop()` function, you may consider doing things with a finite state machine (FSM), so that you don't have to always add the `AudioGenerator::loop()` function to your long loops, but only once for the normal `loop()` function.


message:
interrupt pin of attiny85 unstable

I'm trying to learn how to program a MC, so maybe I didn't know much about a MC. I tried to test interrupt pin of ATtiny85 with this simple code

    #include <avr/io.h>
    #include <avr/interrupt.h>

    void setup()
    {
      GIMSK = 0b00100000;
      PCMSK = 0b00000001;
      sei();
      DDRB = 0b00010000;
    }

    void loop()
    {
      PORTB = 0b00010000;
      _delay_ms(500);
      PORTB = 0b00000000;
      _delay_ms(500);
    }

    ISR(PCINT0_vect)
    {
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);
      PORTB = 0b00010000;
      _delay_ms(100);
      PORTB = 0b00000000;
      _delay_ms(100);

    }
This is just a blink code with an interrupt to make the LED blink faster 10 times. My question is why sometimes the LED blink faster many times with the interrupt pin is not connected to anything (open)? Didn't it have internal pull up or should I use external pull up in my circuit?

Thank you

body:
The internal pullup is only activated, if you activate it in your code. To so, you have to write a `1` to the corresponding bit in the `PORTB` register, while the `DDRB` register is set for the pin to be an input.

So you the interrupt gets triggered randomly, because the pin was floating.

Since you are currently always write to the whole `PORTB`, you have to change the last bit to `1` on every `PORTB` write. Or you can write a `1` to it in `setup()` and only change the one output bit in `PORTB` by using

    PORTB ^= 0b00010000;

This will toggle only your output pin.


body:
More than an answer, these are some comments and suggestions on your
program, that I hope will help you write cleaner code:

1. Since you seem to be avoiding using the Arduino core library, you may
   as well write your own `main()` instead of relying on the one from
   the core. This way you have a plain C program that can be compiled
   either within or outside of the Arduino framework.

2. Instead of opaque constants, like `0b00100000`, use the bit names.
   These names are defined in the datasheet and are provided by the
   avr-libc. They are normally used with the `_BV()` macro, which
   expands to `(1<<(x))`.

3. For those of us who do not have the full datasheet in our head, a
   comment or two stating what each bit does is helpful.

4. To change only one bit from a port, use the syntax `PORTB |= ...;`
   or `PORTB &= ...`. The compiler is smart enough to turn this into
   single assembly instructions, namely `sbi` and `cbi`.

5. Rather than repeating ten times the same lines, use a loop.

Applying these suggestions, your program would like like;

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

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <util/delay.h>

    ISR(PCINT0_vect)
    {
        for (int i = 0; i < 10; i++) {
            PORTB |= _BV(PB4);
            _delay_ms(100);
            PORTB &= ~_BV(PB4);
            _delay_ms(100);
        }
    }

    int main(void)
    {
        PORTB = _BV(PB0);     // internal pullup on PB0
        GIMSK = _BV(PCIE);    // enable pin change interrupt
        PCMSK = _BV(PCINT0);  // sense pin change on PCINT0 = PB0
        DDRB  = _BV(PB4);     // pin PB4 as output
        for (;;) {
            PORTB |= _BV(PB4);
            _delay_ms(500);
            PORTB &= ~_BV(PB4);
            _delay_ms(500);
        }
    }


message:
Wake Huzzah Feather ESP8266 With Reed Switch

Forgive me if this is a really dumb question but I am new to IOT and hardware in general.

I have a Huzzah Feather ESP8266 and I am trying to make a bathroom occupancy sensor.  I am using a standard reed switch door sensor (example [here](https://www.sparkfun.com/products/13247)).

Ultimately what I want this device to do is:

 1. The plan is to wake the device from deep sleep when the door is closed, according to the documentation GPIO16 needs to be connected to RST to send a wake signal.

 2. Once awoken check the reed switch and send a message to Azure IoT hub that says the `bathroom is occupied` if door is closed.
 3. Put the device into deep sleep, waking every 30 seconds.
 4. Every time the device wakes check the switch, once the door is opened I send a message to Azure that the `bathroom is not occupied` and then put into `deepSleep(0)` (i.e asleep until the door is closed again, then the process repeats)

**Right now this all works but in the opposite. I can wake the device when the door is opened, the message sends successfully to Azure.**

From my super limited understanding of this it seems like what I want to do should be possible.  I imagine I am missing something very simple, but I have hit a wall here.

I dont know how to make wiring diagrams so hopefully a description of my setup will suffice:

 * GPIO 16: Door sensor wire #2
 * RST: GPIO 16
 * GND: Door sensor wire #2

Simplified code sample:

    void setup()
    {
     initSerial(); //inits serial
        initWifi(); //initis wifi
     door_open(); //sends message
    }

 void door_open() {
   IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

   if (iotHubClientHandle == NULL)
   {
  Serial.print("Failed on IoTHubClient_LL_Create\r\n");
   }
   else
   {
  // Because it can poll "after 9 seconds" polls will happen
  // effectively at ~10 seconds.
  // Note that for scalabilty, the default value of minimumPollingTime
  // is 25 minutes. For more information, see:
  // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
  unsigned int minimumPollingTime = 9;

  if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
  {
    Serial.print("failure to set option \"MinimumPollingTime\"\r\n");
  }

  if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
  {
    Serial.printf("failure to set option \"TrustedCerts\"\r\n");
  }

  if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, NULL) != IOTHUB_CLIENT_OK)
  {
    Serial.print("unable to IoTHubClient_SetMessageCallback\r\n");
  }

  IOTHUB_MESSAGE_HANDLE messageHandle;
  if(digitalRead(DOOR) == LOW)
  {
    messageHandle = IoTHubMessage_CreateFromString("closed");
    Serial.println("Door closed");
  }
  else
  {
    messageHandle = IoTHubMessage_CreateFromString("open");
    Serial.println("Door Open");
  }

  if (messageHandle == NULL)
  {
    Serial.print("unable to create a new IoTHubMessage\r\n");
  }
  else
  {
    MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);

    if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
    {
   Serial.print("failed to hand over the message to IoTHubClient");
    }
    else
    {
   Serial.print("IoTHubClient accepted the message for delivery\r\n");
    }
    IoTHubMessage_Destroy(messageHandle);
  }

  while (1)
  {
    IoTHubClient_LL_DoWork(iotHubClientHandle);
    ThreadAPI_Sleep(100);
  }
   }
 }

**To clarify:**  Right now my device will wake when the door sensors magnetic parts are separated.  I want the device to wake when the circuit is complete (i.e the sensors are _together_).

body:
The RST (reset) pin of the ESP works as the reset pin of any other microcontroller. If you pull it to LOW long enough (the threshold is surely listed in the datasheet), the whole microcontroller will reset as if you had cut and reestablished the power supply. So it will not wake it from sleep, but reset it completely.

It is correct, that you can use GPIO16 connected to RST, to let the ESP reset itself from a deep sleep. This seems to be an internal hardware functionality, that is distinct from the normal IO hardware. But you cannot use the same pin for some other functionality at the same time. Your reed switch is closed, if the door is closed. So it gives a LOW level to GPIO16 and RST, holding it in reset state. In this state no code is executed, thus you never get a message, that the door is closed. When you then open the door, the switch opens too. Since the RST pin isn't pulled to LOW anymore, the ESP can boot and execute your code. The door is open, so you get the corresponding message.

So you have to use a different pin for the reed switch.


body:
I would get an NC or NO reed switch, the opposite of whatever you have now that's backwards. I would then get rid of all the sleep wakeup stuff and turn the unit on through the reed switch, so it has power when the door is closed, if that's more common than it being open. When closed (powered), the MCU sends a ping on boot to a server that says "hey i closed", and go to deep sleep for 10 seconds.

Once re-awaking, send out a ping that says "I'm still busy". The server needs a tiny bit of smarts, a time-out feature that sets the door state as open 12 seconds after the last ping (10s + some accounting for wifi delays).

This setup uses NO standby power, and only a tiny amount of battery-killing on-time, so it should last a lot longer than trying to sleep and externally wakeup.

For added efficiency, consider building an ESPNOW router with two more ESP8266s. Once you have that ESPNOW router up and running, you can fire off a ping in about 200ms (from a cold/warm boot) instead of 2000ms with wifi, and go back to sleep. This extends your battery life ~10x, at the cost of running two more ESPs 24/7 where power is easily available.


message:
LiPo + charge/boost circuit vs pre-built "power bank" - contrasting portable power sources

Portable 5V power for my projects - I was about to get the necessary parts to wire up an OEM LiPo battery (3.7V battery, boost circuit, charging circuit) when I took a peak at pre-built "power banks".  From all the sources I see the LiPo batteries alone cost more than the power bank, at much lower capacity.  For reference:

 - a 10400 mAh power pack (max output 3A @ 5V) is 26$ on Amazon
 - a 10000 mAh power pack (max output 2.1A @ 5V) is 9$ on Hobby King
 - a 2500 mAh LiPo is 17$ on Amazon
 - a 5000 mAh Lipo is 8$ on Hobby King

The power packs already have charging and voltage regulation circuitry! The price difference makes me think I am missing something.

Reading around I notice issues with power packs auto-shutdown at low current draws. But other than this power packs seem cost optimal and technically equivalent - at least within the output amperage range of the power banks.

Questions:

 - Are there any technical differences in output voltage, lifetime, or otherwise I am missing here?
 - Are there any "surprises" I'm going to face by using a power pack?
 - Can you recommend a solid power pack that doesn't shut down at arduino level draws. (My app will draw 800mA @ 5V max, but during sleep, the draw of an Arduino Nano)

Thanks!

body:
The thing to remember with power banks bought on places like eBay and Amazon is:

* **THEY LIE ABOUT THE CAPACITY**

A typical power bank you would expect to get around 3600mAh from, even though it may say 10000mAh, 50000mAh, 1,000,000,000,000mAh, etc.

The only technical difference between rolling your own circuit and a power bank is the low-current switch-off that *many* (but not all) of them have.  That switch-off is fine if you are always drawing a good amount of current, but once your device goes to sleep and the current drops right down you'll find the power bank will switch off and your device will never wake up again.

However, with rolling your own system you know what you are getting. You know the capacity of your battery.

One further thing to consider: Do you *really* need 5V? The majority of electronics run from 3.3V nowadays, and the Arduino is no different. There are Arduino boards designed to run from 3.3V, and even 5V boards can be tweaked to run at 3.3V (albeit slower than normal).

So the ideal solution would be:

* A single-cell Li-Poly / Li-Ion giving nominal 3.7V
* A Li-Ion charger circuit
* A low-dropout or switching regulator with max 400mV dropout.

And no boost circuit needed. Also, no logic level shifting when communicating with 3.3V devices.


message:
How to configure location of preferences

I had been using Arduino 1.0.5 on my Pi, and in September last year downloaded `arduino-1.8.4-linux32.tar.xz` (which I have since updated).

I have been successfully using 1.8.5, but just noticed it seems to have been `/home/pi/.arduino15` for preferences and packages.

I probably did this inadvertently when I was briefly running both 1.8.4 and 1.0.5 (which is long gone). I have `/home/pi/.arduino` but this only contains `preferences.txt` and has not been used since September.

There seems to be no  way of changing this to the normal directory; where is this configured?

body:
Since the introduction of many enhancements in the IDE, such as the Boards Manager, and the Arduino Builder system, it was decided that this would break backwards compatibility with older versions of the IDE.  In version 1.5.0 of the IDE it was therefore decided that the location of all the Arduino data files (of which there are now many, not just a `preferences.txt` file) should be moved to a new location, and `.arduino15` was chosen to reflect the current version.

Since then a *version number war* broke out between the two Arduino factions, which was then subsequently resolved, and we ended up with the 1.8.x group of versions. These, since they haven't introduced anything drastic to the underlying system since 1.5.x, haven't needed to change the location of the data files (indeed, to do so would be undesirable), so it has remained as `.arduino15`.

I don't believe it's possible to change the preferences location, since the only place would be in preferences, and it would need to load the preferences to know where to load the preferences from.

If you *really* need to access the `preferences.txt` file yourself as `~/.arduino/preferences.txt` (why would you?) then you can just delete the old `.arduino` directory and create a link to the new one:

    $ rm -rf .arduino
    $ ln -s /home/pi/.arduino15 .arduino

----
Update:

There is a command-line argument to the Arduino IDE that lets you set the location of the preferences.txt file (detailed [here](https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc)):

    $ arduino --preferences-file /home/pi/.arduino/preferences.txt

However what that will do with an old preferences.txt file is anyone's guess.


message:
Stopping / starting DC motor with Limit Switches and on/off button

I have an Arduino UNO with 3 switches attached (2 limit switches, 1 activation switch). I'm trying to make the activation switch turn the motor forwards once hit, then wait for any of the limit switches to be hit and stop the motor. The next step is to wait for the activation switch to be hit again and turn the motor in the opposite direction and wait for the limit switch to be hit and stop the motor.

But the issue I'm facing right now is when i press the activation switch the arduino board and H bridge board restart. The LED's turn on and off and the code restarts. And nothing happens. I know all the switches and motor is working because i have tested them by simplifying the code with just the functions.

(edit) Here is a picture of the schematic: [![Schematic View][1]][1]

Can someone please review my code below to see if my logic is correct.

    const byte  frontButtonPin = 2;
    const byte  backButtonPin = 4;
    const byte  onOffButtonPin = 11;
    const int   motorPin =  8;
    const int   motorPin2 =  7;

    boolean  frontButtonState = 0;
    boolean  backButtonState = 0;
    boolean  onOffButtonState = 0;

    /**
        setup inputs for switches and outs for motor pins
        serial begin to read the switches to test for errors
    */
    void setup() {
      // initialize the pin as an inputs:
      pinMode(motorPin, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(frontButtonPin, INPUT);
      pinMode(backButtonPin, INPUT);
      pinMode(onOffButtonPin, INPUT);
      Serial.begin(9600);
    }

    /**
       this function turns motor foward
    */
    void drawMovesForward() {
      // turn motor foward:
      digitalWrite(motorPin, LOW);
      digitalWrite(motorPin2, HIGH);
    }

    /**
       this function turns motor backwards
    */
    void drawMovesBackward() {
      // turn motor in other direction:
      digitalWrite(motorPin, HIGH);
      digitalWrite(motorPin2, LOW);
    }

    /**
       Stop the motor form moving
    */
    void stopDrawFromMoving() {
      digitalWrite(motorPin, LOW);
      digitalWrite(motorPin2, LOW);

    }

    /**

    */
    void loop() {

      frontButtonState = digitalRead(frontButtonPin);
      backButtonState  = digitalRead(backButtonPin);
      onOffButtonState = digitalRead(onOffButtonPin);

      if (onOffButtonState == HIGH) {
        if ( frontButtonState == LOW ) {
          drawMovesForward();

        }

        else if (backButtonState == LOW ) {
          drawMovesBackward();
        }

      }
      else {
        if ( frontButtonState == HIGH ) {
          stopDrawFromMoving();
        }

        else if (backButtonState == HIGH ) {
          stopDrawFromMoving();
        }
      }
    }

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

body:
**Check your switches have pull-up resistors**

It would be helpful if your question included a schematic. Do you have pullup resistors in line with your activation and limit switches? If not, you might find the input is "floating" - that is, it will randomly return either HIGH or LOW. This would possibly cause the motor to go forwards and backwards, but because the loop is possibly occurring hundreds of times per second, you might not see anything moving. You need pull-up or pull-down resistors in the circuit so the Arduino can see a definite LOW or HIGH. See https://www.arduino.cc/en/Tutorial/Button for a tutorial with a resistor, or even better, use https://www.arduino.cc/en/Tutorial/InputPullupSerial and use the existing onboard pullup resistors on the Arduino, as suggested by [Juraj][1] below.

**Potential Logic Error**

There might be a logic error in this part of the code:

      if (onOffButtonState == HIGH) {
        if ( frontButtonState == LOW ) {
          drawMovesForward();
        }
        else if (backButtonState == LOW ) {
          drawMovesBackward();
        }
      }
      else {
        if ( frontButtonState == HIGH ) {
          stopDrawFromMoving();
        }
        else if (backButtonState == HIGH ) {
          stopDrawFromMoving();
        }
      }

Loop #1: Let's say the *onOffButtonState* is HIGH (someone has pressed the switch to ON). The drawer is closed, so the front limit switch is depressed, so *frontButtonState* is HIGH. So the program will execute **stopDrawFromMoving**, and do nothing. Currently you are saying nothing is happening, so this might be your issue.

What you will probably need to do is use flags and while loops. For example:

At the start of the loop() declare this

    drawerMovingOutFlag = 1;

Then change the loop to contain:

    if (onOffButtonState == HIGH) {
        if ( frontButtonState == HIGH ) {
            while(drawerMovingOutFlag == 1)
                drawMovesForward();
                if ( backButtonState == HIGH ) {
                    drawerMovingOutFlag = 0;
                    stopDrawFromMoving()
                }
            }
        }
        else ...

I'll let you do the rest!

  [1]: https://arduino.stackexchange.com/users/37622/juraj


body:
I actually had the right code all along but I just had to add delays when reading the limit switches and detecting the activation switches. Here is one of the original programs i wrote that i threw out thinking it doesnt work, but once the delays were added it works fine.

    // constants won't change. They're used here to set pin numbers:
    const int buttonPin = 4;     // the number of the pushbutton pin
    const int buttonPin3 = 11;     // the number of the pushbutton pin
    const int buttonPin2 = 2;     // the number of the pushbutton pin
    const int motorPin =  8;      // the number of the LED pin
    const int motorPin2 =  7;      // the number of the LED pin

    // variables will change:
    boolean buttonState = 0;         // variable for reading the pushbutton status
    boolean buttonState2 = 0;         // variable for reading the pushbutton status
    boolean buttonState3 = 0;   // variable for reading the pushbutton status

    int drawPosition = 2;  // Tells progam what position the draw is in

    /**
     *  setup inputs for switches and outs for motor pins
     *  serial begin to read the switches to test for errors
     */
    void setup() {
        // initialize the pin as an inputs:
        pinMode(motorPin, OUTPUT);
        pinMode(motorPin2, OUTPUT);
        // initialize the pushbutton pin as an input:
        pinMode(buttonPin, INPUT);
        pinMode(buttonPin2, INPUT);
        pinMode(buttonPin3, INPUT);
        Serial.begin(9600);
    }

    /**
     * this function turns motor foward
     */
    void drawForward() {
         // turn motor foward:
         digitalWrite(motorPin, LOW);
         digitalWrite(motorPin2, HIGH);
    }

    /**
     * this function turns motor backwards
     */
    void drawBackward() {
         // turn motor in other direction:
         digitalWrite(motorPin, HIGH);
         digitalWrite(motorPin2, LOW);
    }

    /**
     * Stop the motor form moving
     */
    void stopDrawFromMoving() {
      digitalWrite(motorPin, LOW);
      digitalWrite(motorPin2, LOW);

    }

    /**
     *
     */
    void loop() {
       // read the state of the pushbutton value:
       buttonState = digitalRead(buttonPin);
       buttonState2 = digitalRead(buttonPin2);
       buttonState3 = digitalRead(buttonPin3);

       // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
       if (buttonState == HIGH) {
          drawPosition = 2;
          Serial.println(F("Front button state is high draw is open"));
          stopDrawFromMoving();
       }else if (buttonState2 == HIGH) {
          drawPosition = 1;
          stopDrawFromMoving();
      }

      if (buttonState3 == HIGH) {
        if( drawPosition  == 1 ){
          drawBackward();
          delay(100);
          drawPosition = 2;
          delay(100);
        }else if (drawPosition == 2 ) {
          delay(100);
          drawForward();
          delay(100);
          drawPosition = 1;
        }

      }
    }


body:
I know this was opened years ago now but I just wanted to add some clarification. When I started this project and created this question I had 0 understanding of software development and didn't understand the code I was writing at the time. Now 3 years later I have revised this project multiple times.

The logic for a project like this is pretty simple, but if you're new to programming and trying to get into the STEM field with Arduino school projects and such, here is what my code now looks like for this same project:
https://github.com/LeehamElectronics/Automated-Cabinet

I have tried to comment it as best I could to help other students understand it. The project is simply a timber cabinet that has an electrically automated draw inside that can be opened and closed at will.

If you are stuck with a similar problem with your own project, I would suggest that you watch a free YouTube video course for C++ programing or even a Arduino programming video course. Even just a few hours of doing that will be enough to get started. That's the one thing I wish someone told me to do when I was starting off 3 years ago, I was wasting hours and hours debugging code that I didn't understand because I just jumped straight into Arduino with little understanding of coding.

I hope this comment helps someone else out there in a similar situation to mine 3 years ago.

Cheers

edit: the answers given about debouncing and pull-up resistors are also important in these types of projects.


body:
That is an excellent project. Great work.

Some suggestions for improvement. You could use a [`enum class byte`][1] instead of a `String` for the drawer position and the drawer moving direction:

```cpp
/* Allows the program to keep track of the last known position of the drawer */
enum class DrawerPositions : byte
{
  Closed,
  Open
} drawerPosition = DrawerPositions::Closed;

/* Keep track of what direction the drawer is moving, can one of the following:  Null | Closing | Opening */
enum class DrawerMovingDirections : byte
{
  Null,
  Closing,
  Opening
} drawerMovingDirection = DrawerMovingDirections::Null;
...
if (drawerPosition == DrawerPositions::Closed)
...
else if (drawerPosition == DrawerPositions::Open)
...
if (drawerMovingDirection == DrawerMovingDirections::Opening)
...
```

It would also be a good idea to add debouncing for all the switch inputs. There are many debouncing algorithms on the internet, but here is a very [simple debouncer][2] I put on GitHub which could be implemented something like this:

```cpp
#include "Debouncer.h"
...
void loop()
{
  static Debouncer limitSwitch0(limitSwitchPin0);
  static Debouncer limitSwitch1(limitSwitchPin1);
  static Debouncer manualToggleButton(manualToggleButtonPin);

  limitSwitch0.Update();
  limitSwitch1.Update();
  manualToggleButton.Update();

  if (drawerIsMoving == true)
  {
    if (drawerMovingDirection == DrawerMovingDirections::Opening)
    {
      if (limitSwitch0.Output() == LOW)  // Get the debounced output of the switch.
      {
        drawerPosition = DrawerPositions::Open;
  ...
  if(manualToggleButton.Rise())   // For rising edge trigger.
  //if(manualToggleButton.Fall())  // For falling edge trigger.
  {
    ...
  }
  ...
}
```

Here is a [debounce demo][3] I put on Wokwi.

  [1]: https://hackaday.com/2017/05/05/using-modern-c-techniques-with-arduino/
  [2]: https://github.com/TimMathias/Arduino-Debouncer
  [3]: https://wokwi.com/arduino/projects/302766933165474312