text:
Adding slave device to Arduino Uno-SPI | Configuring pins
I recently started an oled project. I use a small "128X64 OLED LCD LED Display Module" and I control it using SPI protocol(with my Arduino).
It is the only device connected to the microcontroller. But I have some questions regarding the pins. I found this tutorial and it uses pins 9 as DATA(known as MOSI) and 10 as CLK( or SCK). But the datasheet for my microcontroller(328) shows that pin 11 is MOSI and 13 is CLK.
Obviously..it works. So I think the program provided by the adafruit(that I used-Adafruit_SSD1306) took care of MOSI and generated the clock impulses on pin 10.etc. . But then what are those pins on the board and why are called like that? I mean it seems to me that everyone can just use other pins for MOSI/CLK(at least).What is their purpose?
Question #2: What does DC (or D/C) means?
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

VS

(328<=>128)

You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.
Here are the links to the relevant files in the library, so I can comment on them.

INO example file
Library header file
Library source file

Ok, first of all let's have a look at the example. you can see that the constructor is called as
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

When looking at the lines 144 and following of the source file, you can see
hwSPI = false;

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS), you will use the hwSPI.
Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.
You can also see it in the example:
// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.
As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data


text:
Student Code: map function not functioning
We made this code in class:
 int red = 6;
  int green = 7;
  int blue = 8;
  int pot = A0;
  int potVal = 0;
  int chosenColor = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(pot, INPUT);
  Serial.begin (9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  potVal = analogRead(pot);
  chosenColor = map(potVal, 0, 1023, 1, 3);
  if(chosenColor = 1) {
    redCycle();
  }

  else {
    analogWrite(red,255);
  }

  if(chosenColor = 2) {
    greenCycle();
  }

  else {
    analogWrite(green,255);
  }

  if(chosenColor = 3) {
    blueCycle();
  }

  else {
    analogWrite(blue,255);
  }
  Serial.println(chosenColor);
  Serial.println(potVal);
  delay(500);
}

void redCycle() {
    analogWrite(red,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(red, i);
  }
}

void greenCycle() {
  analogWrite(green,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(green, i);
  }
}

void blueCycle() {
  analogWrite(blue,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(blue, i);
  }
}

When we open the serial monitor we find that chosenColor is always 3 regardless of what the potVal is reading. I am sure is something simple but we can't find where is the error. Please help.

analogWrite() doesn't work on pins 7 and 8, only on those bearing the "~" symbol.

Ok that is one problem we didn't think about! Thank you. Still not sure why the map function is not working.

chosenColor = 3 means “let chosenColor take the value 3”.

As Edgar Bonet pointed out,  “chosenColor = 3 means 'let chosenColor take the value 3'”.  That is, your  potVal = analogRead(pot);  chosenColor = map(potVal, 0, 1023, 1, 3); sequence may very well be working, but by the time you get to Serial.println(chosenColor); you have changed chosenColor to 3.
First, the statement if(chosenColor = 1) {...} changes chosenColor to 1. Then the statement if(chosenColor = 2) {...} changes chosenColor to 2.  Finally, if(chosenColor = 3) {...} changes chosenColor to 3, just before you print out the current value of chosenColor.
When you wish to compare two numeric values for equality, use == instead of =.

Aha! I get it. So I need to use ==. We will change that.

You are confusing = (assign) with == (compare).
eg.
Wrong! ...
if (chosenColor = 3)  // this assigns 3 to chosenColor

Correct:
if (chosenColor == 3)   // compare

Still not sure why the map function is not working.

You just assumed it is not working. Before making assumptions like this do a Serial print to show what the return value of the map function is. (Directly after calling map - not later on in the code).

I thought that <= would mean less or equal than. How would I do a greater than or equal to?

<= reads "less than or equal to"; >= is "greater than or equal to".

