body:
When I call a function, get_split(), the Arduino restarts. I have tried to find what is causing this, but I have had no luck. Here is my code:

    std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
      std::vector<int> class_values; // declares vector 'class_values'
      for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
        class_values.push_back(dataset[i][dataset.size()]);
      }
      std::vector<std::vector<std::vector<float>>> b_index;
      b_index.push_back(std::vector<std::vector<float>>(999));
      std::vector<std::vector<std::vector<float>>> b_value;
      b_value.push_back(std::vector<std::vector<float>>(999));
      std::vector<std::vector<std::vector<float>>> b_score;
      b_score.push_back(std::vector<std::vector<float>>(999));
      std::vector<std::vector<std::vector<float>>> b_groups;
      for (int i = 0; i < dataset[0].size(); i++) {
        for (int j = 0; j < dataset.size(); j++) {
          std::vector<std::vector<std::vector<float>>> groups = test_split(i,  dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
          float gini = gini_index(class_values, groups); // calculates the gini
          if (gini < b_score[0][0][0]) {
            b_index[0][0][0] = i;
            b_value[0][0][0] = dataset[j][i];
            b_score[0][0][0] = gini;
            b_groups = groups;
          }
        }
      }
      std::vector<std::vector<std::vector<std::vector<float>>>> vals;
      vals.push_back(b_index);
      vals.push_back(b_value);
      vals.push_back(b_groups);
      return vals; // returns the values.
    }

This code is meant to check the gini of splitting a certain function (the gini_index() function works fine). Then it calls test_split which assigns the vector values into two sub-vectors in the vector groups, left and right. Then I just choose the split with the lowest gini.

When I delete everything in the function it doesn't restart, but I have deleted the first for loop, and also the part where it returns a vector, but still no luck. Also when deleting the for loop underneath the declaration of b_groups, it still doesn't work. I don't think it is a memory/storage issue because the Arduino IDE says that I'm only using 3% of that.

PS: I have used the library StandardCplusplus library to include vectors.

title: Arduino restarts when a function is called

Answers: 1

body:
Your code is very complex and running it in an environment where you have limited debug facilities is making life worse for yourself.

When an Arduino reboots it is usually because it has thrown a memory error.  This happens when you try and access memory that is no longer your program's to access (or never was yours).  In this case I originally suspected, based on the complexity of your code, that you were accessing a vector element that you could no longer access.

To prove this I 'ran it on a desktop', in my case a Windows 7 box with Visual Studio 2015 (but you could have used Linux, GCC and GDB).  This meant I wrote a little wrapper program and stubbed the functions you called.  This resulted in the error message shown below.

This is my 'desktop' code:

    #include <vector>

    std::vector<std::vector<std::vector<float>>> test_split(const int& i, const float& f, std::vector< std::vector< float > >& dataset)
    {
     std::vector<std::vector<std::vector<float>>> vals;
     return vals;
    }

    float gini_index(const std::vector<int>& class_values, const std::vector<std::vector<std::vector<float>>>& group)
    {
     return 1.0f;
    }

    std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
     std::vector<int> class_values; // declares vector 'class_values'
     for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
      class_values.push_back(dataset[i][dataset.size()]);
     }
     std::vector<std::vector<std::vector<float>>> b_index;
     b_index.push_back(std::vector<std::vector<float>>(999));
     std::vector<std::vector<std::vector<float>>> b_value;
     b_value.push_back(std::vector<std::vector<float>>(999));
     std::vector<std::vector<std::vector<float>>> b_score;
     b_score.push_back(std::vector<std::vector<float>>(999));
     std::vector<std::vector<std::vector<float>>> b_groups;
     for (int i = 0; i < dataset[0].size(); i++) {
      for (int j = 0; j < dataset.size(); j++) {
       std::vector<std::vector<std::vector<float>>> groups = test_split(i, dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
       float gini = gini_index(class_values, groups); // calculates the gini
       if (gini < b_score[0][0][0]) {
        b_index[0][0][0] = i;
        b_value[0][0][0] = dataset[j][i];
        b_score[0][0][0] = gini;
        b_groups = groups;
       }
      }
     }
     std::vector<std::vector<std::vector<std::vector<float>>>> vals;
     vals.push_back(b_index);
     vals.push_back(b_value);
     vals.push_back(b_groups);
     return vals; // returns the values.
    }

    int main(void)
    {
     std::vector<std::vector<float>> dataset;

     std::vector<std::vector<std::vector<std::vector<float>>>> result = get_split(dataset);

     return fgetc(stdin);
    }

