message:
Using a transistor to get 100mA on a IR led

What i saw is that the led use 1.3V on 100mA with a 1:10 Cycle (100ms). Im currently at 30mA using only a 100 resistor, but the range of the led is 20cm at max, i want to get at least 2 meters.

Since i know the max output of the Arduino pin is 40mA i need to use a transistor to get the 100 i want. And that is the problem, i read a lot about how transistors works but i can't yet understand how can i achieve 100mA using a transistor.

I did the math using 5v and got 37R.

Is this correct? So i need to use a 37 ohms resistor to get the 100mA i want?

And this resistor is going between the digital input and the transistor base, correct?

Im using a NPN 2n2222 and reading the datasheet 100mA is easy job for this transistor.

I appreciate any help.

body:
Here is a diagram from [Peter Bennett's answer](https://electronics.stackexchange.com/a/163496/7479) to an  [Electronics Stackexchange](https://electronics.stackexchange.com/) question,  [How much voltage to give my IR LED?](https://electronics.stackexchange.com/q/163494):

[![transistor driver][1]][1]

As you can see, the current-limiting resistor is in series with the IR LED and the transistor's collector.  The base resistor is large relative to the current limiting resistor, because this transistor amplifies base current by a factor like 100.

The 1000 Ω base resistor is ok for loads into the neighborhood of 100 mA; if you plan to drive a larger load, use a smaller base resistor.  As noted in the 2N3904 datasheet, hFE may be as small as 30 when  IC = 100 mA.  To ensure transistor saturation, arrange that  hFE*(VCC-VBE)/RB exceeds desired collector current.

2N2222 specifications are similar to those of the 2N3904 mentioned in the question, but hFE drops off more slowly (as IC increases) for the 2N2222.

See the Electronics Stackexchange question linked above for more discussion and further links.

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


sender: user

sender: assistant

body:
Increasing the power to the LED isn't the best way of increasing the distance. In fact it's the worst way.

The 100mA is only for a small duty cycle. You can power it with 100mA but only for a fraction of the time. The overall average light output won't be any more than at 30mA.

The problem you are actually suffering from is the fact that your receiver can't distinguish the LED's light from the background light. That is simple to overcome though. You just need to modulate your LED with a high frequency (typically 30kHz or higher) and perform a high pass filter and amplification on the receiver.

Exactly the same way that remote controls do it.

That way you can distinguish the LED (flashing at a given frequency) from the background light (static brightness or relatively very slowly changing).


message:
move forward and turn right

i have a project about making an obstacle avoiding robot. But this one is a bit special. I want the robot to move forward and when an object is close to it, to turn right. https://i.stack.imgur.com/Vfnzi.png

    #define echoPin 7 // Echo Pin

    #define LEDPin 13 // Onboard LED

    #define m1a 4

    #define m1b 3

    #define ena 9

    #define m2a 2

    #define m2b 5

    #define enb 8

    int maximumRange = 200; // Maximum range needed

    int minimumRange = 0; // Minimum range needed

    long duration, distance=0; // Duration used to calculate distance

    void setup() {

    Serial.begin (9600);

    pinMode(trigPin, OUTPUT);

    pinMode(echoPin, INPUT);

    pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

    pinMode(m1a, OUTPUT);

    pinMode(m1b, OUTPUT);

    pinMode(m2a, OUTPUT);

    pinMode(m2b, OUTPUT);

    pinMode(ena, OUTPUT);

    pinMode(enb, OUTPUT);

    }
      void moveForward()
     {

     digitalWrite(LEDPin, LOW);

     digitalWrite(m1a, LOW);

     digitalWrite(m1b, HIGH);

     analogWrite(ena, 180);

     digitalWrite(m2a,HIGH);

     digitalWrite(m2b,LOW);

     analogWrite(enb,180);

     }
     void turnRight()

    {

     digitalWrite(LEDPin, HIGH);

     digitalWrite(m1a, LOW);

     digitalWrite(m1b, LOW);

     analogWrite(ena, 100);

     digitalWrite(m2a,HIGH);

     digitalWrite(m2b,LOW);

     analogWrite(enb,100);

     }

    void loop() {

     digitalWrite(trigPin, LOW);

     delayMicroseconds(2);

     digitalWrite(trigPin, HIGH);

     delayMicroseconds(10);

     digitalWrite(trigPin, LOW);

     duration = pulseIn(echoPin, HIGH);

     //Calculate the distance (in cm) based on the speed of sound.

     distance = duration/58.2;

    if (distance <= maximumRange && distance >= minimumRange){
        turnRight();
    }
    else {
    /* Send the distance to the computer using Serial protocol, and
    turn LED OFF to indicate successful reading. */
     moveForward();
    }

    //Delay 50ms before next reading.
     delay(50);
    }

body:
> I want the robot to move forward and when an object is close to it, to turn right.

How close do you want the robot to be to the obstacle? You should at least declare some form of threshold to determine what values are considered "close". (Maybe a *closeThreshold* variable)

> while(distance>=maximumDistance) { moveForward(); if(distance<=maximumDistance) break; } turnRight();

As for the code you have posted, why not use a simple if else function with a *closeThreshold* variable instead of a while loop?

    ...
    void loop() {
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

     //Calculate the distance (in cm) based on the speed of sound.

     distance = duration/58.2;
     if(distance<=closeThreshold) {
     turnRight();
     } else {
     moveForward();
     }
    }


message:
Arduino Uno Sensor DHT11 Failed to read from DHT sensor

I get this error every time. I used the DHT tester file from [this library][1]. Which gives me an error.

And then I realized that in my code Arduino recognizes only the `readTemperature` function, not `readHumidity`, but it doesn't give any compile error. Also, when I read the sensor, this is the output:

>Humidity Sensor Test
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%

My code is here:

    //DHT11 Sensor:
    #include "DHT.h"
    #define DHTPIN 5 // which digital pin we're connected to
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

    //I2C LCD:
    #include <Wire.h> // Comes with Arduino IDE
    #include <LiquidCrystal_I2C.h>

    // Set the LCD I2C address
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    void setup() {
      Serial.begin(9600);
      delay(300);
      lcd.begin(16,2);
      Serial.println("Humidity Sensor Test");
      dht.begin();
      delay(300);
    }

    void loop() {
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      int h = dht.readHumidity();
      int t = dht.readTemperature();

      // set the cursor to (0,0):
      lcd.setCursor(0, 0);
      // print from 0 to 9:

      lcd.print("Temp: ");
      lcd.print(t);
      lcd.print("C");

      // set the cursor to (16,1):
      lcd.setCursor(0,1);
      lcd.print("Humidity: ");
      lcd.print(h);
      lcd.print("%");

      Serial.print("Temp: ");
      Serial.print(t);
      Serial.print("C, Humidity: ");
      Serial.print(h);
      Serial.println("%");
      delay(2500);
    }

Also I have the 10k resistor between data and Vcc pins. Data is connected to digital pin 5. Has anyone had this problem before?

  [1]: https://codeload.github.com/adafruit/DHT-sensor-library/zip/master

body:
There are several versions of the DHT11 library for Arduino out there. This is the one that worked for me: https://github.com/adidax/dht11. Here is a simple sketch to test the sensor with the output going to the serial monitor.

    // 5k ohm pull up resistor is used on the data line.
    // Sensor operates at 5VDC.
    // Data line connects to Arduino Uno pin 3.

    #include <dht11.h>
    dht11 DHT11;
    #define DHT11PIN 3

    // Sensor calibration. Start with 0 for each.
    const int HumidityCorrection = -10;          // -10 worked with my sensor.
    const int CelsiusTemperatureCorrection = 2;  // 2 worked with my sensor.

    const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

    // Update the serial display every 60 seconds.
    const float UpdateSerialDisplay = 60000;

    // Celsius to Fahrenheit conversion.
    double Fahrenheit(double celsius){
      return 1.8 * celsius + 32;
    }

    void setup(){
      Serial.begin(9600);
      // Minimum wait for good data recommended is 1 second.
      delay(2000);
      Serial.println("DHT11 TEST PROGRAM ");
      Serial.print("LIBRARY VERSION: ");
      Serial.println(DHT11LIB_VERSION);
    }

    void loop(){
      Serial.println("");
      int chk = DHT11.read(DHT11PIN);
      switch(chk){
        case DHTLIB_OK:
          //Serial.println("OK");
          break;
        case DHTLIB_ERROR_CHECKSUM:
          Serial.println("Read sensor: Checksum error");
          break;
        case DHTLIB_ERROR_TIMEOUT:
          Serial.println("Read sensor: Time out error");
          break;
        default:
          Serial.println("Read sensor: Unknown error");
          break;
      }

      Serial.print("Humidity: ");
      Serial.print("\t");
      Serial.print(DHT11.humidity + HumidityCorrection);
      Serial.println(" %");

      Serial.print("Temperature: ");
      Serial.print("\t");
      Serial.print(DHT11.temperature + CelsiusTemperatureCorrection);
      Serial.println(" C");

      Serial.print("Temperature: ");
      Serial.print("\t");
      Serial.print(round(Fahrenheit(DHT11.temperature) + FahrenheitTemperatureCorrection));
      Serial.println(" F");

      delay(UpdateSerialDisplay);
    }

Once you get this working you can add the LCD code to it. Here is a link to the DHT 11 Humidity & Temperature Sensor manual / data sheet: http://www.micropik.com/PDF/dht11.pdf


message:
Does the reset button work when not powered?

I'm working on a project and my dad hit the reset button on my Arduino board, unknowingly. If it wasn't connected to any power source or computer, did it still reset? Do I have to upload my code to the board again? Or does the board need power to be reset?

body:
The reset on an Arduino does not erase anything. It merely restarts execution of an already uploaded program. Also the AVR needs to be powered on for it to realize whether it has been reset.

Every time you power on an Arduino it automatically starts code execution from the beginning of the program in the flash memory.


message:
Analog pins for 4x4 matrix keypad

I am working on a project on nano and want to use analog pins for 4x4 matrix keypad input. My connections are for keypad are as follows:

- Digital pins are D10-D13 and Analog pins are A0-A3.
- A0->14,
- A1->15,
- A2->16,
- A3->17

Code is:

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

    #include <Keypad.h> // includes the keypad library
    const byte ROWS = 4; // four rows
    const byte COLS = 4; // four columns
    char keys[ROWS][COLS] = {
     {'1','2','3','A'},
     {'4','5','6','B'},
     {'7','8','9','C'},
     {'*','0','#','D'}
    };

    byte rowPins[ROWS] = {10,11,12,13}; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {14,15,16,17}; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

Can I use analog pins as I defined for keypad? Is "Keypad.h" library compatible with Arduino Nano v3.0?

body:
You can use the analog pins. I prefer {A0, A1, A2, A3} in the code instead of {14, 15, 16, 17}. That makes it easier to check if you connected the wires to the right pins.

Don't use pin 13 for an input with the Arduino Nano. An LED is connected to that pin. You can use that pin as an output for something else.


message:
Resistors/capacitor used in connecting 23LC1024 SRAM 1 Mbit

Yesterday I received by 23LC1024 SRAM with 1 Mbit memory.

I tried to search for some libraries and ways how to connect it.

So I searched around on internet first for the connections and saw some different ways of doing it, especially regarding the pullup resistors.

E.g. in [Example1][1] two resistors are mentioned for pin 3 and 7.
In [Example 2][2] only one resistor is used.
In [YouTube example 3][3] three resistors and a capacitor is used. See around 5:25.

My questions:

1. Is one of those three better (and why)?
2. Is the capacitor in the youtube example 3 connected to GND or 5v? I cannot map the schema with the breadboard since the capacitor should run between +5 and GND but I don't see the +5 or GND connection (depending on where the capacitor is connected to which I cannot see or deduce).

Btw, I got it working with the 2 resistor solution but just wondering if example 1 is good enough or example 3 is better.

  [1]: https://thearduinoandme.wordpress.com/tutorials/external-sram-23lc1024/
  [2]: https://ucexperiment.wordpress.com/2013/02/26/more-memory-arduino-and-23lc1024/
  [3]: https://www.youtube.com/watch?v=eIP_w5uizNw&t=417s

body:
It's better to use external pull-up resistor at least on `CS`. It's because MCU pins are configured as INPUTs without pull-ups just after the startup/restart before it gets into the `setup()`.

Also I'd recommend decoupling capacitor as close as possible to the SRAM power supply pins (between `Vcc` and `Gnd`). You can google what the decoupling capacitors are (they are also called bypass capacitors).

Edit: First two examples are supposed to be on bread board. So it's not so hard just rewire it, if you have to use for example `/HOLD` too. However the third example is soldered on prototype board and therfore it's not so easy to rewire it. That's why `NU` and `/HOLD` inputs are connected to the Vcc through `10k` resistor. If you have to use `/HOLD` in the future, it's easier to just solder new connection, than rewire hardwired connection to the Vcc.

About decoupling caps - there are even sockets with builtin cap:
[![8pin socket with decoupling capacitor][1]][1]

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


message:
Which library to use for 23LC1024 SRAM 1 Mbit

I noticed there are quite some libraries for the 23LC1024 SRAM 1 Mbit memory:

1. [SpiRam Extended library][1]
2. [SpiRam library][2]
3. [Direct SPI ?][3]

I tried 1 and 3 so far. What I noticed was that to read 1 byte took around 18 us for the 3th solution and around 25 us for the first library. However, the first has possibilities to read multiple bytes and that considerably speeds up the time.

Also there are other libraries like MQTT and possibly I missed some.

However, in all cases I would expect speeds around just a few us. Since I maybe need to read 100 of different small groups of bytes preferably within 10 us (and process them), it might get problematic in worst case scenarios.

Does anybody know where the speed differences come from or if there are ways to increase the speed or which library is fast?

  [1]: https://thearduinoandme.wordpress.com/libraries/spiram_extended/
  [2]: http://forum.arduino.cc/index.php/topic,182918.0.html
  [3]: https://ucexperiment.wordpress.com/2013/02/26/more-memory-arduino-and-23lc1024/

body:
SPI RAM has two modes of operation: single byte and "page mode".

In single-byte mode you first send the read or write command followed by the (typically 3-byte) address and then read a byte. That's 5 bytes per transaction, or 40 SPI clock cycles. At the maximum of 8MHz (SPI_CLOCK_DIV2 on a 16MHz MCU) that would be at absolute best (1/8000000*40) 5µS per byte read or written. That's not including the time taken to toggle the CS pin and perform the other software-level parts of controlling the SPI peripheral.

In page mode it is possible to send one *start* address and then read or write sequential data *from* that address upwards. Ideal if you need to read a larger number of bytes that are sequentially in memory. For instance, to read 100 bytes sequentially it would take 104 SPI bytes - one for the read/write command, three for the start address, and 100 for the data. That is 832 SPI clocks, or at 8MHz, 104µS.

As you can see, reading 100 bytes within 10µS is not possible on an Arduino with SPI SRAM. There just isn't enough speed. Even 100 sequential bytes. 100 "small groups of bytes" just ain't gonna happen.

There are other technologies that are faster which may be more suited to your use, but they require different peripherals in the chip (namely SQI), and the chips with that in tend to be more powerful and have more RAM anyway, so your 1Mb of external SRAM would be redundant.


body:
This was an excellent challenge for an [SPI][1] bus manager and device driver support library I have been working on. Below are some performance results for the [SRAM][2] (23LC1024) device driver (Arduino Uno @ 16 MHz, SPI @ 8 MHz) read/write us per byte, kbytes/s, in [benchmark][3].

    write: 9.875 + N*1.4275 us, max. 700 kbyte/s
    read: 9.875 + N*1.5 us, max. 670 kbyte/s
    where N is the number of bytes transfered

The protocol overhead (9.875 us) is 1) slave select pin handling, and 2) command byte and 24-bit address (four bytes header in total).

