title: Logging small capacitance

text:
# Question
Title: Logging small capacitance
I'm measuring capacitance of a system using a multimeter, and found that the value is very small (fluctuate from 50pF to 100 pF). The system is dynamic so the capacitance changes over time.

Now I need to log this value to some text file (csv for example). How could I do this with Arduino? If it's resistance, I could have built a simple voltage divider and sense the voltage using ADC. Also C is very small, I haven't been able to construct some measuring circuit for C.

# Answer
Because the capacitance to be measured is well below 1 nF (50-100 pF), you'll encounter serious problems trying to measure it with the ADC of the Arduino due to its input capacitance (14 pF according to datasheet). Add the stray capacitances of wires, headers and the Arduino board itself and you'll easily end up with 25 pF input capacitance, which is in the same order of magnitude of what you're trying to measure (= A VERY BAD THING).

What to do, then? Well, the main options are these...

## Use an external measurement circuit

This would mean including active devices (op amps, comparator, timers...) and precision passive components. A true HW-based solution.

The accuracy of the measurement in this case would be entirely up to the design (circuit topology and component selection) of the external circuit. The circuit would provide either an analog voltage or a signal whose frequency could be measured by the Arduino without introducing any additional significant errors.

An example using a 555 timer (an additional 4 pF compensation capacitor is needed between OUT and TH for improved accuracy):

**Source:** Use Analog Techniques To Measure Capacitance In Capacitive Sensors, an article by Martin Tomasz published in Electronic Design.

Think of the external circuit as a "sensor" or as a signal conditioning circuit for a "sensor" (the capacitance to be measured). In fact, the dynamic capacitance you're trying to measure probably comes from a sensor (moisture, humidity?), isn't it?

## Connect the capacitor directly to analog pins of Uno and calibrate the readings

It may sound amazing, but something as simple as this works (at the expense of accuracy, of course):

How's that? Because the input capacitance problem that we detected at the beginning is big enough to seriously impair accuracy, but doesn't make the measurement completely unfeasible. Thus, we can calibrate that effect out and still have a valid (although with reduced accuracy) measument in the target range (50-100 pF).

The calibration is done through some hardcoded default values in the following Arduino sketch (source here from braulio777). For better accuracy you should calibrate the values of `IN_STRAY_CAP_TO_GND` and `R_PULLUP` in the sketch by comparing measurements of some capacitors with their already known capacitance values (provided you can do this).

```
//Digital Capacitance Meter
//Measuring from 0.000pF to 1000uF

#include <LiquidCrystal.h>
LiquidCrystal lcd(11, 9, 5, 4, 3, 2);
const int OUT_PIN = A4;
const int IN_PIN = A0;
const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

void setup()
{
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  lcd.begin(16, 2);
  }

void loop()
{
    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_PIN);
    digitalWrite(OUT_PIN, LOW);

    if (val < 1000)
    {
      pinMode(IN_PIN, OUTPUT);

      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);

      lcd.setCursor(0,0);
      lcd.print("Capacitance = ");
      lcd.setCursor(0,1);
      lcd.print("                ");
      lcd.setCursor(0,1);
      lcd.print(capacitance, 3);// for the best precision
      lcd.print("pF ");

    }

    else
    {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do
      {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      }

      while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_PIN);
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP
                              / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      lcd.setCursor(0,0);
      lcd.print("Capacitance = ");
      if (capacitance > 1000.0)
      {
        lcd.setCursor(0,1);
        lcd.print("                ");
        lcd.setCursor(0,1);
        lcd.print(capacitance / 1000.0, 2);
        lcd.print("uF ");

      }

      else
      {
        lcd.setCursor(0,1);
        lcd.print("                ");
        lcd.setCursor(0,1);
        lcd.print(capacitance, 2);
        lcd.print("nF ");

      }

    while (millis() % 1000 != 0);
}
    }

```

The example code above outputs measured values to an LCD display. For your intended application, the best option probably is to write data to an external SD card.

**Disclosure:** I have not tested the code above myself.
> 1 votes

# Answer
For capacitance as small as pF, The RC time constant method yields dirty results on an Arduino board.

You can use the Arduino pins built in small capacitance (which is in Pf itself) to create a "capacitance divider" circuit and calculate much like you would resistance from a voltage divider circuit.