Now you need to workout where it is crashing, easy in Visual Studio but very difficult on an Arduino.  However I would look at simplifying the code too.

[![Your bug][1]][1]

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


body:
For one of my hobby projects I would like to use:

 - [Wemos D1 mini pro][1] ([schematic][2])
 - [Wemos D1 Relay Shield][3] ([schematic][4])

to control the `24V` (`19W`) mist maker.

My current wiring is this:
[![enter image description here][5]][5]

As you can see the both grounds (12V and 5V) are attached to the `com` connector of the power supply.

I wonder whether grounds should be decoupled (for whatever reason) - i.e. to use separate power supplies? If the above wiring is OK I would really like to know in which circumstances (if any) a separate power supplies would be needed.

Thanks for all your answers in advance.

  [1]: https://www.wemos.cc/product/d1-mini-pro.html
  [2]: https://www.wemos.cc/sites/default/files/2016-09/mini_pro.pdf
  [3]: https://www.wemos.cc/product/relay-shield.html
  [4]: https://www.wemos.cc/sites/default/files/2016-09/relay_new.pdf
  [5]: https://i.stack.imgur.com/ottsS.png

title: Wemos D1 & Relay shield

Answers: 1

body:
That grounding scheme looks right since the Load ground is coupled back to the supply separately from the logic ground.

The only reason you would separate supplies would be to isolate them for safety or other reasons. For example, if the load side was a large or ac voltage.

Isolation requirements vary with application so it is hard to be more specific than that here.


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

title: How to combine 3.4ghz intel processor with arduino board

Answers: 3

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

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

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


body:
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][1]

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

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

Thank you!

title: Analog reading via bluetooth

Answers: 1

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


body:
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(0,0);

    }

    void loop() {
      uint8_t buttons = lcd.readButtons();
      int a;
      if (buttons) {

        lcd.clear();
        lcd.setCursor(0,0);

        if (buttons & BUTTON_UP) {
          a+= 1;
          lcd.setCursor(0,0);
          lcd.print(a);
        }
      }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

title: Button that increments a counter

Answers: 1

body:
Your code, simplified, is:

    void loop()
        int a;
        a += 1;
    }

The problem here is that, by putting the declaration of your counter variable within the `loop()` function, you've made it local to that function. Every time `loop()` is called, a new variable `a` is created, initialized to zero, and then incremented.

You want to move the declaration outside of `loop()`, creating a global variable that will remain in existence and maintain its value after `loop()` exits, so that the value is still there when `loop()` is called again:

    int a = 0;
    void loop() {
        a += 1;
    }