Cheers!

Update [2017-09-25]

@MichelKeijzers I recently had time to work on an abstraction of external storage and refactor a number of device drivers to support the new interface. The abstraction includes memory [block][4] allocation, [caching][5], handling of large [vectors][6], and [streams][7] on external storage. Please see https://github.com/mikaelpatel/Arduino-Storage for more details; benchmarks, example sketches, etc.

  [1]: https://github.com/mikaelpatel/Arduino-SPI
  [2]: https://github.com/mikaelpatel/Arduino-Storage/blob/master/src/Driver/MC23LC1024.h
  [3]: https://github.com/mikaelpatel/Arduino-Storage#23lc1024-spi-sram-8-mhz
  [4]: https://github.com/mikaelpatel/Arduino-Storage/blob/master/examples/Block/Block.ino
  [5]: https://github.com/mikaelpatel/Arduino-Storage/blob/master/examples/Cache/Cache.ino
  [6]: https://github.com/mikaelpatel/Arduino-Storage/blob/master/examples/Vector/Vector.ino
  [7]: https://github.com/mikaelpatel/Arduino-Storage/blob/master/examples/Stream/Stream.ino


message:
NodeMCU espcomm_sync failed

I have a NodeMCU ESP12E DevKit V2 from Geekcreit. I had it working some months ago, but now I cannot upload to it. I am using the arduino IDE and I've set the "Additional Boards Manager URLs" to:

> http://arduino.esp8266.com/stable/package_esp8266com_index.json

The error I get:
----------------

> warning: espcomm_sync failed
>
> error: espcomm_open failed
>
> error: espcomm_upload_mem failed

What I've tried so far:
-----------------------

 - Applying 3.3v to the VIN
 - Uploading from 3 different PCs and one Ubuntu
 - Uploading using Arduino IDEs: 1.6.18, 1.6.2, 1.6.9, 1.6.11
 - Using the esptool.exe to upload to it from the cmd prompt.
 - Using following board configurations from the Arduino IDE:
    - "NodeMCU 1.0 (ESP-12E Module)"
    - "NodeMCU 0.9 (ESP-12 Module)"
    - "Generic ESP8266 Module"
    - "NodeMCU 1.0 (ESP-12E Module)"
 - Uploading with different upload speeds.
 - Uploading with different flash sizes.
 - Uploading with different USB cables.
 - Tried erasing flash, read flash.

All of the above has still resulted in the error stated in the top of this post.

Verbose output from upload:
---------------------------

    Arduino: 1.6.11 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

    Build options changed, rebuilding all

    Sketch uses 222,213 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
    Global variables use 31,588 bytes (38%) of dynamic memory, leaving 50,332 bytes for local variables. Maximum is 81,920 bytes.

    C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM1 -ca 0x00000 -cf C:\Users\xxx\AppData\Local\Temp\build48b2fca13fb12d7c15d8dce627beccb2.tmp/Blink.ino.bin
    esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
        setting board to nodemcu
        setting baudrate from 115200 to 115200
        setting port from COM1 to COM1
        setting address from 0x00000000 to 0x00000000
        espcomm_upload_file
        espcomm_upload_mem
        setting serial port timeouts to 1000 ms
    opening bootloader
    resetting board
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    resetting board
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    trying to connect
    An error occurred while uploading the sketch
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    resetting board
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    trying to connect
        flush start
        setting serial port timeouts to 1 ms
        setting serial port timeouts to 1000 ms
        flush complete
        espcomm_send_command: sending command header
        espcomm_send_command: sending command payload
        read 0, requested 1
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed

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