See this excellent post by Nethercott for reference Arduino capacitance meter
> 3 votes

# Answer
Each Arduino capacitance meter relies on a property of resistor capacitor (RC) circuits- the time constant. The time constant of an RC circuit is defined as the time it takes for the voltage across the capacitor to reach 63.2% of its voltage when fully charged. Larger capacitors take longer to charge, and therefore will create larger time constants. The capacitance in an RC circuit is related to the time constant by the equation:

*TC = R x C*

where *TC = time constant in seconds R = resistance in ohms C = capacitance in farads*

Rearranging the equation to solve for capacitance gives:

*C = TC/R*

simulate this circuit – Schematic created using CircuitLab

Example: 1 megohm * 1 microfarad = 1 second

Each capacitance meter has an RC circuit with known resistor values and an unknown capacitor value. The Arduino will measure the voltage at the capacitor and record the time it takes to reach 63.2% of it’s voltage when fully charged (the time constant). Since the resistance value is already known, we can use the formula above in a program that will calculate the unknown capacitance.

As your Capacitance is too Small in Pico Farad Range so you can directly measure Capacitance through your analog pin like this way...  You said that your capacitor in dynamic in nature so you have to take atleast 10 values and average it to get accurate value.

Code for measure Low capacitance in pF range

```
const int OUT_PIN = A5;
const int IN_PIN = A0;
const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

void setup()
{
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_PIN);
    digitalWrite(OUT_PIN, LOW);

    if (val < 1000)
    {
      pinMode(IN_PIN, OUTPUT);

      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);

      Serial.print(F("Capacitance Value = "));
      Serial.print(capacitance, 3);
      Serial.print(F(" pF ("));
      Serial.print(val);
      Serial.println(F(") "));
    }
    else
    {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do
      {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      } while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_PIN);
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP
                              / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      Serial.print(F("Capacitance Value = "));
      if (capacitance > 1000.0)
      {
        Serial.print(capacitance / 1000.0, 2);
        Serial.print(F(" uF"));
      }
      else
      {
        Serial.print(capacitance, 2);
        Serial.print(F(" nF"));
      }

      Serial.print(F(" ("));
      Serial.print(digVal == 1 ? F("Normal") : F("HighVal"));
      Serial.print(F(", t= "));
      Serial.print(t);
      Serial.print(F(" us, ADC= "));
      Serial.print(val);
      Serial.println(F(")"));
    }
    while (millis() % 1000 != 0)
      ;
}

```
> 1 votes

# Answer
Measuring small capacitance value via RC constant estimation essentially requires precise time measurement. ATmega chips have `TCNT1` timer which can be programmed to increment each clock cycle, and can be stopped by a comparator using bit `ACIC` in `ACSR` register. Running a counter at 16 MHz will give you a resolution of 62,5 ns which is enough for capacity measurements in picofarad range. Here's an example of code which uses this measurement technique.

`AnalogRead` is about 1000 times slower, so you'll be limited to nF range if you use it.

Note that you should calibrate your system when measuring such a small capacitance. This is done by running a measurement **with your probes connected** but without the target system. You will then subtract this capacitance value (typically 20-50 pF, depending on the probes you use) from your raw measurements to obtain the capacitance of your system alone.
> 1 votes

# Answer
> (fluctuate from 50pF to 100 pF).

a few ways for such small values -\> assuming you can really read it like a capacitor.

1) form a lc tank and measure its frequency -\> most effective in measuring small value capacitance. but needs precision inductor / calibration, and is subject to parasitics.

2) charge / discharge it via a CCS: and measure the time. simplest as a ccs can be formed via a large resistor. not effective with really small capacitance;

3) charge transfer: using the capacitance of the adc. very effective against small capacitance: \< 10x of adc capacitance. needs calibration.

each has its own problems.
> 1 votes

# Answer
The standard way to measure a resistance with an Arduino is to build a voltage divider by putting it in series with a known resistance. I have tried the same approach for measuring capacitances, and it turns out it works well in the 100 pF range! The circuit is like this:

```
  ┌───────────── Arduino digital output
  │
──┴── known
──┬── cap
  │
  ├───────────── Arduino analog input
  │
──┴── unknown
──┬── cap
  │
 GND

```

The only catch is that you have to do the measurement relatively fast, otherwise you would be measuring the ratio of the leakage resistances. Here is the measurement protocol:

1. Set both pins to `OUPUT` `LOW` in order to discharge both capacitors.
2. Delay for one or two CPU cycles to make sure they are fully discharged.
3. Set the analog input pin to `INPUT` mode: this will make it high impedance and isolate the node connected to it.
4. Set the digital output to `HIGH`: this will charge the two capacitors in series to 5 V.
5. Delay for one or two CPU cycles for the voltage to stabilize.
6. Take an analog reading.

Now you can derive the capacitance from the reading using the same formula you would use with resistors, only with impedances (or, simply 1/C) instead of resistances:

```
C_unknown = C_ref × (1024 − reading) ÷ reading;

```

The same formula can be derived by considering that the node connected to the analog input, which includes one plate of each capacitor, has zero net charge.

A few things worth noting:

* You will get the best resolution by choosing the reference capacitance close to the one you want to measure.
* The delays are not actually needed: as the capacitors charge and discharge very fast, a single CPU cycle is about 24 time constants.
* If you were to measure large capacitances (several nanofarads) with this setup, you would want protective resistors in series with the Arduino pins, but *then* the delays become mandatory. In the 100 pF range I would not worry about the in-rush currents.
* If the delay in step 5 is too long, your measurement will be affected by the leakage of the caps and the analog input pin.
* You need not worry about the 14 pF cap on the sample and hold circuit: it will slightly affect the *very first* measurement but, once that cap is charged, subsequent measurement will not be affected as long as the unknown cap does not change to much between consecutive measurements. You *do* need to calibrate out the stray capacitance of the pin and probes.
> 1 votes

---
Tags: analogread
---


title: Analog reading via bluetooth

text:
# Question
Title: Analog reading via bluetooth
I am making a project in which I am trying to communicate the LDR values collected by one arduino(slave) to another arduino(master) via bluetooth. The readings of the LDR is displayed on the serial monitor. The slave part of the arduino code :

```
 #include <SoftwareSerial.h>
  SoftwareSerial BTSerial(10, 11); // RX | TX
  #define ldrPin A0
  int ldrValue = 0;
  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);
     pinMode(ldrPin, INPUT);
     BTSerial.begin(9600);
     Serial.begin(9600);

   }
   void loop()
    {
     ldrValue = analogRead(ldrPin);
     BTSerial.println(ldrValue);
     Serial.println(ldrValue);
     delay(10);
    }

```

I tried getting the readings of LDR in serial monitor to check whether the readings are correct. The readings shown in Serial monitor were correct.

The code of master part of the project which receives the readings from slave :

```
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
const byte numChars = 1024;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

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

void recvWithEndMarker() {
   static byte ndx = 0;
   char endMarker = '\n';
   char rc;

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

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

   void showNewData() {
      if (newData == true) {
       Serial.print("This just in ... ");
       Serial.println(receivedChars);
       delay(1000);
       newData = false;
    }
   }

```

But The serial monitor did not show the correct readings of LDR . Instead it showed something like this

```
<Arduino is ready>
 This just in ... 8
 This just in ... 3
 This just in ... 4
 This just in ... 3
 This just in ... 3
 This just in ... 3
 This just in ... 3
 This just in ... 4
 This just in ... 3
 This just in ... 4
 This just in ... 3
 This just in ... 3

```

I have referred this link for the Arduino serial communication: Serial Input

Kindly help me out since it has been days since I have stuck up in this issue.

Thank you!

# Answer
1. A byte is 8 bits, it can hold a maximum value of 255. You can not store the number 1024 in a byte. You might want to rethink the type on `ndx`.
2. If `(ndx >= numChars)` then why not set newData to true and print it out. Something has gone wrong if it gets this far and you want to recover if you can.

Apart from those minor issues your code should work as you expect it to. Do you have a printout of what the slave's serial output was? (What you were expecting). Could it be something to do with the differences between SoftwareSerial and Serial?

**Edit:**

I have just run a stubbed version of you code on a PC and it ran fine, so I'm going to point my finger at the SoftwareSerial link. It could well be a misinterpretation of the interface it provides.
> 0 votes

---
Tags: bluetooth, softwareserial, analogread, hc-05
---


# Question
Title: 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.

# Answer
> 4 votes
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.

# Answer
> 4 votes
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).

---
Tags: led, ir, transistor
---