(This could also be done with a static variable, but that's probably beyond the scope of this question.)


body:
I want to recreate this existing ALPS switch board (the board on the left) in Arduino, so I can control the switches (and 3 memory + 1 menu buttons) from my laptop. The ALPS switch board connects to a controller board (PSM) with relays, microprocessor, and DC motors connected to it.
[![ALPS Switch Board + PSM][1]][1]

The idea is to use Arduino to completely replace the ALPS switch board, while still preserving the controller board connection and current wiring and connector (16 pins + 2 empty pins).

Is there a way I can just connect the 16-pin connector directly to header pins on a certain Arduino variant? And program the individual pins, to replicate the manual switch input + 4 buttons?

[![Pin diagram][2]][2]
See pin diagram attached (seen from the other end of the wiring, on the controller board side), where I get a little bit confused about terminal #C4 - #C7.

If easily possible, I want to use the controller board power, not the Arduino power.
I’m also not sure about what the 2000 Ohm resistor on the left side does exactly.

Edit 1:
Hopefully the new picture above clears things up a bit. The switch board connects to a PSM (Power Seat Module), which controls the DC motors of an early 2000s car power seat (don't think the OEM matters here). I want to control the PSM with my Arduino (so I don't have to use the ALPS board anymore). In other words, I have to replicate all the functionality from the ALPS board with my Arduino.

Edit 2: A picture of underside of Alps board:
[![Underside of Alps board][3]][3]

Edit 3:
The P/N for the switch board is: ALPS ANJ971038D RH DR. And for the PSM (which includes the relays): ALPS ANV971018A. There is no public documentation that I found for any of the 2 boards. The pinout diagram above is from the dealership, but I'm not allowed to post further details about it.

Here are the results of what I measured myself using my multimeter. When the switch board is powered from the PSM I measured 4,5V on the + and - of the 4 memory buttons in neutral position. By pressing a memory butting the voltage drops to 0V. The + and - on the white switches measured 11,90V in neutral position. According to the pinout diagram the voltage is supposed to drop to 0V, but this didn't happen when I moved the switch while measuring. I also measured a resistance of 1490 Ohm between pin 2 and 5 of a white switch (so the neutral position), while the switch board was being powered! No resistance when the board is disconnected from the PSM.

I also measured pin #C4 and #C6/7 right from the connector, and I got 0,99V. #C5 and #C6-7 gave me 2,95V. Pin #C4 and #C5 are connected to the resistor (R1).

The switches are all momentary switches.

2 pictures of sketches/measurement results:
[![Pin measurement diagram][4]][4]
[![ALPS board measurement results sketch][5]][5]

  [1]: https://i.stack.imgur.com/9AfBM.jpg
  [2]: https://i.stack.imgur.com/xgJA4.png
  [3]: https://i.stack.imgur.com/LQhC5.jpg
  [4]: https://i.stack.imgur.com/TqvB7.jpg
  [5]: https://i.stack.imgur.com/iCLOa.jpg

title: How to recreate this basic ALPS switch board in Arduino?

Answers: 0


body:
I would like to connect 3 L293D Motor controllers to an Arduino Uno with the hopes of powering 6 different dc motors. I was just wondering how to wire this being that one motor controller (which allows for 2 dc motors to be controlled) already takes up most of the pins on the Arduino, thanks.

Below is the wiring diagram for how I am hooking up 1 L293D motor controllers to the Arduino.

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

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

title: Connect Multiple L293D Motor Controllers to Arduino

Answers: 2

body:
The suggestion of using an [Adafruit Motor Shield V2 for Arduino](https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/overview) seems fairly good, although that particular shield controls only four DC motors at once.  That shield has a dedicated PWM driver chip on it, which removes the overhead of motor and speed control from the MCU.  That might allow you to drive four motors via the shield, and two via wires from the Arduino; or, stack two motor shields on the Uno.

If you definitely want to drive six motors from the Arduino, you may need to add a couple of control chips.  You could add a 74HCT04 hex inverter and a 74LS595, to create inverted drive signals and enable signals.  For example, the first PWM drive would go to L293 pin 1A and to '04 pin 1A; the first '04 output, 1Y, would drive L293 pin 2A.  One of the '595 outputs would go to L293 pin 1,2EN.

Alternately, you could use two '595s, with outputs to control L293 pins 2A; 4A; 1,2EN; and 3,4EN on each of three L293's.  The six PWM outputs from the Uno would go to 1A and 3A on the several L293's.  Using motor shields probably is a better idea, however.

body:
If you want to make your own circuit.. then you need two IC 74HCT595(8-bit serial-in, serial or parallel-out shift register). You have to wiring with your arduino and L293D you can go this way..
[![Wiring schematic with Arduino][1]][1] . This Circuit diagram is an Idea, don't think its actual circuit you have to modify this schematic accroding to your application.

Data Sheet link [74HCT595 DATASHEET][2]

  [1]: https://i.stack.imgur.com/XlSf8.png
  [2]: https://www.arduino.cc/en/uploads/Tutorial/595datasheet.pdf


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

title: Logging small capacitance

Answers: 6

body:
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*

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/FNf5I.png)