Although not related to your main problem, I would like to point out
that there is an issue with your use of the map() function. Or maybe
I should say, with the map() function itself. Since it works with
integer arithmetic, and integer division by default rounds towards zero,
you get a mapping that may be quite different from what you expect.
In the table below, I am showing the result of
map(potVal, 0, 1023, 1, 3). The column labeled “not rounded” is what
you would get if the mapping was done in floating point. The last column
is the rounded value you actually get out of map():
potVal  not rounded  rounded
----------------------------
    0     1.00000       1
            ...
  511     1.99902       1
  512     2.00098       2
            ...
 1022     2.99804       2
 1023     3.00000       3

As you see, you have 512 possible values of potVal mapped
to 1, 511 values mapped to 2 and one single value mapped
to 3.
I assume you would rather have one third of the range mapped to each
value. This can be achieved by writing map(potVal, 0, 1024, 1, 4):
potVal  not rounded  rounded
----------------------------
    0     1.00000       1
            ...
  341     1.99902       1
  342     2.00195       2
            ...
  682     2.99805       2
  683     3.00098       3
            ...
 1023     3.99707       3

This gives 342 values mapped to 1, 341 values mapped
to 2 and 341 values mapped to 3. Now, the problem is that
this way of using map() is confusing. You may prefer to write
something more explicit instead, like:
if (potval < 1023/3) chosenColor = 1;
else if (potval < 1023*2/3) chosenColor = 2;
else chosenColor = 3;

Not sure if this helps but I wanted a slider with a range of 0 to 200 to give 3 values; 0 for the first third of movement, 1 for the second third and 2 for the last third
I used map(slider value, 0, 134, 0, 2)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
RFID working with interrupts
I recently created a rfid project with the sensor rfid rc522. I used the instructions mentioned by this site and works perfectly. However, I intend this project to be battery supplied and I want to make the system use as low current as possible using the low power library. Well I need arduino UNO hibernate until an interrupt by the rfid is occured. Any proposals on how am I going to detect an interrupt by the rfid?
(PS) If there is any better battery saving library that can detect interrupts while keeping arduino slept, then feel free to propose it to me.
Thank you in advance.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

you want to saturate the 2222, then pretend avail ma is infinite, resist from there

Sorry i forgot to reply, but thanks a lot @dandavis your comment helped me a lot.

@dandavis what do you mean by "saturate"? what equations should be used?

@shinzou: that's now explained in the accepted answer

Here is a diagram from Peter Bennett's answer to an  Electronics Stackexchange question,  How much voltage to give my IR LED?:

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.

I have some questions, can i use the 5V arduino output as the source of energy to the led? (in the diagram is the 3.3V input).
I did the math here and i got 22.5R for 80mA instead of the 18R he said is nedded to get 80mA, why i got a different number? For the voltage i did 3.3V - 1.5V (the current of the ir led).
How can i know the correct number of the base resistor? Could i use lets say a 10kR?
Nevermind about the first question, i saw after that the led actually use 1.8V

I edited a bit about the base resistor, and included an equation about it.  With R1 = 10KΩ, Vcc = 5, Vbe = .7, you would get 0.43 mA into the base, and say 43 mA load current (if hFE is 100); so 10KΩ is too much resistance.  Re using  5V arduino output for LED current, most Arduinos are ok supplying a few hundred mA to auxiliary circuits like LEDs, if incoming raw voltage is not too high.  The descriptions at arduino.cc sometimes say how much current can be drawn through the onboard regulator, but to be certain may require reading the regulator's part number and looking it up on the web.

I see, eletricity is hard to gasp but im slowly learning. Thanks for all the help.

What are the parameters for hFE*(VCC-VBE)/RB in the picture? Also where are they in the transistor's spec?

For the 2N3904 shown in the diagram, DC Current Gain hFE and Base-Emitter Saturation Voltage VBE(sat) are shown on page 2 of the spec sheet, in the “ON CHARACTERISTICS” table.  Re other parameters used in the  hFE*(VCC-VBE)/RB equation: VCC depends on Arduino supply voltage, and  RB = R1.

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