https://pastebin.com/GCq6aZsR

I was beginning to suspect that my NodeMCU board is broken somehow, but the old file is still uploaded on the device is active on my network, so if it is broken, it might just be the usb port.
**EDIT**: Just received a new module that gives the same error, so it is not due to faulty hardware.

However, I have found people facing the same issues when googling, but no real solution has worked for me, and the above list of what I've tried is mostly suggestions found in this process.

I'm running low on ideas and I am thinking to order a new NodeMCU board to try and rule out flawed hardware.

Any suggestions or help will be much appreciated. Thank you.

body:
Maybe there's something wrong with your driver.
Check which module of USB-to-UART of your NodeMCU is using.As far as I know, there're two most common modules:CH340 and CP2102.
Just download the driver ([driver for CH340][1]and [driver for CP2102][2]) and try again:)

  [1]: http://www.driverscape.com/download/usb-serial-ch340
  [2]: http://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers


body: Same issue here. For me it was a hardware issue. The esp chip had solder that did not flow from the pads of the board to the esp board. To confirm this, before programming press down on the wifi module and keep pressed during programming. If it is a solder issue, it should program just fine. If it programs, you need to reflow all solder joints around the esp chip. Hope it helps.


body:
Try these steps:
1. Use a different USB port.
2. Go to Device Manage and check if the driver is installed. If already installed, uninstall it and then install it from Device Manager(worked for me, was having the same issue).
3. Nodemcu could be corrupt (faced same error and got it changed).