<!-- End schematic -->

Example: 1 megohm * 1 microfarad = 1 second
[![enter image description here][1]][1]

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...
[![Schematic][2]][2] You said that your capacitor in dynamic in nature so you have to take atleast 10 values and average it to get accurate value.

  [1]: https://i.stack.imgur.com/g3Wv9.jpg
  [2]: https://i.stack.imgur.com/hsTpS.png

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

body:
Measuring small capacitance value via RC constant estimation essentially requires precise time measurement. ATmega chips have [`TCNT1`](https://stackoverflow.com/questions/29593616/using-atmega-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](https://github.com/svn2github/transistortester/blob/master/Software/trunk/ReadCapacity.c)'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.

body:
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][1]

  [1]: http://wordpress.codewrite.co.uk/pic/2014/01/21/cap-meter-with-arduino-uno/

body:
> (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.

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

body:
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):

[![555 timer capacitance meter][1]][1]

[![Frequency vs capacitance][2]][2]

**Source:** [Use Analog Techniques To Measure Capacitance In Capacitive Sensors][3], 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):

[![Uno as capacitance meter][4]][4]

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][5] 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]: https://i.stack.imgur.com/rPguC.gif
  [2]: https://i.stack.imgur.com/aSec7.gif
  [3]: http://electronicdesign.com/analog/use-analog-techniques-measure-capacitance-capacitive-sensors
  [4]: https://i.stack.imgur.com/a4Btil.png
  [5]: https://pastebin.com/njjKZrfv


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

title: What happens if you write >10000 times to the flash memory of an ATmega?

Answers: 5

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

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

body:
This [Wikipedia article][1] 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.

  [1]: https://en.wikipedia.org/wiki/Flash_memory

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

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