# Question
Title: What happens if you write >10000 times to the flash memory of an ATmega?
I realized that I'm uploading code every 5 minutes and doing relatively intensive trial-and-error development, and that this habit could cause problems down the road, especially if I'm working on a custom board (non-Arduino) where the chip isn't readily replaceable.

What will happen?

I noticed that *avrdude* verifies the written flash. So will it simply start noticing errors and possibly be unable to write without failing?

Or will it work sometimes, sometimes not?

**Example of heavy use:** A custom PCB where easy replacement of the MCU is not possible. 10,000 writes would equal 100 days, each 8 hours of development, with flash write every 5 minutes.

I have several habits that drive frequent flash writing: I inject benchmarks into my code, test speed improvements of small optimizations, program size optimizations, and so on.

I now try to restrain myself from flashing too frequently and doing more code revisions before testing, rather than testing immediately.

**In conclusion:** Yes, it's unlikely, and arguably, if you're working full-time on a board, less intensively, for, say, a year, you can probably afford to buy another board when the first one starts failing the flash-verification.

# Answer
> 1 votes
This Wikipedia article about Flash memory discusses failure mechanisms including references to relevant papers. One point that surprised me was "Read Disturbance" of adjacent cells after a large number (\>100,000) of reads from one cell since last erase, causing the adjacent cell(s) to read back erroneously. There's probably more there and in the referenced articles than you ever wanted to know about Flash failure mechanisms.

However...

At 5min per test, 10000 tests will take you 35 days working around the clock or 100+ days @8hrs/day, maintaining that rate of testing. My point being that you're not likely to reach 10K cycles. But if you are concerned about putting a heavily used chip in the field (and I might be, too, in some cases), socketing board #1 would be worth your while.

# Answer
> 2 votes
> What will happen?

it may not pass parity check. so uploading code wouldn't be possible.

with that said, I have never had one flash-based mcu failure due to endurance. that's countless mcus since as far as I can remember.

to give you some sense of design headroom, I wrote-to and then read-back from eeprom on a pic over several hours @ 10ms per read/write, without a failure. that eeprom is rated 1M in endurance.

so unless you get some weird parts or you write to it repeatedly over a long period of time, flash failure is unlikely a practical issue.

# Answer
> 1 votes
Assuming that you don't have to fine tune each board individually, just don't send the board that you do your testing/adjusting to the 'field'.....keep it in-house, and only use new boards for field use.

# Answer
> 0 votes
Although it's not a direct answer to your question, it might be an answer for your problem (the need to do intensive trial-and-error.

Probably you are testing mostly your program (changes), and not your hardware (changes). Since I don't assume you change your hardware (breadboard) every 5 minutes.

In case the program is quite complicated, probably it will be best to write a specific off-line test program, and run it on a computer instead of an Arduino. You probably have to stub some classes/libraries you use, but it might save you a lot of time. Also you have the benefit of a better IDE and many more debug possibilities. After the tests on the offline test program pass, you try it on the Arduino.

This way you probably need to upload the program just a few times per day on the Arduino.

# Answer
> 0 votes
AFAIK the manufacturer say, that the number of write cycles is guaranteed. Usually the chip is able to endure little more (for manufacturer to be safe to keep the guarantee), individual chips may, on random, endure much, much more.

Also the failure can result in two kinds of problems - first one is better in a way - the write just fail, following read returns "something" (usually part of written value, but some bits always set to the same 0/1). The second one is, that the wearing makes the write unreliable - you write it, you read it it is ok, but after some time (like days/months) the content is changed and if you read it again, you will get "something" as in previous case.

It would be better to make sure you are able to exchange the chip, before going to "normal use" and put there fresh one - use a socket/create new board/unsolder old chip and solder new one. Use the weared chip for more testing/developement, but for production use a fresh one with only few cycles of reflashing. Also software emulators could speed up your developement a lot and decrease the need to/number of reflashing the chip on the board.

---
Tags: flash
---


title: move forward and turn right

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

```

# Answer
> 1 votes
> 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();
 }
}

```

---
Tags: arduino-uno
---


# Question
Title: 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?

# Answer
> 9 votes
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.

---
Tags: arduino-nano, atmega328
---


# Question
Title: 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:

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

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

# Answer
> 2 votes
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:

---
Tags: arduino-uno, resistor, sram, capacitors
---


# Question
Title: Arduino HC05 - AT commands won't respond
A little while ago i tried using AT commands on my HC05 bluetooth module using my arduino mega 2560 and it worked fine , skipping a few weeks ahead i tried doing the same , only now i suddenly doesn't work , i tried replacing the arduino and HC05 module , even used the same script for the commands. So i unplugged the module's VCC , pressed the button on the module , reconnected the VCC and the module was blinking every 2 seconds (it's in AT mode !) , now i go ahead to the serial monitor and using that script i typed the command i wanted to execute and it just didn't do nothing , i saw the serial LED on the arduino blink , but nothing was written in the serial monitor and nothing was changed in the arduino.

Does anyone know how to solve this ? it worked perfect before , but now it wont D:

# Answer
Maybe you should try a couple of different baud rates for your script? Also check that your RX/TX wires are connected in the right order. I've had some HC-05 modules where RX/TX markings on the module were reversed.
> 1 votes

# Answer
Here's the solution! First, you have to wire the board like the solution 2 in the instruction. http://www.elecfreaks.com/wiki/index.php?title=Bluetooth\_Shield Then, Use this code!

```
/*********************************************************************
 **  Description:                                                    **
 **  This file is a sample code for your reference.                  **
 **                                                                  **
 **  Copyright (C) 2011 ElecFreaks Corp.                             **
 **  Created by ElecFreaks Robi.W /29 Sep 2011                      **
 **                                                                  **
 **  http://www.elecfreaks.com                                       **
 *********************************************************************/
void setup()
{
   Serial.begin(57600);
   Serial1.begin(38400);

}

void loop()
{
  int i = 0;
  char someChar[32] = {0};
  // when characters arrive over the serial port...
  if(Serial.available()) {
    Serial.print("------->  ");
    do{
      someChar[i++] = Serial.read();
      //As data trickles in from your serial port you are grabbing as much as you can,
      //but then when it runs out (as it will after a few bytes because the processor
  //is much faster than a 9600 baud device) you exit loop, which then
 // restarts,
  //and resets i to zero, and someChar to an empty array.So please be sure to keep this delay
      delay(3);
    }while (Serial.available() > 0);
    Serial1.println(someChar);
    Serial.println(someChar);
  }

  while(Serial1.available())
      Serial.print((char)Serial1.read());
}

```
> 1 votes

---
Tags: bluetooth, hc-05
---


# Question
Title: How to combine 3.4ghz intel processor with arduino board
Im totally new to arduino but have some programming experience. I have an idea that i would like to realize but it requires way better hardware than what a standard arduino board offers. I would like to use my 3.4 ghz intel processor for example...

The question might seem very stupid to most people here but i actually did not find the answer anywhere (here, google, arduino website), but is it possible to combine the simplicity of arduino and the power of pc-level hardware without using a server? (The calculations should be made locally on the arduino).

# Answer
> 1 votes
How real time do you need things to be?

Arduino gives you very good control of timings because there is no operating system getting in the way switching between tasks in the background.

If you need hard real time then you need to work bare metal, mbed gives you a more processing power while still maintaining the ease of use and reliable tight timing. That will get you up to around 150 MHz with an FPU but still a long way from PC capabilities.

You can run bare metal code on any CPU but doing so without an easy to use set of libraries can have a very steep learning curve, I don't know of any faster systems that allow you to do this in an accessible way.

If you can live with a few ms of delay in the system then you can run something with an OS which opens up a lot more possibilities. The Pi is at the low end of the range in both price and performance. The odroid or beagleboard boards give you more power for more money but are still fairly good in terms of price. I'm not sure what exactly you want to do but four 2 GHz CPUs is enough to do quite a lot of number crunching if you can multi-thread the task.

# Answer
> 1 votes
It depends what you want to do.

An Arduino gives you are simple low cost board for interfacing to peripherals. If you are interfacing to kit then you probably want to stick with a microprocessor because of its real time behaviour, its low cost and its simplicity.

If you then want to crunch numbers send the data back to a beast of a processor and crunch numbers, where you have features like floating point and clever stuff.

The two processors you talk about are both good at what they are aimed at, but not much use at the other.,

Looking at it another way, you are a farmer and have a tractor for ploughing the fields, a quad bike for chasing sheep, and a Porsche for nipping down the shops. You could go shopping in the tractor same as you could try to plough the field with the Porsche, but you look a bit of a \[fool\].

You could look at Netduinos, ESP8226, ESP32, Pi's or PICs.

You can get a PC card that talks to an I2C bus and could control the microprocessors using that.

# Answer
> 0 votes
Of course you can combine it, but it depends what you need. If you say you need to do the calculations on the Arduino, and assuming the electronics will also be driven from the Arduino, I wonder what you want your 3.4 intel processor to do.

If you want to let the Arduino use the intel directly, that will be impossible or at least impractical. The number of pins used by the intel will be very high and the Arduino runs on 16 MHz so never can provide the intel with enough data to keep it busy.

---
Tags: power, shields
---


# Question
Title: 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

# Answer
> 0 votes
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);