body:
Returning to this, the issue still persisting, I tried once more with the
[flashing software][1].

After flashing the NodeMCU I was once again able to upload to my NodeMCU from the Arduino IDE.

So no hardware flaws and no need for new drivers.

  [1]: https://github.com/nodemcu/nodemcu-flasher


message:
SIM800L Arduino Pro Mini

I am trying to send an SMS using the Sim800L module and it seems to be unable to connect to the network. When I send the AT+COPS=? command it shows me a list of all the available networks along with the carrier of the sim card inserted but the module is unable to connect to the network. AT+CPIN returns an error as well. I read that changing the antenna will help but I don't think this can be the case as the networks are being detected. What could be going wrong?

body: Make sure that you are giving it enough power, seaching and registering to a network needs a current peak of 2amps, if the model you are using has a built-in regulator plug it to a stable 5v 2amp source of power and try AT+COPS? again, it should work; you can try with the computer power supply it has a 5v 2amp source.


message:
Bluetooth serial readings on 0.96'' Adafruit OLED

I am trying to display the readings of LDR connected to slave arduino through serial monitor of master arduino paired with bluetooth. I got the readings and it is working fine.

But when I connected OLED to the master arduino so that the LDR readings can be displayed on OLED as well as serial monitor, it is not displaying as expected.