body:
I am currently working on an obstacle avoidance robot project and I have seen numerous algorithms for obstacle avoidance a very good example is this [Obstacle avoidance algorithm][1] [Editor's note: by user3880651],
but unfortunately non of those algorithm works with Arduino so upon my research I found this [blog][2]

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

and in there the author talks about an effective way to avoid obstacles and even has a formula he uses for avoiding obstacles at different positions e.g (Front and sides) but doesn't really explain how he got the formula so I was wondering if anyone as an effective formula or algorithm for obstacle avoidance that works with Arduino thanks for your help in advance

  [1]: https://arduino.stackexchange.com/questions/36307/obstacle-avoidance-algorithm
  [2]: http://www.rmcybernetics.com/projects/DIY_Devices/diy-robot-arduino.htm
  [3]: https://i.stack.imgur.com/ePQxK.png

title: Formula for decision making when in contact with an obstacle using Arduino

Answers: 2

body:
The algorithm mentioned in the blog uses a Fuzzy Logic Controller to perform obstacle avoidance. You can read up more on fuzzy logic here: https://www.calvin.edu/~pribeiro/othrlnks/Fuzzy/home.htm

> newMotorSPD_L = basicVelocity + urgMotor_L + (urgTurn_R/4) - (urgTurn_L/2) + 60;
newMotorSPD_R = basicVelocity + urgMotor_R + (urgTurn_L/4) - (urgTurn_R/2) + 60;

Based on the code, the formula is basically made up of variables with different weight/ratio.

**basicVelocity** is the default moving velocity of the robot when there is no obstacle or wall detected.

**urgMotor_L/urgMotor_R** is the ouput of the controller for frontal object detection/avoidance by getting the difference between the left and right ultrasonic sensor.

**(urgTurn_R/4) - (urgTurn_L/2)** is probably the left/right bias?

**+60** at the end is probably to offset the error of the motor. (Assuming all other variable are 0, the robot should be still at 60 for their case?)

To simplify what the formula does, it can be shown using this graph:
[![enter image description here][1]][1]

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

body:
Obstacle avoidance doesn't really have any practical use unless it works alongside a goal finding algorithm.

Take a look [here][1] for a simple introduction (and a few modifications) to [this excellent paper][2] on goal finding with obstacle avoidance.

You can also experiment with the python code (add obstacles, change positions of goal and start points, and step through the decision process). Keep in mind that in this code, ***sensor inputs are also simulated*** and so the code is much more complex than that would actually need to be deployed on a robot with real world sensors.

  [1]: https://bayesianadventures.wordpress.com/2015/08/31/obstacle-avoidance-for-clever-robots/
  [2]: http://www.wseas.us/e-library/conferences/2009/tenerife/CIMMACS/CIMMACS-03.pdf


body: I connected and flashed successfully an ESP8266 module to a Nano. Now I want to control pins values with a REST API, but all the libraries I found are for using standalone ESP8266 modules (without Arduino) or for Arduino with some other modules like CC3000 etc. Can anybody recommend a library please?

title: Nano + ESP8266 control pins with REST API

Answers: 1

body:
You can use Firmata to control the Arduino pins, just having the ESP8266 publish a web page exposing the Firmata operations you desire to expose and sending the user actions to the Arduino via serial using the Firmata protocol.

To make your life easier you can consider your ESP8266 an equivalent of your serial console: everything you write _from_ the ESP82667 becomes input data on the console for your Arduino and the other way around.

In Firmata, each command can be read from a generic _Stream_, with `Serial` being the default implementation.


body:
I am new here and perhaps you could help me. I am trying to program Attiny13 with the following short sketch which uses ADC (analogread()) function, that is supposed to work like this:

- reads voltage from voltage divider using photoresistor - analogread() from A1 (ADC1)
- turns LED on/off whenever there is low light (covering photoresistor) - digitalwrite() LED at 3 (PB3)

however it does not work on each of the ADCs:
- works when I use A3 (ADC3) as analogread
- does not work when I use A1 (ADC1) or A2 (ADC2) as analogread

Do you know what might be the reason? Same code, but works on 1 of the ADCs only.

I program uC with USBASP programmer, but I don't think this matters since with 1 of the ADCs all works fine. Also it works on Arduino Mega 2560 and uC Atmega88, so something wrong with Attiny13.

Sketch that does not work:
<!-- language: c++ -->

    int state = 0;

    void setup()
    {
    pinMode(3, OUTPUT);
    }

    void loop()
    {
     int reading = analogRead(A1);

     if (reading < 100) // ONCE I COVER PHOTORES. IT GOES INTO THIS LOOP AND TURNS ON/OFF THE LED
     {
      state = !state;
      digitalWrite(3, state);
      delay(200);
     }

     delay(100);
    }

title: Attiny13 analogread() not working on all pins

Answers: 0


body:
I have made a program that increments a counter everytime the up button is pressed. I am trying to write this value to EEPROM, so that when I turn my board off and on again, the value before power off is shown on screen.

I wrote this code but the value doesn't seem to be written to EEPROM. The counter incrementation works fine.

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

    int addr = 0;
    byte value;

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(0,0);
    }

    int a;
    void loop() {
      uint8_t buttons = lcd.readButtons();
      if (buttons) {

        lcd.clear();
        lcd.setCursor(0,0);

        if (buttons & BUTTON_UP) {
          a+= 1;
          EEPROM.write(addr, a);
          value = EEPROM.read(addr);
          lcd.print(value);
          delay(100);
        }
      }
    }