```

---
Tags: bluetooth, arduino-nano, adafruit, display, hc-05
---


title: What should I use for IOT Things?

text:
# Question
Title: 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.

# Answer
> 1 votes
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.

---
Tags: arduino-ide, bluetooth, wifi
---


# Question
Title: 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?

# Answer
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
}

```
> 3 votes

---
Tags: arduino-uno, sensors, interrupt
---


title: Interfacing IMU and GPS with Arduino

text:
# Question
Title: Interfacing IMU and GPS with Arduino
I am using an Arduino UNO board and trying to interface IMU sensor (GY-521) and GPS sensor (Ublox Neo-6M) at the same time. The connections of the IMU and GPS are as follows

IMU to Arduino:
Vcc --\> 5V
Gnd --\> Gnd
SDA --\> A4
SCL --\> A5
INT --\> D2

GPS to Arduino:
Vcc --\> 5V
Gnd --\> Gnd
Tx --\> Rx
Rx --\> Tx

Now when I used the IMU sensor alone and tested it with the Jeff Rowberg library, it was working fine. But as soon as I make the connections with the GPS and upload a program, the IDE gives the following error:

```
Arduino: 1.7.10 (Windows 7), Board: "Arduino Uno"

Build options changed, rebuilding all

Sketch uses 3,970 bytes (12%) of program storage space. Maximum is 32,256 bytes.

Global variables use 313 bytes (15%) of dynamic memory, leaving 1,735 bytes for local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa5

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

```

I can't seem to spot the problem. Kindly help me out as I am new to the Arduino development. Thanks.

# Answer
> 1 votes
Remove the GPS from RX/TX during the sketch upload. It is confusing the USB connection. The alternative is to use SoftwareSerial for the GPS.

Cheers!

# Answer
> 0 votes
Not enough to comment yet, but to add Mikael Patel's answer, using Software Serial might help here to take the gps off the Arduino's serial lines

---
Tags: sensors, uploading, gps
---


title: Arduino leave PWM on

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

}

```

# Answer
> 3 votes
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;
  }
}

```

---
Tags: programming, led, pwm
---


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

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

```

# Answer
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);
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: 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?

# Answer
> 4 votes
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.

---
Tags: serial, usb, arduino-leonardo, uart
---


# Question
Title: How can I setup a LED state change with push buttons?
I'm doing a project using **Arduino Uno R3** and I'm trying to use two buttons to change **LED** state between **HIGH** and **LOW**. I have already a code but someting its not right because the **LED** should be starting in **LOW** state but it's starting in **HIGH** state. I checked the circuit and its all good none of the components is connected in wrong place or not connected corretly and the resistors I used are the right ones.

Here is the code I'm using:

```
 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);
}

void loop() {

static bool ledState = false; // LED is off by default
 if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
    digitalWrite(ledpin, HIGH);
    ledState = true;
 }
  if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}

```

# Answer
> 1 votes
You need some PULLUP there - either external resistors or INPUT\_PULLUP settings, otherwise disconnected pin have not defined valou (so it can be LOW even if button is not pressed.

# Answer
> 2 votes
This is an excellent tutorial for exactly that: http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/

Its a bit hard to give you a specific answer without seeing you circuit. but as a start, i would set the ledPin to LOW in the setup routine.

```
void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);

  //initialize the pin to low
  digitalWrite(ledpin,LOW);

}