I know i can only power for a fraction of time. Thats why i said it was a 1:10 cycle (1 cycle on and 10 cycles off with 100ms per cycle).
Im already sending the signal with 32kHz and i can't filter the receiver since i didn't make it, im only doing a controller not a receiver.
Anyway it worked as far as i know. The led is receiving about 70mA. What was before a 30cm range is now about 7m range. So i guess i did something right sending more amperage. In theory i could go even further and try to reach 80mA but im happy with the final result.
Anyway thanks for the tip.


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

m1a,m1b,m2a,m2b are the motor pins. ena, enb are the pwm pins from the driver(l298n). I am currently using an arduino uno, and hc-sr04 ultrasonic sensor and a l298n motor shield

Please edit your question (click "edit") and include the information from your comment in the body of the question.  Also, please edit your question and mark the code as code.  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.

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();
 }
}

oh well..the robot now is stuck right now.

Stuck as in not moving at all or stammering at a particular spot?

Not moving at all

I created a variable called maximumDistance, and if the current distance is smaller than that, the obstacle is considered close enough. It's the same with the closeThreshold variable

nope. it's not working at all

I made an edit in the source code and nothing happens. I made a function which calculates the currentDistance, but no results so far

Is there any values coming from the ultrasonic sensor?

Actually no. I mean i used the serial.print() function and it just displays text from the if statement in the serial monitor

OK...i tried with a sample code and now i get values from the sensor

Integrate your main code with the sample code, the robot should be able to move

So...i just did what you said. No results. With the sample code works as charm(The values come continuously and in the implemented version, they come one by one and the motors are just stuck)

http://arduinobasics.blogspot.nl/2012/11/hc-sr04-ultrasonic-sensor.html this is the sample code

i removed the functions and tested the code just like that

I think the problem lies in your moveForward() and turnRight() function: you are delaying 1s everytime you call the function. So the whole loop delay would be ~1 second per cycle. Maybe reduce the delay in it?

Plus can you update the implemented version of code into the body of the question as an update? Easier to see what you have changed.

ok so...any ideas? removing the delay didn't work


text:
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. 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?

Please, post the actual sketch your are using. This one doesn't compile and your lcd declaration is wrong.

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


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

Was the board turned off?  The reset button doesn't do anything if no power is attached to the board.

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.

Everything in RAM (non persistant memory) will be erased. progmem/flash and EEPROM are persistant and will not be erased.

you can't erase RAM any more than you can erase a projector screen; electrons+photons erase themselves.

Actually, pressing RESET doesn't erase RAM. It resets the CPU and sets all SFRs to power-on defaults, but the RAM remains the same. It's the code that is added to the start of your program (crt0.o) that erases the BSS area and copies any other defaults into place from flash. The rest of RAM continues to hold what was in there before. Of course, with no power applied it's all rubbish anyway, since nothing is happening.


text:
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:
#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?

if you want to use just a few pins, get a few cheap shift register ICs, like the  74HC165.

Tested on Nano v3.0 and it works flawlessly with this exact code. You can't use A6 and A7 as they are analog inputs only.

The problem i was going through is because of pin number 13. Pin 13 is connected to LED and is not good option for taking input as it is connected to 3.3V internally. Because of this arduino was detecting one key pressed constantly making other key presses undetected. In this case the key was charecter *.

ADVICE: Don't use pin 13 for input!

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.

i tried that but nano is unable to take inputs from keypad. Keypad is working fine on mega.

You'd better try with another Nano if the solution Jot proposed not working.

it's working when tested separately but not with the whole 400 lines code which worked perfectly on mega. i changed pin numbers etc but no result.

Could the problem be a memory problem ? What does the compiler say about sram (dynamic) memory usage. Do you use large arrays or many String objects ?

In fact that, 4x4 keypad programming with Arduino is quite straight forward. So, I am surprised you have an issue with that . Since we can't see the entire code, it is hard to give a proper look and answer accordingly. You maybe do some debugging with some "Serial.print(yourvariable)" to see where the bottleneck is. As Jot has also mentioned that the memory is quite an issue when you use memory consuming large array or struct in the code. I am not talking about the memory used when you complied but in run time.