Thanks for the help!

title: Using EEPROM to write a counter value

Answers: 1

body:
just add `a = EEPROM.read(addr);` in your setup
also, you can remove `byte value` and use `a` you wrote to memory in the previous line


body:
I recently started an oled project. I use a small "128X64 OLED LCD LED Display Module" and I control it using SPI protocol(with my Arduino).

It is the only device connected to the microcontroller. But I have some questions regarding the pins. I found [this][1] tutorial and it uses pins 9 as DATA(known as MOSI) and 10 as CLK( or SCK). But the [datasheet][2] for my microcontroller(328) shows that pin 11 is MOSI and 13 is CLK.

Obviously..it works. So I think the program provided by the adafruit(that I used-Adafruit_SSD1306) took care of MOSI and generated the clock impulses on pin 10.etc. . But then what are those pins on the board and why are called like that? I mean it seems to me that everyone can just use other pins for MOSI/CLK(at least).What is their purpose?

Question #2: What does DC (or D/C) means?

    #define OLED_MOSI   9
    #define OLED_CLK   10
    #define OLED_DC    11
    #define OLED_CS    12
    #define OLED_RESET 13
**VS**
[![enter image description here][3]][3]
(328<=>128)

  [1]: https://learn.adafruit.com/monochrome-oled-breakouts/wiring-1-dot-3-128x64
  [2]: https://www.arduino.cc/en/Hacking/PinMapping168
  [3]: https://i.stack.imgur.com/75nMY.png

title: Adding slave device to Arduino Uno-SPI | Configuring pins

Answers: 1

body:
You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.