So for simplicity I tried sending the word "hello" from slave to master. The code for slave is :

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup() {
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      BTSerial.begin(9600);
      Serial.begin(9600);
    }

    void loop() {
      BTSerial.println("hello");
      Serial.println("hello");
      delay(1000);

    }

Then I tried displaying the same only on serial monitor of master. The code:

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(10, 11); // RX | TX
    char state ;

    void setup() {
     pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
     digitalWrite(9, HIGH);
     BTSerial.begin(9600);
     Serial.begin(9600);
     Serial.println("<Arduino is ready>");
    }

    void loop() {
     if (BTSerial.available()) {
       state = BTSerial.read();
       Serial.write(state);
     }
    }
It is showing valid readings in serial monitor with hello being printed after every one second

    <Arduino is ready>
    hello
    hello
    hello
    hello
But when I modified the code so that I can get the readings on OLED as well as serial monitor;

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(10, 11); // RX | TX
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #define OLED_RESET 4
    Adafruit_SSD1306 display(OLED_RESET);
    char sensor;
    void setup()
    {
      Wire.begin();
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);// initialize with the I2C addr 0x3C (for the 128x32)(initializing the display)
      Serial.begin(9600);
      BTSerial.begin(9600);
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
    }

    void displayreading()
    {
       if (BTSerial.available()) //checks for incoming data
        {

          sensor = BTSerial.read();//reads data from bluetooth serial
          display.clearDisplay();
          display.setTextColor(WHITE);
          display.setCursor(30,0);
          display.setTextSize(1);
          display.print("LDR Reading:");
          display.setCursor(30,10);
          display.setTextSize(2);
          display.print(sensor);
          Serial.write(sensor);
        }
    }

    void loop()
    {
        displayreading();
        display.display();
    }