Thank you all of you guys for trying to help me. But just now i discoverd the problem. its wriiten in answer.


text:
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 two resistors are mentioned for pin 3 and 7.
In Example 2 only one resistor is used.
In YouTube example 3 three resistors and a capacitor is used. See around 5:25.
My questions:

Is one of those three better (and why)?
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.

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:

thank you very much ... some more reading to do, thanks for the right naming/functionality of the capacitors. In the example of the youtube video (3th example) at 5:25, pins 1 and 3 (and 7) have a resistor and the capacitor is going from those resistors to either GND or +5v (I cannot see) but in the schematics the pins 1, 3, 7 and 8 all goes to the capacitor from +5 to GND so I do not see how the schematics and the breadboard map? Can you explain this?

@MichelKeijzers Updated. Btw, it's even more difficult if you have custom board :D

Thank you again KIIV .. for the coming months I will stay away from prototype boards probably ... so I will use the breadboard solution I have now, but add the capacitor on the breadboard as in example 3. Still not sure exactly how to place the capacitor in my case, however, I will first read and maybe it gets clear automatically.

@MichelKeijzers Like this: http://i.imgur.com/vRvhIhy.png (it's pretty much the same for 8pins chips)

Thanks ... so in my case in http://www.bing.com/images/search?view=detailV2&ccid=%2f7BbflDG&id=B3D333677F7B9C059EC35C0294DFAEA2F33F7015&q=23lc1024&simid=607995735057761174&selectedIndex=11&ajaxhist=0 I have to put e.g. a 0.1nF between pins 4 and 8?

Ah That is really clear (the pic you added). I guess always (or mostly) pins 4 and 8 are +5V and GND (or at least the two opposite pins) ... I just have a few ICs yet, so I haven't noticed it.


text:
Which library to use for 23LC1024 SRAM 1 Mbit
I noticed there are quite some libraries for the 23LC1024 SRAM 1 Mbit memory:

SpiRam Extended library
SpiRam library
Direct SPI ?

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?

since they both use the SPI  lib, SPI.setClockDivider matters. a lot on RAM. digitalWrite is slower than the PORTB stuff. there's overhead in sending, so shipping many bytes at once saves "handshake" time. put the tricks together for max speed. might update the code to use https://www.arduino.cc/en/Reference/SPISettings