Here are the links to the relevant files in the library, so I can comment on them.

 - [INO example file](https://github.com/adafruit/Adafruit_SSD1306/blob/master/examples/ssd1306_128x32_spi/ssd1306_128x32_spi.ino)
 - [Library header file](https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.h)
 - [Library source file](https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.cpp)

Ok, first of all let's have a look at the example. you can see that the constructor is called as

    Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

When looking at the lines 144 and following of the source file, you can see

    hwSPI = false;

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as `Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS)`, you will use the hwSPI.

Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.

You can also see it in the example:

    // If using software SPI (the default case):
    #define OLED_MOSI   9
    #define OLED_CLK   10
    #define OLED_DC    11
    #define OLED_CS    12
    #define OLED_RESET 13
    Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

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

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.

As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data


body:
We made this code in class:

     int red = 6;
      int green = 7;
      int blue = 8;
      int pot = A0;
      int potVal = 0;
      int chosenColor = 0;

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

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

      else {
        analogWrite(red,255);
      }

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

      else {
        analogWrite(green,255);
      }

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

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

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

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

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

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

title: Student Code: map function not functioning

Answers: 4

body:
As Edgar Bonet pointed out,  “`chosenColor = 3` means 'let chosenColor take the value 3'”.  That is, your  `potVal = analogRead(pot);  chosenColor = map(potVal, 0, 1023, 1, 3);` sequence may very well be working, but by the time you get to `Serial.println(chosenColor);` you have changed `chosenColor` to 3.

First, the statement `if(chosenColor = 1) {...}` changes `chosenColor` to 1. Then the statement `if(chosenColor = 2) {...}` changes `chosenColor` to 2.  Finally, `if(chosenColor = 3) {...}` changes `chosenColor` to 3, just before you print out the current value of `chosenColor`.

When you wish to compare two numeric values for equality, use `==` instead of `=`.

body:
You are confusing `=` (assign) with `==` (compare).

eg.

### Wrong! ...

    if (chosenColor = 3)  // this assigns 3 to chosenColor

### Correct:

    if (chosenColor == 3)   // compare

---

> Still not sure why the map function is not working.

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

body:
Although not related to your main problem, I would like to point out
that there _is_ an issue with your use of the `map()` function. Or maybe
I should say, with the `map()` function itself. Since it works with
integer arithmetic, and integer division by default rounds towards zero,
you get a mapping that may be quite different from what you expect.

In the table below, I am showing the result of
`map(potVal, 0, 1023, 1, 3)`. The column labeled “not rounded” is what
you would get if the mapping was done in floating point. The last column
is the rounded value you actually get out of `map()`:

    potVal  not rounded  rounded
    ----------------------------
        0     1.00000       1
                ...
      511     1.99902       1
      512     2.00098       2
                ...
     1022     2.99804       2
     1023     3.00000       3

As you see, you have 512 possible values of `potVal` mapped
to 1, 511 values mapped to 2 and one single value mapped
to 3.

I assume you would rather have one third of the range mapped to each
value. This can be achieved by writing `map(potVal, 0, 1024, 1, 4)`:

    potVal  not rounded  rounded
    ----------------------------
        0     1.00000       1
                ...
      341     1.99902       1
      342     2.00195       2
                ...
      682     2.99805       2
      683     3.00098       3
                ...
     1023     3.99707       3

This gives 342 values mapped to 1, 341 values mapped
to 2 and 341 values mapped to 3. Now, the problem is that
this way of using `map()` is confusing. You may prefer to write
something more explicit instead, like:

    if (potval < 1023/3) chosenColor = 1;
    else if (potval < 1023*2/3) chosenColor = 2;
    else chosenColor = 3;

body:
Not sure if this helps but I wanted a slider with a range of 0 to 200 to give 3 values; 0 for the first third of movement, 1 for the second third and 2 for the last third

I used map(slider value, 0, 134, 0, 2)


body:
I recently created a rfid project with the sensor rfid rc522. I used the instructions mentioned by [this site][1] and works perfectly. However, I intend this project to be battery supplied and I want to make the system use as low current as possible using the [low power library][2]. Well I need arduino UNO hibernate until an interrupt by the rfid is occured. Any proposals on how am I going to detect an interrupt by the rfid?

(PS) If there is any better battery saving library that can detect interrupts while keeping arduino slept, then feel free to propose it to me.

Thank you in advance.

  [1]: https://create.arduino.cc/projecthub/Aritro/security-access-using-rfid-reader-f7c746
  [2]: https://github.com/rocketscream/Low-Power

title: RFID working with interrupts

Answers: 0


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

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

Answers: 2

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

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

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

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

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

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

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

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

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

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

Exactly the same way that remote controls do it.

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


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

title: move forward and turn right

Answers: 1

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

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

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

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

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

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

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


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

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

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

My code is here:

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

    DHT dht(DHTPIN, DHTTYPE);

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

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

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

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

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

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

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

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

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

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

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

Answers: 1

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

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

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

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

    const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

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

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

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

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

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

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

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

      delay(UpdateSerialDisplay);
    }

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


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

title: Does the reset button work when not powered?

Answers: 1

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

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


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

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

Code is:

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

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

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

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

title: Analog pins for 4x4 matrix keypad

Answers: 2

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

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

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

> **ADVICE: Don't use pin 13 for input!**


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

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

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

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

My questions:

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

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

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

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

Answers: 1

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

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

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

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

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


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

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

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

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

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

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

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

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

Answers: 2

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

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

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

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

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

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

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

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

Cheers!

Update [2017-09-25]

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

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


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

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

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

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

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

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

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

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

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

    Build options changed, rebuilding all

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

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

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

https://pastebin.com/GCq6aZsR

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

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

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

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

title: NodeMCU espcomm_sync failed

Answers: 4

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

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

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

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

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

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

So no hardware flaws and no need for new drivers.

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


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

title: SIM800L Arduino Pro Mini

Answers: 1

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


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

title: Bluetooth serial readings on 0.96'' Adafruit OLED

Answers: 1

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

    String content = "";
    char character;

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

and then you send content to lcd by putting

    display.write(content);


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

title: What should I use for IOT Things?

Answers: 1

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

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

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

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