The OLED is showing one letter at a time clearing the screen after every letter rapidly (since I did not add delay which will add up to the problem of data lag). Like :
h , (clear screen)
e (clear screen)
l (clear screen)
l (clear screen)
0 (clear screen)

The serial monitor is showing the readings as:

    <Arduino is ready>
    hello
    hello
    hello
    hello
But the word hello is printed letter after letter and not in a whole like in the previous master code.There is one second gap after every printing of "hello".

Can somebody please help me with this problem?
Thanks in advance

body:
Instead of BTSerial.read(); there should be

    String content = "";
    char character;

    while(BTSerial.available()) {
         character = BTSerial.read();
         content.concat(character);
     }

and then you send content to lcd by putting

    display.write(content);


message:
What should I use for IOT Things?

I am very much interested in using the Blynk. Well I like it because of its feature. I want to control or read my sensors or something like that remotely. So Blynk says you need something like esp8266 or BLE stuff or something similar. I came across NodeMCU and Ethernet shield. I want to buy something that is efficient for reading my sensors. Is there anything similar that is similar to NodeMCU and is Arduino IDE compatible.

body:
I am assuming Esp8266/NodeMCU does not have enough IO for your application? (It combines Wifi with Arduino for little cost and is compatible with the Arduino IDE development tool)

Aruino have a different solution called the [Arduino Yun][1]. The problem with the Yun might be that it doesn't have very much memory and is based on the Atmel 328 processor (which has some IO but maybe not enough for you).

An alternative I have heard good reports about is the [Dragino Yun Shield][2]. That is a shield that provides powerful networking, sits on any Arduino board and works the same as an Arduino Yun. Therefore a Yun Shield sitting on an [Arduino Mega2560][3] would give a lot of memory and a good supply of IO.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardYun
  [2]: http://www.dragino.com/products/yunshield/item/86-yun-shield.html
  [3]: https://www.arduino.cc/en/Main/arduinoBoardMega2560


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

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

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

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

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

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

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

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

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

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

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

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

      Serial.begin(9600);

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

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

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

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

      digitalWrite(CSn_Pin, HIGH);

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

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

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

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

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

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

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

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

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

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

   Serial.begin(4800);

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

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

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

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

   digitalWrite(CSn_Pin, HIGH);

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

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

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

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

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

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

---

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

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

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

---

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

> LiquidCrystal_I2C(0x3F,16,2);

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

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


message:
Arduino leave PWM on

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

    #include <DS3231.h>

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

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

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

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

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

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

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

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

    }

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

    }

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

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

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

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

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

To summarize, the code could look something like this:

    #include <DS3231.h>

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

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

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

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

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

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

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

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

    }

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

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


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

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

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

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

    }

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

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


body:
You can use this code :

Explanation of the code

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

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