@dandavis Thanks for that information ... I hope I can get it to work since I also want to connect an SD card via SPI so have to change the settings probably when switching between SD and SRAM (this will only be needed in the first second after startup and only to transfer 128 KB in 512 byte blocks (so 256 times), afterwards I don't need the SD anymore.

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.

Thank you for the very detailed answer ... I don't think I will go for SQI for now, since I'm a beginner, however I will check into the byte versus page modes. I guess I will find in the libraries what is used.  So maybe I have to adapt the manual if I want to use both ways. My idea is to use quite some lookup tables so a smart layout of the memory map in the SRAM might be useful.

Hello! I use Arduino Due and i require external ram to be read/written fast for real time audio. What is SQI?

@user1584421 Serial quad interface. Like SPI but uses 4 data bits instead of 1 for transfers.

Thanks! Are there chipsets like the 23LC1024 that provide external RAM that can be used with arduino DUE for quick r/w? Are you aware of any?

Or do you think 23LC1024 would be suitable for realtime audio? (using the ADCs and DACs).

Depends on the bit depth and sample rate you want. It may be possible, yes. In have done 44.kHz stereo 16 bit from SD card over SPI before.

I am doing fine with the 12 bit ADCs from DUE.. Does that give you a clue on if the 23LC1024 is suitable for me? I just need more RAM. (Also, thanks a lot for your help!)

It's faster than an SD card, so I'd say yes, sure. As long as you code it well. Using DMA would be the best way of doing things, at least for the ADC and DAC access. All my audio work has been on the PIC32MZ using DMA and an external audio DAC chip through I2S.

I have to stick to the DUE due to external libraries. 23Lc1024 supports DMA? Its only today i figured i need more RAM

It doesn't care about DMA. DMA is what the sure does to communicate with it at high speed.

This was an excellent challenge for an SPI bus manager and device driver support library I have been working on. Below are some performance results for the SRAM (23LC1024) device driver (Arduino Uno @ 16 MHz, SPI @ 8 MHz) read/write us per byte, kbytes/s, in benchmark.
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 allocation, caching, handling of large vectors, and streams on external storage. Please see https://github.com/mikaelpatel/Arduino-Storage for more details; benchmarks, example sketches, etc.

I got with my test for 1 byte: 23,49 us/byte, for 8 bytes: 6,70 us/byte, for 100 bytes: 4,06 us/byte, for 1000: 3,86 us/byte. So yours are really faster. However, I decided to not use the 23LC1024 since I want to store some more complicated structures and 'real' RAM (being able to use real variables/pointers etc) is more comfortable. Therefore I ordered a 192 KB STM32 (which causes me a lot steeper learning curve which I'm still busy with).

Actually there is more speed to be gained by interleaving (pipelining) the SPI transfer with data collect. All the SPI wait cycles can be used. The SPI library does some pipelining of the data fetch/store to the buffer. The data access (read/write) and the pointer increments are done while waiting for the SPI transfer. My next challenge is to add a file system/heap on the SRAM and then a Stream binding so that it can work as a ultra fast intermediate Serial for trace etc.

To be honest, I never checked much inside the library itself. Sounds like an interesting project you are doing. It seems like external SRAM is good for continuous regions (and reading less or more bytes from it). Like in your case a file system. To use it as 'real' SRAM is complicated or impossible (meaning to have any kind of variables) to be either using internal SRAM or external SRAM (and even not be aware of the difference as the user of SRAM).


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

Did you double tab the reset button to force it into bootloader mode? Then try the upload.

Thank you for your suggestion. I just tried this, but still no luck.

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
iam getting this errors while uploading a blink program to esp8266 pls help me

sidagam sankar, please try the different solutions listed below.

You can try, turn off esp modul board and turn on and start flashing again

Returning to this, the issue still persisting, I tried once more with the
flashing software.
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.

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.

After a lot of trial'n'error, this was the solution for me. Very frustrating!

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

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 CH340and driver for CP2102) and try again:)

Thank you for four answer.
Both my PCs says the CH340 is already installed and the other one installed with no further notice. However it still says the same.

i had a same problem . then as above said i uninstalled the what i installed drivers early . and reinstalled the drivers . and baude rate is 115200 .and uploaded the file. thank you sampath from srilanka

Please verify which you have before downloading random drivers.  The CH340 is rectangular, which the CP2012 is square.

Thank you for the advice. I did heed your warning and started downloading the CH340 driver from random places, which lead to a lot of malware and ultimately i had to format my laptop.


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

what command you use to connect network? what error you get? what is the error with cpin command?

Are you giving it enough power?

Yes I am, the AT commands are working and it shows me available networks as well. Actually now when I looked at the available network and the signal strength, the carrier of the sim card installed is not appearing. Only two other networks, does this mean the module is not compatible with the network of the sim installed? Can it be that the sim card is 3G?

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.


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

BTSerial.read() reads a single byte.

and serial write seems working ok, because there you don't move cursor

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);


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

NodeMCU can be programmed from the Arduino IDE. You just need to instal the board files.

Is there any thing similar to that ?

Why would you want anything else? It seems that you want something, but have no idea what? The NodeMCU is a good choice for general IO over wifi.

You know I wanted to know what are the other choices

the d1mini is like the nodemcu only smaller and no extra power pins. esp32s are under $10 now/

D1 is not compatible with Blynk

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. 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. 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 would give a lot of memory and a good supply of IO.

But the price tag is quite high

Yep that's why I said the NodeMCU is cheap. The Yun has a preconfigured linux/linnino server so in theory its networking is much more powerful than the Esp8266