```

# Answer
> 1 votes
I think you have just minor changes. First of all, you haven't applied pullup. And here, what is the use of `boolean lastbuttonstate1 = LOW;` and `boolean lastbuttonstate2 = LOW;`? I think it not useful for the code so I remove it. And always initialize flag or something in starting of the code means globally. I update your code, just check it out. It might be helpful.

```
int ledpin = 13;
int pushbutton1 = 8;
int pushbutton2 = 7;

static bool ledState = false; // LED is off by default

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

  pinMode(pushbutton1,INPUT_PULLUP); // Provide pullup
  pinMode(pushbutton2,INPUT_PULLUP); // Provide pullup
}

void loop()
{
  if((digitalRead(pushbutton1) == LOW) && !ledState) // 1 pressed & led is off
  {
    digitalWrite(ledpin, HIGH);
    ledState = true;
  }
  if((digitalRead(pushbutton2) == LOW) && ledState) // 2 pressed & led is on
  {
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}

```

---
Tags: arduino-uno, led, button
---


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

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

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

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

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

Arduino 3.3V \<\> TGAM + (VCC)

Arduino GND \<\> TGAM - (GND)

Good luck.

---
Tags: power, pins, electronics, electricity
---


# Question
Title: 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?

# Answer
> 1 votes
@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.

---
Tags: uploading, arduino-micro, avrdude, windows
---


title: EMG control of solenoid valve

text:
# Question
Title: 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;

        }

    }

}

```

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

```
> 0 votes

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

```
> 1 votes

---
Tags: programming, sensors
---


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

# Answer
Yes you may.

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

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

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

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

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

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

The right answer is yes and no.

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

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

The typical solutions are:

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

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

---
Tags: interrupt
---


# Question
Title: SD.begin() causes SD card to pull 20mA in idle mode. Seem high?
I'm working on a project that uses an Atmega328p as the primary controller. I am using the Arduino libraries for programming.

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

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

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

# Answer
> 1 votes
You should look here and see if it helps. Basically:

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

---
Tags: sd-card, sd
---


# Question
Title: How to avoid report of unsuitable sketch names?
I bought a kit of 37 sensors for Arduino, and downloaded all the example sketches. Now, when I try to start up the Arduino IDE I get a *lot* of frustrating messages like this:

... and I have to click "OK" on every one in turn before the IDE will start up.

Obviously I do not want to delete the sketches and their accompaniments, so I have tried to rename all the files and directories, with a shell script, to remove non-alphanumerical characters, but my understanding of shell programming is not good enough, so I have had no success.

I have made backups of the files in case things went awry with my scripting, and now see that these messages are repeated, as in the image, for the backup copies as well. I cannot find out how the Arduino IDE finds them, they are not in my Sketchbook folder.

I would be grateful for advice on either how to avoid these messages, or to edit the names so that they do not occur: I would be happy to edit the names of each sketch as I come to try it out, but I baulk at doing the lot at once.

I am using Linux Fedora 20.

# Answer
> 4 votes
That message is actually a hang-over from when the IDE was Processing. The name of a file had to match the name of the Java class within that file, and there are strict rules about what can be in a Java class name.

They just basically haven't got around to deleting that piece of ancient code yet.

So you have 3 options:

1. Rename all the folders and files.
2. Edit the IDE's source code to delete that old code
3. Use a different IDE.

The first option can be long winded if you don't know how to do good scripting, as you have found out.

The second option requires knowledge of Java coding.

So that leaves the third option. Now, I'm going to be shamelessly advertising my own work here ;) Why not try a better IDE? Such as the popular and powerful UECIDE (yes, written by me). It's based on the Arduino IDE, so it will mostly be familiar to you, but the whole of the insides have been ripped out and re-written. If you're feeling brave you might want to give the beta version a go - it has some really really cool features not found in any other IDE in the history of mankind.

# Answer
> 0 votes
Short answer: You can't avoid that error in the Linux Arduino IDE until your sketches have allowable naming.

Similar question here: How can I use my Arduino sketches on my Raspberry Pi IDE?

Note that it is only complaining about the directory names. But the IDE wants the filenames to match the directory names.

So your best way to deal with this is to go into Windows IDE then load each sketch and resave it with allowable names, before transferring. Make a separate directory for the saves.

If you have dozens, or if you don't have the Windows IDE available, then the program I wrote (see the link above) will do the job for you on the Linux side. It definitely works. I had a bunch and it ran through them all in a minute or two.

I suggest you avoid using the program in favor of the Windows route.. But look at that link to get a feel for how I'm set up.

It is really easier to just use the Windows-based IDE to do the renaming. One by one, just load them then resave them without the special characters, into a subdirectory to be used to transfer to Linux on a flash drive or FileZilla.

Another issue you will face in the Linux IDE is the libraries. First put them in a libraries folder under sketchbook.

Then use the IDE menu item "Sketch..Import Library..Add Library" for each library - it then stores them elsewhere in the IDE's guts.

You can do this on an as-needed bases. Start with the most common ones like Adafruit\_sensor.h, (Note that the underscore is OK for that one) which you know will be used by many of the sensors. SoftwareSerial.h is another good one. DHT.h if using the temp/humidity sensor. Wire.h must be in there for a lot of them.

In the end, it works fine, as you can see at the link above. I rather enjoy sitting at my desk using Remote Desktop via WiFi to the Pis, then remote-reprogramming the Nanos (C++) and/or the Pi (Python, BASH, SCP, etc) to get them calibrated to collect my data.

Have fun with the sensors. Those will take some time to absorb, but in the end it is all worth it.

---
Tags: sketch, ide
---


# Question
Title: Is the DigitalWriteFast library still needed?
Yesterday I played with a SRAM 621024 SRAM 1 Mbit IC and since I use a lot of pins, digitalReads and digitalWrites are needed including shift registers (see Example

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

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

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

Now I get different values:

* Writing 397.880 us per byte
* Reading 386.524 us per byte

Without the fast library:

* Writing 502.152 us per byte
* Reading 483.752 us per byte

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

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

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

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

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

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

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

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

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

void loop(){}

```

The result was:

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

```

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

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

---
Tags: arduino-uno, digitalwrite
---


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

This is what I have so far:

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

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

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

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

int Timer() {
  half_hour_millis = millis();

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

// My interrupt function
void sensor() {
}

```

# Answer
Andrew,

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

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

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

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

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

```

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

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

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

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

Hope this helps and good luck!
> 1 votes

---
Tags: arduino-uno, sensors, interrupt
---


title: How to pull a pin low?

text:
# Question
Title: How to pull a pin low?
On the instructions for this motor driver, it says that motors can be put to sleep by "pulling a pin low".

> **SLP** \- Logic Input. When pulled LOW, outputs are disabled and power consumption is minimized.

I'm guess this means connect to ground? How could I trigger that via my Arduino board?

# Answer
> 3 votes
Connect it to an IO port and set it to OUTPUT and LOW. That's what it means to "pull low".

It helps if you understand how an IO port works. This may help you.

---
Tags: motor, stepper
---


title: Multiple connections on the same pin

text:
# Question
Title: Multiple connections on the same pin
I want to connect an arduino uno both to a TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf and a bluetooth shield. The arduino is to receive data from the TGAM module and sent it to an android device. The problem is I should connect the bluetooth and the TGAM to the same pins on the arduino. Is that a problem (I am still a novice, doing my research)? If it is a problem what is the work around?

**Arduino \<\> TGAM**

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

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

Arduino 3.3V \<\> TGAM + (VCC)

Arduino GND \<\> TGAM - (GND)

**Arduino \<\> HC-06**

3.3v \<\> VCC

GND \<\> GND

TXD \<\> RXD

RXD \<\> TXD

# Answer
> 3 votes
No, you cannot use one pin (or set of pins) for two functions like that.

To communicate with two serial devices you will need two serial ports. It's possible to (just about) emulate one in software using the SoftwareSerial library. It's not wonderful though - personally I would use a chip that has multiple UARTs in it.

---
Tags: bluetooth, pins
---


# Question
Title: How to send command from coordinator to router in Xbee?
I am using an XBee-PRO S2b module. I have sent data from the router Xbee to the coordinator Xbee.

Now I want to send a command packet from the coordinator to the router Xbee to set a pin high.

My coordinator is in API mode and the router is in AT mode.

Can anyone say how to do that?

# Answer
In order to change the router from the coordinator, you have to create a function that run in a microcontroller that is connected to the coordinator.You can refer to this link , https://www.youtube.com/watch?v=CzH146rR-7I&t=236s
> 1 votes

---
Tags: arduino-uno, xbee
---