```


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

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

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

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

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

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

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

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

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

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

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .^C

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

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

body:
@per1234 was correct:

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

*From [Arduino.cc][1]*

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

    $ avrdude -patmega32u4 -cavr109 -PCOM6 -b1200

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

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

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

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

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


message:
EMG control of solenoid valve

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

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

    const int ledPin=13;

    const int sensorPin= 0;

    int level;

    const int threshold1=400;

    const int threshold2 =500;

    void setup() {

        pinMode (ledPin, OUTPUT);

        pinMode (sensorPin, INPUT);

        Serial.begin(9600);
        }

    void loop(){

        level= analogRead(sensorPin);

        if (level > threshold1){

        digitalWrite(ledPin, HIGH);

        if (level > threshold2)

        digitalWrite(ledPin, LOW);

        }

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

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

Here's the code:

    const int ledPin=13;

    const int sensorPin= 0;

    int level;

    int flex= 0;

    int PreviousState = 501;

    const int threshold1=600;

    void setup() {

        pinMode (ledPin, OUTPUT);

        pinMode (sensorPin, INPUT);

        Serial.begin(9600);
    }

    void loop() {

        level= analogRead(sensorPin);

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

              {

                flex =!flex;

              }

              if (flex == 1)
              {

                digitalWrite(ledPin, HIGH);

              }

              else

              {
                digitalWrite(ledPin, LOW);

              }

              PreviousState = level;

            }

        }

    }

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

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

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

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

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

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

in setup

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

    ...

in loop

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


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

    ...

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

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

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

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

    ...

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

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


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

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

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


message:
POV using ATmega328 powered with cr2032 cell

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

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

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

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

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

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

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

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

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

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

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


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

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

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


message:
Control Android Camera using Arduino over Bluetooth

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

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

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

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

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

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

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


message:
Arduino connection to brainwave analyzing module

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

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

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

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

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

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

Good luck.


message:
Can an interrupt function call a regular function?

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

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

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

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


body:
Yes you may.

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

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


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


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

The right answer is yes and no.

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

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

The typical solutions are:

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

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


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

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

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

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

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

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

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

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


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

Background:

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

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

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

Questions:

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

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

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

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

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

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

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


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

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

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


message:
Working with multiplexers for constant voltage output

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

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

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

Below is my current Arduino sketch:

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

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

    int testValue = 255;

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

      pinMode(SIG_pin, OUTPUT);

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

    }

    void loop(){

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

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

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

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

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

      //return the value
      return 0;
    }

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

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

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

Happy to start offer a bounty to a helpful answer.

Thank you

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

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

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

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

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

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

      pinMode(SIG_pin, OUTPUT);

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

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

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

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

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

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

      //return the value
      return 0;
    }


message:
Arduino Video player?

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

if yes please tell me.

thanks in adavance

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

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

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

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


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

**Questions:**

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

**Background/Detail:**

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

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

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

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

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

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

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

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

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

    float v = (rawVIN*5.0)/1024.0;

to

    float v = (rawVIN*4.75)/1024.0;

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

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

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

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

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

    analogReference(INTERNAL);

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

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

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

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

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


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

**What can you do about it?**

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

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

Source: [analogReference][1]

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

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

Source: [ATmega328 datasheet][3]

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

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

**Bonus**

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

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

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

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

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


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

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

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

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


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

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

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

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

The linked page describes how you might choose resistor values.

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


message:
Arduino Interrupt example not working

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

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

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

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

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

    void blink() {
      state = !state;
    }

This is my setup:

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

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

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

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

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

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

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


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

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

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

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

    void setFlag()
    {
        flag = true;
    }


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

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

the rest remains unchanged.

here is how it works:

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

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

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

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

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

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

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

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

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

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


message:
Is the DigitalWriteFast library still needed?

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

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

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

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

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

Now I get different values:

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

Without the fast library:

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

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

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

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

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

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

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

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

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

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

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

    void loop(){}

The result was:

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

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

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