text:
Two outputs: which one "leads" the other?
I have a problem with my Arduino Uno and my AS5311 position sensor
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):
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:
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?

Search this site for “rotary encoder”. Even though yours may not be rotary, it's exactly the same problem.

On a rising edge of A check the state of B, if it's high B is leading A, if it's low A is leading B.

Thanks for your helpful comments. I updated my question accordingly.

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 to the question How to read RPS for fast rotation with status change method in Arduino?, 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.

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 methods for  handling quadrature inputs, 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” at eevblog.com – from which the first diagram below is taken – and in Omapl137 linux eqep driver at ti.com, where the second diagram is from.  Both those sources provide substantial detail about processing quadrature inputs.

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 usually is a better choice when dealing with asynchronous transitions like encoder inputs.
By “indirect IO” I mean use of functions like digitalRead() and 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 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 and Simple Pin Change Interrupt on all pins 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
}

Could you please elaborate on why rotary encoders tend to lose count and how the solutions you suggested solve the problem? I don't only want it to work, I would also like to understand. I should mention that this is the first time I've ever used a microcontroller so I am a total beginner (know a thing or two about C++ though).

@Mario, see edit

In addition to this excellent answer I have a page about rotary encoders.


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

Why you are using  'LiquidCrystal_12C.h  library for display ?

What LCD are you using?

Because my lcd have I2C shield. I'm using 20x4 LCD display with I2C shield.

Might need to consider the int range in this statement; "rpm = (60000000/duration);"

what is suitable for the rpm formula??

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);

I truly believe my lcd is not the problem. I am using a 20x4 LCD display with I2C shield. I have tried running the code from the website https://www.instructables.com/id/Simple-Motor-Speed-Tester-Tachometer/ . The changes I have made on the code from the website was changing the LCD command and use the command for LCD 20x4 I2C.  When I tested it, the rpm sensor works and the rpm displayed on the lcd.  However, combing it with my own coding of speed and time control, the sensor does not work and no rpm display on lcd

Did your check whether the if statement was executed? Coz if it does not, there would never be a delay in your main loop, and you would not be able to see anything in your LCD Display

Other than that, did you check whether the getTheNumber() function is working properly, outputting the correct values?

Before I add the rpm measurements code, the speed and time control coding work perfectly fine, just how I wanted it to be.  Now with the addition of rpm measurement code. The rpm of the spinning motor is not show on the LCD.   Is this have something with delay()??   Does the delay() causing the reading of rpm not shown of the LCD??  Is there any other way for me to change my coding so that the speed, timing and rpm  measurement work as a single functional unit?

Maybe you can try out something like multi-threading of the display (or Protothread for Arduino's case)? There are quite a few examples on it online.


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

}

You need to have the program remember whether the light are ON or OFF. That way you can check the see if they are already on, before calling start.

The PWM is not supposed to turn off all by itself: last thing you wrote is 255, and it should stay at that level. It looks to me like this is not a software problem, but rather a hardware issue. Just for testing, replace your LED by a low power one (a standard 3 mm or 5 mm LED) in series with a resistor in the 220 Ω – 1 kΩ range. If it works with this setup, then you know it is a power supply issue.

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;
  }
}


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

}

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);`

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);

Please enhance your answer: Correct the typo in "cmd". Add some words what is different to the existing code.

Please use DigiKeyboard.print(cmd);

And why do you think that will open CMD in administrator mode?


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

Are you sure that the com port is 6 instead of 10? If the Arduino IDE doesn't have problems uploading on that port, should you try 10? Or did you just plug it into a different port that time you programmed it

I recommend reading the "Uploading Code to the Leonardo, Leonardo ETH and Micro" section of https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro. There are some special things that need to be done to upload to the ATmega32U4 boards: First the serial port is opened at 1200 baud and then closed, which signals to the firmware that it should reset the microcontroller. After the reset that serial port disappears and the IDE waits for a new port to appear before uploading to that port. Some of this may be done via the IDE rather than solely AVRDUDE. You could try using the Arduino IDE CLI instead.

@CarrotM No, the two commands you see where issued directly after one another, the Arduino was plugged into the exact same port. The IDE displays the Arduino being connected on COM6 in the GUI as well.
Trying to use COM10 on cmd leads to a hard fail with a "system couldn't find this path" error message, so it's just the IDEs verbose mode bugging out there.

@per1234 that seems to be a good indication of what's going wrong, I'll try that out this evening!

Ok, I managed to make it happen. Thanks for your help!

@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
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.


text:
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;

        }

    }

}

To mark code as code: In the editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. (To highlight text click-drag across it or use the arrow keys while holding the shift key.)  Note, short bits of code are enclosed in back-ticks, like ` which is why part of your text is formatted that way

you Can use Switch case. Switch(val) then take action according to value

In which case you want to switch the state to LOW? What is the meaning of two thresholds?

What behavior do you want in the 554570-558872 data?    I think I'd use some https://en.wikipedia.org/wiki/CUSUM filtering to debounce the level  signal, and maybe use some separate logic for switching into or out of the flex state.

I'd think there are 4 distinct states you should to keep track of separately: idle, flexing, flexed, and relaxing.

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

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;
}


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

actually When you uploading a sketch to your board through USB programing port that time the skect might go to the serial device which is connected with Arduino through Rx and Tx pin

@Prayuktibid I couldn't see any signal on pins 0 or 1 with a scope when using the USB port, even with those pins set to an output.

@Prayuktibid he is using a Leonardo which has separate USB and hardware serial.

How to use USB and TX/RX at the same time?

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.

Great, thanks. Do you know how this compares with other boards? Apparently the Uno can't do use both.

Arduino Uno can't do this, it has only one hardware serial.
Atmega 2560 has 4 hardware serials.
Having multiple serials are always handy. With Uno you just stuck and have to use software serial if the case more than one serial. Most of the time Software Serial doesn't treat you well, it is just a workaround after all.


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

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?

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.

This video from "GreatScott" covers this type of project very well. https://m.youtube.com/watch?v=57carjNxI9A

In the Atmega datasheet, you can read that 16mhz may not work at 3V. You'll probably have to program it using an USBasp or something comperable, to also be able to change the fuse bits.

It may also help to have some kind of feedback that indicates whenever a full turn has been made. This way the display can be synchronized to the speed of the motor, and keep orientated right. Then you can most likely alsof skip the LM317

Why not use an Arduino LilyPad?

Welcome to StackExchange.  Be sure to take the Tour at https://arduino.stackexchange.com/tour to see how it works here.

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

Indeed.  If the motor is powered by something else, this could work at a low clock rate.  But if the motor is supposed to be powered by this circuit, ie, it rotates itself, then a more capable power source is needed.

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


text:
'SoftwareSerial' does not name a type in Adafruit Feather M0 Bluefruit LE
I am trying to create a software serial connection between Arduino Uno & Adafruit Feather M0 Bluefruit LE.
I am getting the following error in the M0 sketch:
Arduino: 1.8.1 (Windows 10), Board: "Adafruit Feather M0"

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

 SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

 ^

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

 Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,

                               ^

exit status 1
'SoftwareSerial' does not name a type

Here are the modifications I did to the atcommand sketch (in Adafruit BluefruitLE nRF51 library) before uploading to the M0:
#include <Arduino.h>
#include <SPI.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
  #include <SoftwareSerial.h>
#endif

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

#include "BluefruitConfig.h"

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

SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

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

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

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

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

I  tried to comment the if statement before #include <SoftwareSerial.h>, I got the following error:
Arduino: 1.8.1 (Windows 10), Board: "Adafruit Feather M0"

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

   #include "SoftwareSerial.h"

                              ^

compilation terminated.

exit status 1
Error compiling for board Adafruit Feather M0.

What is the problem?

SoftwareSerial is not available for the Zero core. There are so many HardwareSerial ports to use instead :) https://forum.arduino.cc/index.php?topic=341054.0

THANK YOU .. It finally works .. really appreciate your help ..