message:
MFRC522 ReadNUID example reboots unless I include a null if statement

I'm fairly new to Arduino (and C), but not to embedded electronics and programming.

I'm using an MFRC522 module (the common one) with a Nano, and getting some strange results. They are on a very simple custom PCB I've made (the only parts on it, except for a couple of LEDs on D4 & D5)
I'm using SS_PIN on 8, and RST_PIN on 7, which is changed from 10 & 9, because the board will also be using an NRF24L01 module on the SPI bus (not fitted yet).

And I'm using the MFRC522 library.
The DumpInfo example in the library works fine, but not the ReadNUID example.

When I bring a tag/card near the reader, the sketch (sometimes) gets some of its output to the serial monitor, but then (always) the board reboots and the startup messages appear again. This happens continuously while the card is near.

I have the RFID IRQ connected to pin D3, and while thinking that may be causing the problem, and trying all sorts of stuff, I found that it wasn't. In the process I did get the sketch to work, and have distilled the fix down to two seemingly superfluous lines of code:-

Added a null if statement at the start of loop:-
<!-- language-all: lang-cpp -->

    if (GotIRQ) {}

and defined a volatile variable for it to test:-

    volatile boolean GotIRQ=false;

Doesn't work if it's not volatile. (A clue?)

What Gives? Some dumb newbie mistake?

(I could post the entire code if required, but I've started again from the original source, and only made the 2 changes and 2 additions described above)

Here is the code:-

    /*
     * --------------------------------------------------------------------------------------------------------------------
     * Example sketch/program showing how to read new NUID from a PICC to serial.
     * --------------------------------------------------------------------------------------------------------------------
     * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
     *
     * Example sketch/program showing how to the read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
     * Reader on the Arduino SPI interface.
     *
     * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
     * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
     * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
     * will show the type, and the NUID if a new card has been detected. Note: you may see "Timeout in communication" messages
     * when removing the PICC from reading distance too early.
     *
     * @license Released into the public domain.
     *
     * Typical pin layout used:
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN 8   //QQ This changed from 10
    #define RST_PIN 7   //QQ This changed from 9

    MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

    MFRC522::MIFARE_Key key;

    volatile boolean GotIRQ=false; //QQ needed for null if statement

    // Init array that will store new NUID
    byte nuidPICC[3];

    void setup() {
      Serial.begin(9600);
      SPI.begin(); // Init SPI bus
      rfid.PCD_Init(); // Init MFRC522

      for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
      }

      Serial.println(F("This code scan the MIFARE Classsic NUID."));
      Serial.print(F("Using the following key:"));
      printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
    }

    void loop() {
      if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

      // Look for new cards
      if ( ! rfid.PICC_IsNewCardPresent())
        return;

      // Verify if the NUID has been readed
      if ( ! rfid.PICC_ReadCardSerial())
        return;

      Serial.print(F("PICC type: "));
      MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
      Serial.println(rfid.PICC_GetTypeName(piccType));

      // Check is the PICC of Classic MIFARE type
      if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
        piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
        piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
        Serial.println(F("Your tag is not of type MIFARE Classic."));
        return;
      }

      if (rfid.uid.uidByte[0] != nuidPICC[0] ||
        rfid.uid.uidByte[1] != nuidPICC[1] ||
        rfid.uid.uidByte[2] != nuidPICC[2] ||
        rfid.uid.uidByte[3] != nuidPICC[3] ) {
        Serial.println(F("A new card has been detected."));

        // Store NUID into nuidPICC array
        for (byte i = 0; i < 4; i++) {
          nuidPICC[i] = rfid.uid.uidByte[i];
        }

        Serial.println(F("The NUID tag is:"));
        Serial.print(F("In hex: "));
        printHex(rfid.uid.uidByte, rfid.uid.size);
        Serial.println();
        Serial.print(F("In dec: "));
        printDec(rfid.uid.uidByte, rfid.uid.size);
        Serial.println();
      }
      else Serial.println(F("Card read previously."));

      // Halt PICC
      rfid.PICC_HaltA();

      // Stop encryption on PCD
      rfid.PCD_StopCrypto1();
    }

    /**
     * Helper routine to dump a byte array as hex values to Serial.
     */
    void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
      }
    }

    /**
     * Helper routine to dump a byte array as dec values to Serial.
     */
    void printDec(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], DEC);
      }
    }

OK, trying to cut down to a minimal example has proved useful. It seems the problem is caused by the loop that stores the NUID, but not if the superfluous if statement is present. The code is :-

    // Cut down version of MFRC522 library ReadNUID example that exhibits strangle
    // problem of rebooting the board when a card is near the reader.
    // But only if:-
    // * the Store NUID loop is included
    // and
    // * the superfluous "if" statement at start of loop() is NOT present.
    // Changes from original example are indicated by comments starting with "//QQ"
    // (plus a lot of removed code)

    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN 8   //QQ This changed from 10
    #define RST_PIN 7   //QQ This changed from 9

    MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

    MFRC522::MIFARE_Key key;

    volatile boolean GotIRQ=false; //QQ needed for null if statement

    // Init array that will store new NUID
    byte nuidPICC[3];

    void setup() {
      Serial.begin(9600);
      SPI.begin(); // Init SPI bus
      rfid.PCD_Init(); // Init MFRC522

      for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
      }

      Serial.println(F("This code scan the MIFARE Classsic NUID."));
    }

    void loop() {
    //  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

      // Look for new cards
      if ( ! rfid.PICC_IsNewCardPresent())
        return;

      // Verify if the NUID has been readed
      if ( ! rfid.PICC_ReadCardSerial())
        return;

      Serial.print(F("PICC type: "));
      MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
      Serial.println(rfid.PICC_GetTypeName(piccType));

      // Store NUID into nuidPICC array //QQ does not fail if this loop is excluded
      for (byte i = 0; i < 4; i++) {
        nuidPICC[i] = rfid.uid.uidByte[i];
      }

      // Halt PICC
      rfid.PICC_HaltA();

      // Stop encryption on PCD
      rfid.PCD_StopCrypto1();
    }

body: I'm assuming that the extra byte in the array is needed, possibly for a null terminator or whatever, and that the example code has a bug. I've had no further problems since changing the NUID[3] to NUID[4], so I'll leave this at that.


sender: user

sender: assistant

body:
You've defined this array to have three elements:

    byte nuidPICC[3];

those three elements are numbered 0, 1, and 2.

In this for loop:

    for (byte i = 0; i < 4; i++) {
        nuidPICC[i] = rfid.uid.uidByte[i];
      }

you are writing to position 3, which is out of bounds for that array.

Once you write out of bounds on an array the behavior is undefined.  Resetting is one common result.  But anything could happen.


message:
What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz

I am doing a school project and saw someone use an Arduino and a piece of wire as an antenna here: https://forum.arduino.cc/index.php?topic=88422.0

I've tested this experiment and it works, but I have searched the internet for some time now for some background knowledge or theory on why this works, and how does it?

If anyone knows anything about the arduino creating simple AM waves, could you please let me know about it or redirect me to another source.

For some context, in this school project I've got to explain the theory behind creating basic AM waves and amplitude modulation in general, then prove the theory by conducting this experiment which I prove it correct.

body:
Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.

Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.

The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.

The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.

To understand more about *why* it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).


body:
It works because everything is wrong. A perfect sine wave of 800 kHz would not transmit very well with such a small wire as antenna.

The output signal is a digital pulse (PWM signal) with very sharp edges. Those edges create many harmonics as Majenko wrote. It is those high harmonic frequencies that can use that small wire as antenna. The receiver might get help of those harmonic frequencies to combine them with the base signal to be able to receive the base signal of 800kHz. The receiver might also receive the electrical field coupling (capacitive coupling) instead of really receiving radio signals. The electrical (capacitive) coupling might even be main part of what is received.

You could add a large antenna or a large open coil or a tuned circuit of a coil with a capacitor. That should increase the range, because that will transmit real radio signals.

The Arduino board with the wire can not be used to explain AM radio signals, because it is not a AM radio signal. You can also not use it to explain AM modulation, because there is no modulation (only on/off).
Do you know someone who has equipment to make modulated AM signals ?

Last but not least: it is illegal to transmit at 800kHz.


message:
Not able to add JSON data to Arduino data

In my recent project, I'm working with Arduino with JSON.

I made software on JSON. Now, I want to send data from this software to my Arduino. Serial communication is done between Arduino and JSON. But somehow, I can't able to get proper data from JSON to my Arduino. So, I google out and find library named `ArduinoJson`. And here, I found out example code. So, I tried out that code and modified based on my requirement.

Here, below is my code.

Now, Software sends me value. And I split it out into three variable MAP_Json, TPS_Json, and LOAD_Json.
In Arduino side, I have already the value of MAP, TPS, and LOAD.

So, now my main intention is to compare `MAP_Json with MAP` & `TPS_Json with TPS`. If they are matched then `LOAD_Json is added to LOAD`. But, when I try it out, then `LOAD_Json not added to LOAD`. I don't understand why this happened?

     #include <ArduinoJson.h>

    //----------------------------For MAP calculation----------------------------//
    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    int LOAD_MIN_MAP[] = {1, 2};
    int LOAD_MAX_MAP[] = {3, 4};

    float mMAP[2] = {};
    float yMAP[2] = {};

    int i, j, a;
    float MAP, mFinalMAP, yFinalMAP;

    //----------------------------For TPS calculation----------------------------//
    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    int LOAD_MIN_TPS[] = {1, 3};
    int LOAD_MAX_TPS[] = {2, 4};

    float mTPS[2] = {};
    float yTPS[2] = {};

    int k, l, b;
    float TPS, mFinalTPS, yFinalTPS;

    //----------------------------For LOAD calculation---------------------------//
    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD[] = {8.00, 9.06};
    float injTime_MAX_LOAD[] = {10.60, 11.86};

    float mLOAD[2] = {};
    float yLOAD[2] = {};

    int m, n, c;
    float LOAD, mFinalLOAD, yFinalLOAD;

    //------------------------------ Variable ---------------------------------//

    float load;

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

    void loop()
    {
      //----------------------ARDUINO DATA-------------------------//

      //----------------------------MAP----------------------------//

      MAP = analogRead(A0) * (5.0 / 1023.0);

      for(a = 0; a < 2; a++)
      {
        mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
        yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
      }

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      for(b = 0; b < 2; b++)
      {
        mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
        yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
      }

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
      yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

      mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
      yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

      LOAD = (yFinalTPS + yFinalMAP) / 2;

      Serial.print("T : ");
      Serial.print(TPS);
      Serial.print("\t");
      Serial.print("M : ");
      Serial.print(MAP);
      Serial.print("\t");
      Serial.print("L : ");
      Serial.print(LOAD);
      Serial.print("\t");

      while(!Serial)
      {
        // wait serial port initialization
      }

      StaticJsonBuffer<200> jsonBuffer;

      char json[] = "{\"TPS\":1.67, \"MAP\":1.83,\"LOAD\":30}"; // JSON DATA

      JsonObject& root = jsonBuffer.parseObject(json);

      // Test if parsing succeeds.
      if(!root.success())
      {
        Serial.println("parseObject() failed");
        return;
      }

      // Splitted JSON DATA

      float TPS_Json = root["TPS"];
      float MAP_Json = root["MAP"];
      float LOAD_Json = root["LOAD"];

      Serial.print("T_J : ");
      Serial.print(TPS_Json);
      Serial.print("\t");
      Serial.print("M_J : ");
      Serial.print(MAP_Json);
      Serial.print("\t");
      Serial.print("L_J : ");
      Serial.print(LOAD_Json);
      Serial.print("\t");

      //Compare JSON DATA and ARDUINO DATA

      if(TPS_Json == TPS && MAP_Json == MAP) //If matched
      {
        load = LOAD_Json + LOAD;            // Add LOAD_Json and LOAD
      }

      Serial.print("Final Load :");
      Serial.print(load);
      Serial.print("\n");
    }

**EDIT 1:** Improve question formatting

**EDIT 2:** Upload Complete code

body:
Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).

Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".

E.g.:

    float diff = abs(TPS - TPS_Json);
    if (diff < 0.5) {
        // do something
    }


message:
Measuring voltage from -12 to +12 VDC

I'm making a -12 to +12V DC regulated power supply, on which I want to measure voltage and current with Arduino (through a voltage divider, of course).

I'm not sure, how to either detect nor measure negative voltage. I could "detect" it via a Schottky diode, but I'd get about 0.3V voltage drop, but that's not what I want, because any voltage between 0.0V and -0.3V wouldn't be measured. I want also to be able to measure positive and negative voltage on the same Arduino analog input pin.

And furthermore, how to measure current, flowing into both ways? (not an AC current, but will change during operation).

I will make additional PCB for this application, so size and number of components isn't important at all.

body:
Measuring voltage
-----------------

Use the following interfacing circuit for measuring voltage:

[![Voltage translator][1]][1]

Resistors R1, R2, R3 (1% tolerance or better recommended) will map the voltage input range (-12 to +12V DC) to an output range that can be read will the Arduino ADC  (+0.5 to +4.5V DC, in order to have some slack from the top and bottom end of the ADC range). The actual theoretical input range would be -15 to 15V DC.

The optional (but recommended) Schottky diodes D1 and D2 will protect the Arduino analog IN pin that you connect to Vout from any input under/overvoltage outside the -15 to +15V DC range.

This is the resulting input to output voltage translation curve:

[![Voltage translator curve][2]][2]

Measuring current
-----------------

For measuring current, use a current shunt (i.e., a very low resistance resistor, in the milliohm range) and measure the voltage drop on it via a high input impedance differential amplifier, then sample the output of the amp with the Arduino ADC.

<!-- 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/WMOYe.png)

<!-- End schematic -->

Follow [this link][3] to an article in EE Times to learn more about the main options available for current measurements using a shunt.

  [1]: https://i.stack.imgur.com/9D0Kd.png
  [2]: https://i.stack.imgur.com/friCM.png
  [3]: http://www.eetimes.com/document.asp?doc_id=1279415


message:
Smooth out digital signal from SW-420 vibration sensor in order to record duration?

I'm attempting to make a sensor that will record the duration and frequency of a pump going off. It always fires for at least 4 seconds, but the duration can be up to 7 days.  The vibration sensor I have is a SW-420, which I think will work. I'm fairly new at this, and I don't mind figuring out the actual code myself, but I'm running into newb problems.

 1. Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub? Is there a better solution?
 2. Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".
 3. The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

Bonus points if I can accomplish this without any additional libraries. I'd love to put this on an ESP8266.

Thanks for your help, I appreciate it.

body:
> Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

> Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close".  An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with > 49 days by itself.

> The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs?  If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.

To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.


message:
Error compiling: expected unqualified id before token {

#include <LiquidCrystal.h>
    #define trigPin 12              // the trig pin to digital pin 12
    #define echoPin 13              // the Echo pin to digital pin 13
    #define led 8
    #include <Servo.h>
    Servo servoMain; // Define our Servo

    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup() {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led, OUTPUT);
      Serial.begin(9600); // Starts the serial communication
      lcd.begin(16, 2);
      servoMain.attach(11); // servo on digital pin 11
    }

    void loop() {
      servoMain.write(5);  // Turn Servo Left to 5 degrees
      delay(1000); // Wait 1 second
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      if (distance < 3) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("PLEASE REFILL!");
        lcd.setCursor(0, 1);
      } else {
        digitalWrite(led, LOW);
      }
      if (distance < 6) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("U May Refill Now");
        lcd.setCursor(0, 1);
      } else {
        digitalWrite(led, LOW);
      }
      if (distance < 8) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Take it easy");
        lcd.setCursor(0, 1);
      }
      if (distance <= 16) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("FULL!!");
        lcd.setCursor(0, 1);
      }
      if (distance > 16 || distance <= 0) {
        Serial.println("Out of range");
      } else {
        Serial.print(distance);
        Serial.println(" cm");
      }
    }
    delay(1000);
  }
    }

body:
At line 82 you have the closing bracket of the loop function. Then after that you have:

      delay(1000);

    }
    }

Which is invalid.

If you format your code properly it's easy to see. Fix that and it will compile. Will it do what you want is an other question...

    #include <LiquidCrystal.h>
    #define trigPin 12        // the trig pin to digital pin 12
    #define echoPin 13        // the Echo pin to digital pin 13
    #define led 8
    #include <Servo.h>
    Servo servoMain; // Define our Servo

    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup()
    {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led, OUTPUT);
      Serial.begin(9600); // Starts the serial communication
      lcd.begin(16, 2);
      servoMain.attach(11); // servo on digital pin 11

    }
    void loop()
    {
      servoMain.write(5); // Turn Servo Left to 5 degrees
      delay(1000);     // Wait 1 second

      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;

      if (distance < 3) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("PLEASE REFILL!");
        lcd.setCursor(0, 1);
      }
      else {
        digitalWrite(led, LOW);
      }

      if (distance < 6) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("U May Refill Now");
        lcd.setCursor(0, 1);
      }
      else {
        digitalWrite(led, LOW);
      }

      if (distance < 8) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Take it easy");
        lcd.setCursor(0, 1);
      }

      if (distance <= 16) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("FULL!!");
        lcd.setCursor(0, 1);
      }

      if (distance > 16 || distance <= 0) {
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
    }
    delay(1000);

    }
    }


message:
Button to not run script

I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:

    void setup() {
      pinMode(3, INPUT_PULLUP);
      if (digitalRead(3) == LOW) {
        while(1);
      }
      // Beginning the Keyboard stream
      Keyboard.begin();
      // then the rest of the code.

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

body:
I would do it this way:

    void setup () {
        pinMode(3, INPUT_PULLUP);
    }
    void loop () {
        while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
        // do all my stuff
    }

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

    void setup () {
        pinMode(3, INPUT_PULLUP);
        pinMode(13, OUTPUT);
        digitalWrite(13,LOW);
    }
    void loop () {
        while (digitalRead(3)==LOW) {
           digitalWrite(13,HIGH); // let it shine
           };
        digitalWrite(13,LOW);
        // do all my stuff
    }

eventually

    void setup () {
        pinMode(3, INPUT_PULLUP);
        pinMode(13, OUTPUT);
        digitalWrite(13,LOW);
    }
    void loop () {
        if (digitalRead(3)==LOW) {
           digitalWrite(13,HIGH); // let it shine
           while (digitalRead(3)==LOW) {
              // do some other stuff
           };
        digitalWrite(13,LOW); // switch indicator off
        // do my regular stuff
    }


message:
Easy bipolar motor control?

Is here some easy way to control bipolar motor
 without using any other external devices, drivers or shields? I have small motor from CD-ROM so I expect it's low voltage. By control I mean just turning clockwise  and anti-clockwise and speed. I'm looking for easy to make circuit not just direct control from Arduino.

body:
No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.

You need a motor driver (or at least some transistors and diodes etc) to control the motor.


body:
Taking a guess here, the current this motor requires will be exceeding the safe operation limits of the Arduino's GPIO pins. Furthermore without a [flyback diode](https://en.wikipedia.org/wiki/Flyback_diode) the voltage spike across the motor (an inductive load) when the current is reduced/switched off might kill the GPIO pin.

You will need a motor driver or transistor with flyback diodes to operate it.

[This](http://www.instructables.com/id/Run-A-CDROM-Brushless-Motor-With-Arduino/) is a nice tutorial that has it sorted out for a CD ROM brushless motor.


message:
Avoid blocking from bluetooth callbacks

I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.

    // timer interrupt 20Hz
    // reading sensors to buffer
    ISR() {
     int a = analogRead(A0);
     buffer.push(a);
    }

    void loop(){
     if buffer.isFull() {
      myFile.open("data.csv", FILE_WRITE);
      myfile.print(buffer.getData());
      myFile.close();
     }
    }

    // possibility of blocking data collection process
    RFduinoBLE_onConnect() {
     int freeSpace = SD.vwd()->fileSize();
        // other operations for monitoring data collection process
     RFduinoBLE.sendInt(freeSpace);
    }

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.

What is the recommended technique to make sure that data collection process will not be affected?

UPDATE:

The actual usage is that RFduinoBLE_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE_onConnect requests?

body:
Well, one easy, but effective improvement is to use 2 buffers for writing data - while you are writing the one full to file, your interrupt can safely push values to the other and then after the other is full, your ISR would go to first one, while the second will be written. So even long open/seek/write/close loop does not get hit by new data arrival.

Then the main problem - RF - I would bet, that the on_connect() is called from interrupt too, as it is not mentioned anywhere in the loop(). In that case you would like to have it as small and fast as possible. So if you are only providing data, I would collect all the data in the main loop() in some variable (structure, class, what you need), get it thread safe as much as possible (atomic operations, or have two instancies, one actually enabled for the callback, the other opened for filling new data, then pointers to point which is which and just reassigning those pointers in atomic way (means disable interrupts, swich two pointers, enable interrupts - interrupts can wait for time need to two pointers be changed - on other hand you have no chance do anything in main loop (as disabling interrupts), while interrupt is actually running)

So (I know, it is just example, but) you know, that fileSize() is changed only after file is written - so save its value to some (volatile, of course) variable each time you write to the file and use that variable in onConnect.

So more like this (did not tested it, just idea):

    volatile buffs[2];
    volatile actBuff;
    // timer interrupt 20Hz
    // reading sensors to buffer
    ISR() {
        int a = analogRead(A0);
        buffs[actBuff].push(a);
    }

    volatile int freeSpace;
    void loop(){
        if buffs[actBuff].isFull() {
            int fullBuff=actBuff;
            cli();             // disable global interrupts
            actBuff = 1 - actBuff; // switch actual Buffer between 0 and 1
            sei();// enable global interrupts
            // ISR have nice free buffer to fill, we will write and empty the old one
            myFile.open("data.csv", FILE_WRITE);
            myfile.print(buffs[fullBuff].getData());
            myFile.close();
            buffs[fullBuff].empty()
            int tempval = SD.vwd()->fileSize();
            cli();             // disable global interrupts
            freeSpace = tempval;
            sei();// enable global interrupts:
        }
    }

    // possibility of blocking data collection process
    RFduinoBLE_onConnect() {
        // int freeSpace = SD.vwd()->fileSize();
        // do the same trick here // other operations for monitoring data collection process
        RFduinoBLE.sendInt(freeSpace); // use the value from loop
    }


message:
How to find the pin map for the LCD 1602 I2C adapter module?

I'm working with I2C to work with my LCD 1602 and the I2C adapter.

This module has 16 pins and I don't know how to communicate with it.

I2C sends 8-bit packets. What are the commands to deal with this module, because it has 16 pins?

This is my current code:

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

    void I2C_init(void);
    void I2C_start(void);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    void I2C_TWSR_Check(void);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      I2C_init();
      I2C_TWSR_Check();
      I2C_start();
      I2C_TWSR_Check();
      I2C_tx(0x20);
      I2C_TWSR_Check();
    }

    void loop() {
      uint8_t i;

      for (i = 0; i < 5; i++)
      {
        I2C_tx(0xff);
        I2C_TWSR_Check();
        _delay_ms(500);
      }
    }

    void I2C_init(void) {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1 << TWEN);
    }

    void I2C_start(void) {
      TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));
    }

    void I2C_stop(void) {
      TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
    }

    void I2C_tx(uint8_t u8data) {
      TWDR = u8data;
      while (!(TWCR & (1 << TWINT)));
    }

    void I2C_TWSR_Check(void) {
      uint8_t Status;
      Status = TWSR & 0xF8;
      switch (Status)   {
        case 0x08:    // start OK
          Serial.println("Start is OK");
          break;
        case 0x10:    // Re start
          Serial.println("Re start");
          break;
        case 0x18:        // SLA+W OK ACK
          Serial.println("SLA+W OK ACK");
          break;
        case 0x20:        // SLA+W no ACK
          Serial.println("SLA+W no ACK");
          break;
        case 0x28:        // data OK ACK
          Serial.println("data OK ACK");
          break;
        case 0x30:        // data OK no ACK
          Serial.println("data OK no ACK");
          break;
        case 0x38:        // arbitration lost in SLA+W or data TX
          Serial.println("arbitration lost in SLA+W or data TX");
          break;
        default:
          Serial.println("Error");
          break;
      }
    }

I don't know I get first case working all the time. I can't proceed to sending the data.

This is the most I got from google images:
[PCF8574 I2C backpacks for HD44780 Compatible LCD Module Arduino Raspberry][1]

  [1]: http://www.wtihk.com/image/cache/catalog/arduino/module/I2C_LCD/I2C_backpack_for_LCD_modules_layout-500x500.png

body:
The ￼[tronixstuff page about PCF8574-based backpacks for LCD modules and Arduino](http://tronixstuff.com/2014/09/24/tutorial-serial-pcf8574-backpacks-hd44780-compatible-lcd-modules-arduino/) (with [material that also appears in an instructable](http://www.instructables.com/id/Using-PCF8574-backpacks-with-LCD-modules-and-Ardui/)) includes a sketch that most likely will work with that backpack.

Once you've identified which I2C library to use, and the appropriate object instantiation, most of the general API description (that is, “the commands to deal with this module”) as shown at [arduino.cc's *LCDi2c Library*](http://playground.arduino.cc/Code/LCDi2c) page and at [arduino.cc's *LCD API 1.0*](http://playground.arduino.cc/Code/LCDAPI) page will apply.

The I2C library-include and the appropriate object instantiation for the backpack shown in your link probably will look much like:

    #include <LiquidCrystal_I2C.h>
    ...
    LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);

For documentation of what the numbers mean, see lines 82 to 90 of LiquidCrystal_I2C.h:

    @param      lcd_Addr[in] I2C address of the IO expansion module. [...]
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d4[in] LCD data 0 pin map on IO extender module
    @param      d5[in] LCD data 1 pin map on IO extender module
    @param      d6[in] LCD data 2 pin map on IO extender module
    @param      d7[in] LCD data 3 pin map on IO extender module

Briefly, 0x27 is the I2C address of the PCF8574 chip on the backpack.  Note, if your backpack has a PCF8574A, its address is 0x3F.

The other seven numbers describe which PCF8574 output pin is connected for each designated purpose.  Most PCF8574/PCF8574A I2C backpacks are wired the same and numbers 2,1,0,4,5,6,7 are appropriate.

---

*Edit 1:* If you write an LCD-with-backpack library of your own and expect to publish it, it is reasonable to comply with the [LCD API mentioned earlier](http://playground.arduino.cc/Code/LCDAPI).  By using standard interface functions, you will make it possible for users to plug in your library in place of others with the same interface.  In addition, the availability of sketches using the LCD API provides you with a range of test material to verify your drivers.

In writing an LCD-with-backpack library, start by solidifying your understanding of each of the parts – LCD and backpack – separately.

**LCD:**  Get some HD44780-based LCD units; hook one up using direct wiring or a shield rather than a backpack; install a known-good library and sketch; run tests to verify the wiring.  With the wiring known to work, develop an LCD control library.  This may require detailed study of the Hitachi HD44780U data sheet or other HD44780 data sheets.  The necessary timing for LCD control is picky enough that it would be a fool's errand to not verify the wiring using known-good software before writing your own.

**Backpack:**  Plug the 16 pins of a backpack into a breadboard, and attach LED cathodes to all the breadboard pins that connect to PCF8574 output pins.  Use appropriate resistors to V+ on the anode sides of the LEDs.  Connect the backpack's SDA, SCL, V+, and ground to that of your Arduino.  Write simple test software using `Wire.h` calls to send data to the PCF8574, verifying proper operation using the LEDs.  This may require detailed study of the Texas Instruments *PCF8574 Remote 8-Bit I/O Expander for I2C Bus* data sheet.  Write your PCF8574 control library.  Adapt your LCD control software to send data via the PCF8574 library instead of via direct wiring.


message:
How to connect an Arduino to WIFI using an ESP8266

Hi I am trying to make `Arduino Uno` on local network with the help of ESP8266 wifi module.

I tried to search on internet, found mostly they are making `ESP8266` as web server.http://circuits4you.com/2016/12/16/esp8266-web-server-html/

Can anyone help me how to add `Arduino Uno` on network with the help of `ESP8266`.
[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/sVmx8.jpg
  [2]: https://i.stack.imgur.com/ceO4o.jpg

body:
It depends on how you want to approach it.  I know of two options:

1. Use AT commands.
2. Program the ESP.

When you are using AT commands you need to program the Arduino to open a serial line to the ESP (ensuring rx and tx are crossed over).  You tell the Arduino to send the AT commands you need to the ESP and wait for each one to be acknowledged.  Then the Arduino sends its network data via the serial connection, to the ESP and the ESP will forward it to the network.

You can program the ESP in EXACTLY the same way as you would the Arduino.  You could write some code to accept data from the Arduino over either Serial, SPI, I2C or your own proprietary communication method.  The ESP has libraries to be a DHCP client, DNS, HTTP client, etc. (most of which you have probably seen already).  If you then write a simple application that establishes the connection to the network and then waits for a packet of data from either the Arduino or the network and forwards it as appropriate.

I can't tell you which option is best, because I have never tried either method.  I just program the ESP to do everything that the Arduino would have done anyway and simplify the code.


body:
Sending the following commands to the ESP should get you started:

    AT+RST                         # Reset
    AT+CWMODE=1                    # Set to station-mode as a client
    ATE0                           # turn off command echo
    AT+CWLAP                       # optional: list access points
    AT+CWJAP_DEF="SSID","PASSWORD" # Always connect to this SSID

(I made-up the comment syntax; don't try to send those.) The full
[ESP8266 AT Instruction Set][1] has the complete set of commands and a functional description of each one.

Update:
> ... do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to
> TX of Arduino, Ground of Arduino to RESET ?

Rx & Tx must be cross-connected with the corresponding Arduino pins and the ESP's reset pulled high (3.3v).

  [1]: https://espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf


message:
How to set alarm on DS3231 sensor?

I want to know if it is possible to set an alarm in DS3231.
I want to set the alarm every 6 AM in the morning. Is this possible?

body:
Yes it is (see datasheet [datasheet][1]) ... the DS3231 has 2 alarms.

There is also a library for the Arduino, see: [library][2].
The alarm(s) can be set (repeatedly) via one of the following functions:

    Alarm.alarmRepeat(hours, minutes, seconds, function);
    Create an alarm that will call a function every day at a particular time.

    Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
    Create an alarm that will call a function every week on a specific day at
    a particular time.

     "dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday,
     dowThursday, dowFriday, or dowSaturday.

Detailed info and more functions: [link][3]

  [1]: https://datasheets.maximintegrated.com/en/ds/DS3231.pdf
  [2]: http://playground.arduino.cc/Code/Time
  [3]: https://www.pjrc.com/teensy/td_libs_TimeAlarms.html


body:
I find the answer to my question .
I just add `Time  t;` and `t = rtc.getTime();` into my code then an if statement like this `if (t.hour == 11 && t.min == 59 && t.sec == 00)`

ref http://www.instructables.com/id/Setup-for-DS3231-AlarmTimer-Function/


message:
#define VS local static const char

Could someone give me a hint regarding what would be the best practice to save memory: should I `#define` strings or use local `static const char` arrays?

Code example, option #1:

    #define    LCD_LIMIT "Number of hours"
    ...
    setup(){
        DisplayData(LCD_LIMIT, actual_Data);
    }
    ...
    void DisplayData(const char *theme, String data){
    }

Code example, option #2:

    setup(){
        DisplayData(actual_Data);
    }
    ...
    void DisplayData(String data){
        static const char theme[] = "Number of hours";
    }

Cheers

body:
I think they both are similar with respect to memory stored in the heap.

However, since you pass one extra pointer, it cost 2 of 4 bytes extra on the stack (temporary space).

To save more memory use the F() function to store it in FLASH (32 KB on Arduino Uno) instead of the heap (only 2 KB). By using

    static const char theme[] = F("Number of hours");


body:
The #define will be substituted in at compile time. So as far as memory usage goes

    #define MYSTRING "hello world"
    DisplayData(MYSTRING);

and

    DisplayData("hello world");

are completely identical.

but

    static const char theme[] = "hello world";
    DisplayData(theme);

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).

However if you are using the same string twice or more then things are different.

The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size.
If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.


message:
Combining code for two sensors in one programming

We need to read two readings of Humidity and Temperature from 2 different locations. We can run each of them separately but we don't know how we can make them work simultaneously in one program. We are using a TH02 sensor that we connect to I2C and DHT11 that is connected to one of the Analog port.

We are connecting them to Grove base shield V2, which is on top of Arduino uno wifi.

TH02 Code:

     void setup()
    {
    Serial.begin(9600);        // start serial for output

    Serial.println("****TH02_dev demo by seeed studio****\n");
    /* Power up,delay 150ms,until voltage is stable */
    delay(150);
    /* Reset HP20x_dev */
    TH02.begin();
    delay(100);

    /* Determine TH02_dev is available or not */
    Serial.println("TH02_dev is available.\n");
    }

    void loop()
    {
    float temper = TH02.ReadTemperature();
    Serial.println("Temperature: ");
    Serial.print(temper);
    Serial.println("C\r\n");

    float humidity = TH02.ReadHumidity();
    Serial.println("Humidity: ");
    Serial.print(humidity);
    Serial.println("%\r\n");
    delay(1000);
    }

DHT11 Code:

    byte read_dht11_dat()
    {
    byte i = 0;
    byte result=0;
    for(i=0; i< 8; i++){

        while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
        delayMicroseconds(30);

        if(PINC & _BV(DHT11_PIN))
        result |=(1<<(7-i));
        while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
    }
    return result;
    }

    void setup()
    {
    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    Serial.begin(9600);
    Serial.println("Ready");
    }

    void loop()
    {
    byte dht11_dat[5];
    byte dht11_in;
    byte i;
    // start condition
    // 1. pull-down i/o pin from 18ms
    PORTC &= ~_BV(DHT11_PIN);
    delay(18);
    PORTC |= _BV(DHT11_PIN);
    delayMicroseconds(40);

    DDRC &= ~_BV(DHT11_PIN);
    delayMicroseconds(40);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(dht11_in){
        Serial.println("dht11 start condition 1 not met");
        return;
    }
    delayMicroseconds(80);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(!dht11_in){
        Serial.println("dht11 start condition 2 not met");
        return;
    }
    delayMicroseconds(80);
    // now ready for data reception
    for (i=0; i<5; i++)
    dht11_dat[i] = read_dht11_dat();

    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
    // check check_sum
    if(dht11_dat[4]!= dht11_check_sum)
    {
        Serial.println("DHT11 checksum error");
    }

    Serial.print("Current humdity = ");
    Serial.print(dht11_dat[0], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[1], DEC);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(dht11_dat[2], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[3], DEC);
    Serial.println("C  ");

    delay(2000);
    }

body:
This example combines both codes but uses a single `delay`. If you want readings at two different times you should use two `unsigned long` global variables to store the `millis()` of the last time the functions were called. Then you use an `if` statement to only call `readTH02()` or `readDHT11()` when the last `millis` is less than the `<= current-interval`.

It is better to use `millis` interval checking instead of delays but I have not made significant changes to your code to implement that. Take a look at the Arduino IDE example called `BlinkWithoutDelay` to understand how to use intervals instead of `delay()`

    void setup()
    {
      setupTH02();
      setupDHT11();
    }

    void loop()
    {
      readTH02();
      readDHT11();

      delay(1000);
    }

    void setupTH02()
    {
    Serial.begin(9600);        // start serial for output

    Serial.println("****TH02_dev demo by seeed studio****\n");
    /* Power up,delay 150ms,until voltage is stable */
    delay(150);
    /* Reset HP20x_dev */
    TH02.begin();
    delay(100);

    /* Determine TH02_dev is available or not */
    Serial.println("TH02_dev is available.\n");
    }

    void readTH02()
    {
    float temper = TH02.ReadTemperature();
    Serial.println("Temperature: ");
    Serial.print(temper);
    Serial.println("C\r\n");

    float humidity = TH02.ReadHumidity();
    Serial.println("Humidity: ");
    Serial.print(humidity);
    Serial.println("%\r\n");
    //delay(1000);
    }

    byte read_dht11_dat()
    {
    byte i = 0;
    byte result=0;
    for(i=0; i< 8; i++){

        while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
        delayMicroseconds(30);

        if(PINC & _BV(DHT11_PIN))
        result |=(1<<(7-i));
        while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
    }
    return result;
    }

    void setupDHT11()
    {
    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    Serial.begin(9600);
    Serial.println("Ready");
    }

    void readDHT11()
    {
    byte dht11_dat[5];
    byte dht11_in;
    byte i;
    // start condition
    // 1. pull-down i/o pin from 18ms
    PORTC &= ~_BV(DHT11_PIN);
    delay(18);
    PORTC |= _BV(DHT11_PIN);
    delayMicroseconds(40);

    DDRC &= ~_BV(DHT11_PIN);
    delayMicroseconds(40);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(dht11_in){
        Serial.println("dht11 start condition 1 not met");
        return;
    }
    delayMicroseconds(80);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(!dht11_in){
        Serial.println("dht11 start condition 2 not met");
        return;
    }
    delayMicroseconds(80);
    // now ready for data reception
    for (i=0; i<5; i++)
    dht11_dat[i] = read_dht11_dat();

    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
    // check check_sum
    if(dht11_dat[4]!= dht11_check_sum)
    {
        Serial.println("DHT11 checksum error");
    }

    Serial.print("Current humdity = ");
    Serial.print(dht11_dat[0], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[1], DEC);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(dht11_dat[2], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[3], DEC);
    Serial.println("C  ");

    //delay(2000);
    }


message:
Serial monitor isn't updating in while loop

I'm trying to make a lamp that fades when it reacts with surrounding light. I've installed a library from github  that doesn't require the delay (). The serial monitor doesn't refresh.
The lamp is supposed to fade from 0-255 when in the dark and fade 255-0 when in light. It's supposed to happen only once so I can't put it in loop().

The LED is connected to PWM pin 10. The LDR sensor is connected to A0.

    #include <LEDFader.h>
    int sensorvalue = analogRead(A0);
    LEDFader led = LEDFader(10);

    void setup(){

      if(sensorvalue<=380){
        led.set_value(0);
        led.fade(255, 3000);
      }
      if(sensorvalue>=555){
        led.set_value(255);
        led.fade(0,3000);
      }
    }

    void loop() {
      Serial.begin(9600);
      Serial.println(sensorvalue);
      led.update();
   }

body:
Arduino does not work that way. You only try to read a sensor value outside of a function, so will happen once only, if it works at all. You need to read the sensor more often and always read from within a function.

`Serial.begin()` is used once when the code starts, so that will be in the setup()

Your LED fade values are only set one time, when the cpu starts because you have the fade in the `setup()`.

In the following example we do all fade code in the `loop()` but change the fade values only when the sensor reading changes.

    #include <LEDFader.h>
    LEDFader led = LEDFader(10);

    int sensorValue = 0;
    int sensorValueLast = 0;

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

    void loop()
    {
      sensorValue = analogRead(A0);
      Serial.println(sensorValue);

            if (sensorValueLast!=sensorValue)
            {
              sensorValueLast = sensorValue;
              if(sensorvalue<=380)
              {
                 led.set_value(0);
                 led.fade(255, 3000);
              }
              if(sensorvalue>=555)
              {
                led.set_value(255);
                led.fade(0,3000);
              }
            }

      led.update();
    }

This example only calls `led.fade()` when the sensor value changes but uses the same sensor reading that was found during startup. The sensor is read just once time and the fade values are set just one time.

    #include <LEDFader.h>
    LEDFader led = LEDFader(10);

    int sensorValue = 0;
    int sensorValueLast = 0;

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

    void loop()
    {
      sensorValue = analogRead(A0);
      Serial.println(sensorValue);

            if (sensorValueLast!=sensorValue)
            {
              sensorValueLast = sensorValue;
              if(sensorvalue<=380)
              {
                 led.set_value(0);
                 led.fade(255, 3000);
              }
              if(sensorvalue>=555)
              {
                led.set_value(255);
                led.fade(0,3000);
              }

              led.update();
            }
    }

This example does everything just one time, when the cpu starts

    #include <LEDFader.h>
    LEDFader led = LEDFader(10);

    int sensorValue = 0;

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

       sensorValue = analogRead(A0);
       Serial.println(sensorValue);

              if(sensorvalue<=380)
              {
                 led.set_value(0);
                 led.fade(255, 3000);
              }
              if(sensorvalue>=555)
              {
                led.set_value(255);
                led.fade(0,3000);
              }

              led.update();

    }

    void loop()
    {
       //we will always see the same value
       Serial.println(sensorValue);
    }


message:
#endif without #if

I have an extrange Problem...
I have written this short code:

    ////////////// BOARD SETTINGS \\\\\\\\\\\\\\
    #define BAUD_RATE 9600

    // Board type selection
    // Uncomment the wanted
    //#define WAND 0
    //#define GUN 0
    #define RIFLE 0

    ////////////// WAND SETTINGS \\\\\\\\\\\\\\
    #ifdef WAND
    //#define USE_CHARGER 0

    #endif

    ////////////// GUN SETTINGS \\\\\\\\\\\\\\
    #if GUN
    //#define USE_CHARGER 0

    #endif

    ////////////// RIFLE SETTINGS \\\\\\\\\\\\\\
    #ifdef RIFLE
      #define USE_CHARGER 0

    #endif
It's in a file called `Settings.h`, that I use in the main code:

    #include "Settings.h"

    void setup(){
      Serial.begin(BAUD_RATE);
      #ifdef WAND
        Serial.println("Initializing Wand...");
      #endif
      #ifdef GUN
        Serial.println("Initializing Gun...");
      #endif
      #ifdef RIFLE
        Serial.println("Initializing Rifle...");
      #endif
    }

    void loop(){
      #ifdef WAND

      #endif
      #ifdef GUN

      #endif
      #ifdef RIFLE

      #endif
    }
But for an extrange reason, it gives me this error: `error: #endif without #if`
Full error is:

    In file included from D:\MEGA\Winsoft\Projects\Hardware\MWands\Arduino_5\Arduino_5.ino:1:0:

    Settings.h:15: error: #endif without #if

     #endif

      ^

    Settings.h:21: error: #endif without #if

     #endif

      ^

    Settings.h:27: error: #endif without #if

     #endif

      ^

    exit status 1
    #endif without #if
Any idea in where am I wrong?

And taking advantage that I'm asking, is necessary the 0 after `#define RIFLE 0`, next to each definition?

body:
If you remove backslashes at the end of comments on lines before `#ifdefs`, it will work just fine.

The gvim editor was much more helpful in that:
[![enter image description here][1]][1]

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


body:
It looks like your comment style is causing the problem.

Remove the `////////////// BOARD SETTINGS \\\\\\\\\\\\\\` style comments, or change them to something like: `/*----------- BOARD SETTINGS -----------*/`


message:
Arduino Nano Circuit grounding

I am making an LED circuit for a Lobot (from star wars) costume headset that will not be on a PCB or stripboard. It will all be running inside the walls of the plastic shell I am making. Please see Gif of what I am hoping to do:

[![Gif of Lobot from the star wars in action][1]][1]

EDIT:
-----
The LEDs will run through 4 different programs. Here is one program as an example:

-Far left and right led pairs will alternate on/off
-Single LEDs will blink twice then off for a cycle
-The (4) pairs on the left and right will rise and fall like a soundboard
-The (3) pairs of white(blue in the demo) will chase bottom to top and back down again

I am new to electronics so I am a little nervous about running the ground wire for it. Here is my circuit:
## EDIT 2: ##

Here is a reworked diagram based on the suggestions i received below:
[![Circuit with resistors][2]][2]

The reds were switched to blue for the simulation but will actually be white. So they are 3v each but running in parallel will need 100ohm.

Now that we have that out of the way, is the ground wire run correctly?

The simulation runs perfectly, but I want to make sure that I am not overlooking something important before I try it on my arduino IRL. Is there a neater way to do this? Google searches availed me not. What is the accepted method for this type of circuit?

  [1]: https://i.stack.imgur.com/1FHVv.gif
  [2]: https://i.stack.imgur.com/ktXVY.jpg
  [3]: https://i.stack.imgur.com/9LJWI.gif

body:
The schematics is unfortunately somewhat complicated to read as one has to look at the pinout to understand it. When comparing it to the [pinout](http://www.keywild.com/arduino/gallery/Nano_PinOut.png) however I find a few things that are odd, e.g. one of the green wires (top, fourth pin from the right) is connected to GND.

Note that the sum of the forward voltages of the LEDs connected in series need to be (significantly) lower than the supply voltage of the Arduino. This forward voltage is different for differing LEDs (depending on the colour). Blue LEDs have a higher voltage (typically 3.0 - 3.5 volts). Connecting two blue LEDs or some more red LEDs in series leads to a necessary forward voltage higher than what the Arduino can provide.

Be sure to add the current limiting resistor for the LEDs in the appropriate places. Due to the non-linear current-voltage characteristic of (light emitting) diodes those resistors are a must-have (unless driving them with a current source, which the Arduinos GPIO pins are not). Do use one resistor per LED or if LEDs are connected in series. Do not use only one resistor for LEDs wired in parallel. For more details on this topic see [here](https://electronics.stackexchange.com/q/32990/52154).

**Edit to add** ([revision of question](https://arduino.stackexchange.com/revisions/37893/4)):

Given 3 V forward voltage and 100 Ohm series resistor one LED presumably leads to a current of about 20 mA. But since you intent to drive two LEDs in parallel (so 40 mA) from each pin, you're well out of spec and hitting Absolute Maximum Ratings:

DC current rating, [source](https://www.arduino.cc/en/Main/arduinoBoardMicro#techspecs):

> DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  20 mA

Absolute Maximum Rating, [source](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf)

> DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  40.0mA

Furthermore you intend to connect 18 pairs of LEDs (give or take the red LEDs). This would be a total current of 720 mA which is significantly above the limits of the microcontroller. Consider that all the current flowing through the LEDs into the GPIO pins also needs to flow to VCC through the controllers power supply lines (just two pins!). Those have limits too:

Absolute Maximum Rating, [source](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf)

> DC Current VCC and GND Pins  . . . . . . . . . .  200.0mA

You need an external driver (such as the ULN2803, as presented in [this answer](https://arduino.stackexchange.com/a/37899/17196)) or transistors.


body:
I am putting all comments here as answer.
Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D

Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino.

To make it SUPER COOL i would suggest [WS2812B][1] LEDs. They need 5V, GND, and Data in. And you can make it any color you want and control all LEDs separately.

[Some video about WS2812B][2]

I would strongly recommend it.

  [1]: http://www.seeedstudio.com/document/pdf/WS2812B Datasheet.pdf
  [2]: https://www.youtube.com/watch?v=KaClIgAVuI8


message:
Using a 4*4 keypad to enter an integer value

I have a 4*4 keypad and I want to use it to enter a number.  I will then use this number as a delay to a LED or a motor to run for the specified time.
This is my sample code:

    #include<Keypad.h>
    #include<LiquidCrystal.h>
    const byte numRows = 4; //number of rows on keypad
    const byte numCols = 4; //number of columns on keypad

    char keymap[numRows][numCols]=
    {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'X', '0', 'Y', 'D'}
    };

    char value[4]="";
    int index = 0;

    byte rowPins[numRows] = {22,23,24,25}; //Rows 0 to 3
    byte colPins[numCols]= {26,27,28,29}; //Columns 0 to 3

    Keypad key= Keypad(makeKeymap(keymap), rowPins, colPins, numRows,numCols);

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

    void setup() {
    Serial.begin(9600);
    pinMode(13,OUTPUT);
    lcd.begin(20,4);

    lcd.print("       WELCOME      ");
    delay(100);
    }

    void loop() {
    char keypress = key.getKey();
    while (keypress != NO_KEY){
      if (keypress == 'X'){
          lcd.clear();
          for(int j=0;j<=4;j++){
            value[j]=0;
          }
          index=0;
          }
       else if (keypress == 'Y'){
          int amt = atoi(value);
          digitalWrite(13, HIGH);
          delay(amt);
          }
       else
          value[index]=keypress;
          index++;
        }
    }

How do I read the value returned by the keypad as an integer?  (When I press 3 I want to read 3 not "3").

body: Your problem is that you have your keypress matching inside a while loop. That means it will, once matched once, continue matching over and over again as infinitum. You need to replace your while with an if so it only runs once for each keypress.


body:
You can easily read by this line of code

    value = anyDigitFromKeypad - 48

e.g value = "3"-48 = 3


message:
Basic questions on Inputs

I'm completely new to Arduino or even micro-controllers, I'm not even good in physics.

First of all, I'll explain what I am trying to build:

I have an Arduino Nano, for a university project (computer science) I'm trying to make an alternative controller(HID). This controller will be a simple glove, which contains conductive yarn from the Arduino to each finger. If two fingers connect their conductive yarn, I know which fingers are connected and I map this to an input for the computer, which I connected to the Arduino.

For example, if the thumb touches the index finger, it means an `X` on the computer.

To get the code done is not the problem I guess.

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

Since I'm completely new, I have some pretty basic questions:

1) Can I use the circuit diagram I created or won't it work? Imagine the switches are my hand, which works like a switch.

2) Does my circuit need a connection to 5V and ground, or can one of the pins be a GROUND / 5V?

3) To know if a switch is active, do I have to watch for changes on the pin? For example, the pin is LOW, is it HIGH after the circuit is "closed"?

If you guys can provide me further information for my project or nice tutorials to get in touch with micro-controllers, I would really appreciate it.

Thank you in advance!

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

body:
>1) Can i use the circuit diagram i created or wont it work?

It won't work. The reason is when the switches are open the input pins are floating and that means they could be `HIGH`or `LOW` or flipping back and forth. You want the pins to be always in a specific state whether the switch is open or closed. To do this a pull-up or pull-down resistor is used. This resistor sets the pin to `HIGH` or `LOW` respectively when the switch is open but the value of the resistor is chosen so that when the switch is closed it overpowers the resistor and the pin reads the opposite state. Since you have your switches connected between the input pin and 5 V you would need to add a pull-down resistor to every pin. That's easy enough but there is an even easier way. The microcontroller on your Nano has internal pull-up resistors you can turn on by doing this:

    pinMode(inputPin, INPUT_PULLUP);

See: https://www.arduino.cc/en/Reference/PinMode

So using the internal pull-ups meas you wouldn't need to add any extra components. But a pull-up isn't helpful if you have your switches connected to 5 V because that would make the pin read `HIGH` whether the switch is opened or closed. So you would need to connect the switches to GND instead. This would mean that the input pin will read `HIGH` when the switch is open and `LOW` when the switch is closed.

>3) To know if a switch is active do i have to watch for changes on the Pin?

Of course. The easiest way to do this is with `digitalRead()`.

See: https://www.arduino.cc/en/Reference/DigitalRead

You need to make sure your code is non-blocking. When blocking code like `delay()` is used the microcontroller will not be able to check the state of the input pins and so you could miss touches or have the controller not be responsive enough.


body:
When you're dealing with switches, you need to watch out for 'bounce'. This means that a switch is never perfect and when it changes state from ON to OFF or vice versa, usually there are several fluctuations that take place before the switch settles on a final ON/OFF value.

You could debounce your switches by either hardware or software. If you're debouncing your switches by software basically you run a check on each switch to see if it's digital value has stabilised over some finite time period (usually a few milliseconds) and take action on the switch value only AFTER its value has stabilised.

Hardware debouncing makes use of capacitors in your circuit that prevent high frequency fluctuations in the line from reaching your digital pin. Put simply, the capacitor acts like a channel to 'drain' away variations in voltage. If you are implementing hardware debouncing, you can just do a digitalRead() to read your pin.

http://dduino.blogspot.in/2012/03/arduino-button-debouncing.html


message:
SPP-C and HC-05 are they the same thing or something else?

I was actually thinking to buy a cheap HC-05 module while I was searching I found a similar (think so) [module](https://m.aliexpress.com/s/item/32616503772.html) It say it is a replace for HC modules.

Is it compatible with Arduino Nano and will it work same as the HC-05 module ????

body: Yes, both the SPP-C and HC-05 are compatible with the Arduino range, and they do work in pretty much the same manner!


body:
In theory they are the same and have the same capabilities. Practically they are not. With SPP-C you get twice the headache for half the price as for HC-05. In had to find it out the hard way [Sending data using Bluetooth SPP-C Module without a Breakout-Board][1]. I tried both SPP-C and HC-05 with and without breakout boards finding the same issues. So if you are willing to spend time, risk your project and save some money then use SPP-C. Otherwise use the well known HC-05.

  [1]: https://arduino.stackexchange.com/questions/26873/sending-data-using-bluetooth-spp-c-module-without-a-breakout-board


message:
Can I connect an Arduino Uno Wifi to Arduino Cloud?

If yes, how? If no, what cloud is compatible?

I have tried to look online but I could not find anything that raises this question.

body:
If you sign in to Arduino Cloud the very first thing it asks you is which board you are using. One of the options is the Arduino WiFi Shield 101. That is a shield that you can attach to any Uno-footprint board (including the Uno) to give it encrypted WiFi.

Another option is the Yun shield which turns your Uno into a kind-of Yun.

There are many many other "clouds*" that support Arduino, and many that if you are a reasonable programmer should be simple enough to make work with Arduino, since 99.99% of them all work through some form of HTML-based interface.

----

* Cloud: *n.* An idiotic buzzword used to describe pretty much any website these days.


message:
How to program Fio v3 without MicroUSB port

I got given a Fio V3 but unfortunately the MicroUSB port is missing, not sure why.  Is there any other way to program it?  I'm thinking perhaps those 6 pins under the microcontroller?

[![fiov3][1]][1]

Also can I still power the board?  I notice it doesn't have a VCC or RAW pin like the Pro Micro version.  I'm not to worried about using a battery, can I plug any matching voltage into the battery plug?

I tried looking through the schematics and tutorials on Sparkfun but don't really know what I'm looking at.  Here are some relevant links anyhow:

* [Product page][2]
* [Schematics][3]
* [Datasheet][4]

  [1]: https://i.stack.imgur.com/e32KL.jpg
  [2]: https://www.sparkfun.com/products/11520
  [3]: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Fio_v31.pdf
  [4]: https://cdn.sparkfun.com/datasheets/Components/General IC/33244_SPCN.pdf "Datasheet"

body:
The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.

Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.


body:
Looking at the hook up guide might help.  https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide

The "best" solution might be to try and get the connector replaced, if the pads are still OK.  But soldering those connectors is not an easy task.

The datasheet you linked to is the Lion charger, forget about that PDF.


message:
I can't upload my program to Arduino Uno

I've not used my Arduino for about 2 months. Before this time it worked fine, but now when I want to upload my program I get this error:

> Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

I reset immediately after uploading but it doesn't work.What else should I do?
I'm using Ubuntu and the Arduino IDE.

body:
Checks:

- Check if the board has power (probably it will).
- Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
- Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
- Check if you have multiple versions of the IDE running.
- Check if you have multiple IDEs installed.
- Check if you don't have the RX pin used while uploading a sketch.

Try the following:

- Use a different USB port on your computer
- Use a different USB cable
- Reinstall the Arduino IDE


body:
I struggled with a failure to upload the `Blink` program, with LED between #13 pin (+) and GND lead.

My solution was found by choosing other serial ports by stepping through the Serial Port options under the **Tools** menu

Selecting the correct port brought my new board to life!


message:
Detect certain characters and if not a consequence

How can I program in Arduino Uno a `serial.available` that will detect some chars that aren't supposed to belong in a list of options, like this:

    void lerRespostaUtilizador(){
      if(Serial.available('s' && 'v' && 'r'){
        Serial.println("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos.")
      }
      switch(Serial.read()){
        case 's': // Mostrar sinais de controlo
          mostrarSinais();
          Serial.println("Podes visualizar ainda: (v)ariaveis do sistema e conteudo de (r)egistos.");
          Serial.println("");
          break;
        case 'v': // Mostrar variáveis do sistema
          mostrarVariaveis();
          Serial.println("Podes visualizar ainda: (s)inais de controlo e conteudo de (r)egistos.");
          Serial.println("");
          break;
        case 'r': // Mostrar conteúdo de registos
          mostrarRegistos();
          Serial.println("Podes visualizar ainda: (s)inais de controlo e (v)ariaveis do sistema.");
          Serial.println("");
          break;
        }
    }

What I want is if the user inserts some chars that aren't 's', 'v' or 'r', a message will appear saying what they can insert to obtain certain results.

body:
I would rewrite that as something like this:

    void lerRespostaUtilizador(){
      while (!Serial.available());
      switch(Serial.read()){
        case 's': // Mostrar sinais de controlo
          mostrarSinais();
          break;
        case 'v': // Mostrar variáveis do sistema
          mostrarVariaveis();
          break;
        case 'r': // Mostrar conteúdo de registos
          mostrarRegistos();
          break;
        default:
          Serial.println(F("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos."));
        }
    }


message:
I2C begginer with I/O expander with mega328p C code

I've just started with the I2C protocol. I read about it in the datasheet, other documents, blogs and videos.

So, I started to develop my code and I think I did my first success, I succeeded to send start and check TWST for sending start signal.

I get started OK, but I can't proceed to send data. What I'm missing? I'm thinking I didn't send the correct address.

    void I2C_init(void);
    void I2C_start(void);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    void I2C_TWSR_Check(void);

    void setup() {
      Serial.begin(9600);
      I2C_init();
      //  I2C_TWSR_Check();
      I2C_start();
      I2C_TWSR_Check();
      I2C_tx(0x40);           // sending the address
      I2C_TWSR_Check();       // waiting for response
    }

    void loop() {
      uint8_t i;
      // simple loop to blink an LED on the I/O expander pin
      for (i=0;i<5;i++) {
        I2C_tx(0xff);
        I2C_TWSR_Check();
        _delay_ms(500);
        I2C_tx(0x00);
        I2C_TWSR_Check();
        _delay_ms(500);
      }
    }

    void I2C_init(void) {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1<<TWEN);
    }

    void I2C_start(void) {
      TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
      while (!(TWCR & (1<<TWINT)));
    }

    void I2C_stop(void) {
      TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    }

    void I2C_tx(uint8_t u8data) {
      TWDR = u8data;
      while (!(TWCR & (1<<TWINT)));
    }

    void I2C_TWSR_Check(void) {
      uint8_t Status;
      Status = TWSR & 0xF8;
      switch(Status) {
        case 0x08: // start OK
        Serial.println("Start is OK");
         break;
        case 0x10: // Re start
        Serial.println("Re start");
         break;
        case 0x18: // SLA+W OK ACK
        Serial.println("SLA+W OK ACK");
         break;
        case 0x20: // SLA+W no ACK
        Serial.println("SLA+W no ACK");
         break;
        case 0x28: // data OK ACK
        Serial.println("data OK ACK");
         break;
        case 0x30: // data OK no ACK
        Serial.println("data OK no ACK");
         break;
        case 0x38: // arbitration lost in SLA+W or data TX
        Serial.println("arbitration lost in SLA+W or data TX");
         break;
         default:
         Serial.println("Error");
        break;
      }
    }

body:
OK the answer is that I didn't send the correct address!

Because if the I2C starting command with the slave is successful, then you should get successful sending ACK according reading the value of transmission status from the status register TWSR and ANDing this value with 0xF8. Then by reading the datasheet you know the value of transmission status. I developed a function to determine the status of transmission with Arduino Serial library which is I2C_TWSR_Check();.

I did this code for Master transmitter and receiver only.

So the trick is that you have to fix the address according to the AVR's TW address command format, which is the first bit is for read/write command and the remaining 7-bits are for the address, so you have to shift the real address which I got by "I2C address scanner" I got from one of AVRfreaks members.

For example, if the address is 0x20, then after shifting it 1-bit to the left, the new address is 0x40 for write operation and 0x41 for read operation.

    void I2C_init(void);
    void I2C_start(uint8_t address);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    uint8_t I2C_rx(void);
    void I2C_TWSR_Check(void);

    uint8_t bitmask;

    /////////// I2C modules addresses ////////////
    // 8-bit I/O expander 0x20
    #define IOEXP_WR  0x40    // I/O 8-bits expander address
    #define IOEXP_RD  0x41

    // LCD1602 adapter
    #define LCD1602_WR  0x4E  // LCD1602 I2C adapter address
    #define LCD1602_RD  0x4F

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      I2C_init();
    }

    void loop() {

      I2C_start(LCD1602_WR);
      I2C_TWSR_Check();
      I2C_tx(0xff);
      I2C_TWSR_Check();
      I2C_stop();
      _delay_ms(500);

      I2C_start(LCD1602_WR);
      I2C_tx(0x00);
      I2C_stop();
      _delay_ms(500);
    }

    void I2C_init(void)
    {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1<<TWEN);
    }

    void I2C_start(uint8_t address)
    {
      TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
      while (!(TWCR & (1<<TWINT)));
      //I2C_TWSR_Check();
      TWDR = address;
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      //I2C_TWSR_Check();
    }

    void I2C_stop(void)
    {
      TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    }

    void I2C_tx(uint8_t data)
    {
      TWDR = data;
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      //I2C_TWSR_Check();
    }

    uint8_t I2C_rx(void)
    {
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      return TWDR;
    }

    void I2C_TWSR_Check(void)
    {
      uint8_t Status;
      Status = TWSR & 0xF8;
      switch(Status)
      {
        /////////////// MASTER TRANSMITTER //////////////
        case 0x08:
        Serial.println("Start is OK");
         break;
        case 0x10:
        Serial.println("Re start");
         break;
        case 0x18:
        Serial.println("SLA+W OK ACK");
         break;
        case 0x20:
        Serial.println("SLA+W no ACK");
         break;
        case 0x28:
        Serial.println("data TX OK ACK");
         break;
        case 0x30:
        Serial.println("data TX OK no ACK");
         break;
        case 0x38:        // arbitration lost in SLA+W or data TX
        Serial.println("arbitration lost in SLA+W or data TX");
         break;

        /////////////// MASTER RECEIVER //////////////
        case 0x40:
        Serial.println("SLA+R OK ACK");
         break;
        case 0x48:
        Serial.println("SLA+R OK NO ACK");
         break;
        case 0x50:
        Serial.println("data RX OK ACK");
         break;
        case 0x58:
        Serial.println("data RX OK NO ACK");
         break;

         default:
         Serial.println("Error");
        break;
      }
    }


message:
LED series Resistor- Noob question

Can someone please explain to me, like I'm 5, why this circuit does not work?

[![Led no resistor][1]][1]

Every resistance calculator I use says that there is not enough voltage to calculate a resistance. If I understand correctly, wouldn't the LEDs light but just at a lower brightness?

Using R = V/I, The source voltage is 5v, the LED voltage is 6 divided by the current of 20mA equals -50ohms. All of the charge is used up by the time it reaches the arduino right?

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

body:
LEDs won't necessarily light at lower brightness (or conform to Ohm's law at all), it's explained [here][1]. If an appliance apparently does provide a "dim" LED mode, it's usually using a clocked signal (and blinking rapidly).

  [1]: https://electronics.stackexchange.com/questions/256336/does-led-brightness-change-with-voltage


body:
The two LEDs in series have a forward voltage of 6v which is more than the Arduino's supply voltage.

Forward voltage is the bare minimum amount of voltage required for the LEDs to start conducting electricity (ie: to allow the current to pass through)

Read this: https://www.baldengineer.com/led-basics.html :

> Forward Voltage
>
> The Forward Voltage defines the amount of voltage
> required in order to conduct electricity. Any voltages below this
> amount will cause the LED to remain “Open” and non-conductive. This
> also means any components in-series with the LED will not have current
> flowing through them either! Once the voltage dropped across the LED
> reaches the Forward Voltage, it will begin to conduct electricity. Not
> only that, but the LED will only drop its Forward Voltage at any given
> time.
>
> For example, consider a LED with a Forward Voltage rated at 3.0V. Now
> what happens if you attach the Anode to the Positive (+) Terminal of a
> AA (LR-6) Battery and the Cathode to the Negative (-) Terminal? Will
> the LED do anything? No! The AA (LR-6) Battery only has a nominal
> voltage of 1.5V. Until you add a second battery, the LED will not
> light up.


body:
The simple reason is that LEDs are not light bulbs. An LED is not a passive device and does not follow Ohms law.

To a first approximation if the voltage across an LED is below the forward voltage then no current will flow. In that situation the voltage across the LED pins is whatever the supply voltage is.<br>
If the voltage across an LED is over the forward voltage then an unlimited current can flow and the voltage between the pins is fixed at the forward voltage.

This approximation isn't perfect but 90% of the time it's good enough.

So with 1 LED and no resistor you get 3V over the LED and then 2V left over with zero resistance, I=V/R = 2/0 = infinite current flow. The LED is dissipating 3*infinity watts of energy and instantly vaporizes. Clearly this isn't exactly what happens in the real world but the result is enough to tell you that bad things will happen.

With 1 LED and a 200 ohm resistor you get 3V over the LED and then 2V extra with 200 ohms resistance, I=V/R = 2/200 = 10mA. The LED is within its operating current and will light up.

With 2 LEDs and no resistor you get 3V on one LED and 2 V on the second (or 2.5 on both if you prefer). Either one or both LEDs are below their forward voltage and so no current flows. The LEDs remain off.


body:
 > Can someone please explain to

With the right leds, the circuit can work.

Where it may fail:

1. Two less with combined forward voltage greater than the one applied to them. The meds wouldnt light up or wouldn't light up brightly, depending on the leds used.

2. The two leds with combined forward voltage much less than the supply which has low output resistance. The two leds may light up very brightly, or so briefly ending up in led heaven permanently. If you can capture them in high frame rate code on the glow before their death is quite pretty.


message:
Should I use OOP?

I am a long time participant in a competition called [Robocup Rescue Line](http://rcj.robocup.org/rcj2016/rescue_line_2016.pdf). For next year's competition, I am building a robot (and the code for the robot) from the ground up. The tasks that the robot has to do are complex enough for the code to be a fairly complex thing. I have some experience with classes and OOP so I thought I could try to organize the code in a OOP fashion. I thought I could have a class for each type of Sensor (e.g: LineSensor(), RGBSensor UltraSound()...) and another for the Motors (e.g: Motor()) that would have two instances on the code. Basically, all the code has to do is take sensor readings and produce a motor response. With this class structure, where would I do this correspondence? Is this not appropriate for this kind of project? Is there a better way to do this, that is still OOP?

body:
I have a lot of experience with OOP, but mostly in embedded/pure software designs. However, I'm sure you can use it in a robot project too.

Avoid creating lots of objects dynamically, this results in gap in the very small memory available for the Uno. Try to create the object instances beforehand (this will also benefit performance hits during execution, by placing it into the initialization).

About the Sensors: you can make a baseclass if needed (Sensor) and let other classes derive from it (there is a small performance hit when calling methods though).

For the controlling:

- Put sensor readings in the sensor classes
- Put motor responses in the motor classes
- Put the control in a special class (Control?) that couples the sensor response to the motor response.


message:
Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board

Specifically, I want to add multiple relays (approximately 36 to 40) to an Arduino Uno board (using only a few pins). I found a solution using ShiftOut. You can take a look [here][1]. But here the example is for testing small LEDs bulbs.

I will control high-voltage electricity like fans, tube lights, washing machine with those relays, so what will be a proper graph or image diagram for that? And if you have any more suggestions for me then you can tell me :) And yes please tell me what I should use for it.

Right now am thinking to use an Arduino, relays, 74HC595 IC only. My diagram for controlling LED is like this:

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

You can edit it. I just need proper guidance for it and a few good suggestions.

  [1]: https://www.arduino.cc/en/tutorial/ShiftOut
  [2]: https://i.stack.imgur.com/QQgZZ.gif

body:
If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.

Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/


body:
What about using an I2C I/O expander like MAX7328 or equal and a ULN28XX as relay driver. and you can connect several I/O expanders to the same I2C buss with different addresses.

This will use minimal amount of pins and minimal amount of components.


message:
Is the use of malloc() and free() necessary in my Kalman noise Filter function?

I had a code that implements Kalman noise filtering on Arduino, and there is a use of malloc() and free(). I'm wondering if this will affect the Arduino or not (for example, the program will not function as I wanted, ...).

This is because when I got all raw (unfiltered) data and wrote the same Kalman Noise Filter function on Matlab, the filtering works well. However, when I write this FKalman function directly in Arduino, it doesn't work like it did on Matlab.

The Kalman Noise Filter is based on this article: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/

Here is the code (just have a look at the function Fkalman and the tick, ignore the other parts):

    #define START_MSG

    #define NBDATASEND 6
    #define NBBYTE2SEND (2*NBDATASEND)

    char StartMessage[] = "START";
    char StopMessage[] = "STOP";
    uint8_t byteRead;
    uint8_t StartAsked = 0;
    uint8_t StopAsked = 0;
    unsigned long previous = 0;
    int mod_11k = 12;
    int mod_17k = 13;
    uint8_t Header = 174;
    uint8_t tab_1[NBBYTE2SEND]={0,0,0,0,0,0,0,0,0,0,0,0};
    uint16_t data_toSend[NBDATASEND]={0,0,0,0,0,0};

    float P1[4];float P2[4];float P3[4]; float P4[4];float P5[4];float P6[4];
    float xprec1[2];float xprec2[2];float xprec3[2];float xprec4[2];float xprec5[2];float xprec6[2];
    float *sol1;float *sol2;float *sol3; float *sol4;float *sol5;float *sol6;
    float Te;
    float Tbeg;

    void setup() {
      pinMode(mod_11k,OUTPUT);
      pinMode(mod_17k,OUTPUT);
      digitalWrite(mod_11k,LOW);
      digitalWrite(mod_17k,LOW);
      //Start serial port with Gumstix
      Serial1.begin(115200);

    //Initialize KF
     P1[0] = 0.05; P1[1] =0; P1[2] =0; P1[3] = 0.05;
     P2[0] = 0.05; P2[1] =0; P2[2] =0; P2[3] = 0.05;
     P3[0] = 0.05; P3[1] =0; P3[2] =0; P3[3] = 0.05;
     P4[0] = 0.05; P4[1] =0; P4[2] =0; P4[3] = 0.05;
     P5[0] = 0.05; P5[1] =0; P5[2] =0; P5[3] = 0.05;
     P6[0] = 0.05; P6[1] =0; P6[2] =0; P6[3] = 0.05;
     xprec1[0] =0; xprec1[1] =0;
     xprec2[0] =0; xprec2[1] =0;
     xprec3[0] =0; xprec3[1] =0;
     xprec4[0] =0; xprec4[1] =0;
     xprec5[0] =0; xprec5[1] =0;
     xprec6[0] =0; xprec6[1] =0;

      //Wait for start message
    #ifdef START_MSG
      //Waiting START message to begin
      StartAsked = 0;
      while (StartAsked == 0)
      {
        if (Serial1.available() >= strlen(StartMessage))        //?????
        {
          //Serial.write("Bytes available");
          // verifiy that the received stream is well the start stream
          for (i = 0; i < strlen(StartMessage); i++)
          {
            byteRead = Serial1.read();
            if ((uint8_t)StartMessage[i] == byteRead)
            {
              StartAsked = 1;
            }
           // Serial.println(byteRead);
          }
        }
        delay(1);
      }
      Serial1.write("START");
      //Serial.write("START");
    #endif

    //KF first time
        Tbeg = millis();
        digitalWrite(mod_11k,HIGH);
        delayMicroseconds(2000);
        data_toSend[0] = analogRead(0);   //phi1 11k
        data_toSend[1] = analogRead(1); //phi2 11k
        data_toSend[2] = analogRead(2);
        digitalWrite(mod_11k,LOW);
        delayMicroseconds(200);
        digitalWrite(mod_17k,HIGH);
        delayMicroseconds(2000);
        data_toSend[3] = analogRead(0);
        data_toSend[4] = analogRead(1);
        data_toSend[5] = analogRead(2);
        digitalWrite(mod_17k,LOW);
        delayMicroseconds(200);
        xprec1[0] = data_toSend[0];
        xprec2[0] = data_toSend[1];
        xprec3[0] = data_toSend[2];
        xprec4[0] = data_toSend[3];
        xprec5[0] = data_toSend[4];
        xprec6[0] = data_toSend[5];
        Te = (millis() - Tbeg)/1000;
        sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
        sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
        sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
        sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
        sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
        sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
        Tbeg= millis();
    }

    void loop()
    {
        tick();
    }

    void tick() {
        //Previous value for filtering
        P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
        P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
        P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];
        P4[0] =sol4[2]; P4[1] =sol4[3]; P4[2] =sol4[4]; P4[3] =sol4[5];
        P5[0] =sol5[2]; P5[1] =sol5[3]; P5[2] =sol5[4]; P5[3] =sol5[5];
        P6[0] =sol6[2]; P6[1] =sol6[3]; P6[2] =sol6[4]; P6[3] =sol6[5];
        xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
        xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
        xprec3[0] =sol3[0]; xprec3[1] =sol3[1];
        xprec4[0] =sol4[0]; xprec4[1] =sol4[1];
        xprec5[0] =sol5[0]; xprec5[1] =sol5[1];
        xprec6[0] =sol6[0]; xprec6[1] =sol6[1];

        free(sol1);
        free(sol2);
        free(sol3);
        free(sol4);
        free(sol5);
        free(sol6);

        //Get data
        digitalWrite(mod_11k,HIGH);
        delayMicroseconds(2000);
        data_toSend[0] = analogRead(0);   //phi1 11k
        data_toSend[1] = analogRead(1); //phi2 11k
        data_toSend[2] = analogRead(2);
        digitalWrite(mod_11k,LOW);
        delayMicroseconds(200);
        digitalWrite(mod_17k,HIGH);
        delayMicroseconds(2000);
        data_toSend[3] = analogRead(0);
        data_toSend[4] = analogRead(1);
        data_toSend[5] = analogRead(2);
        digitalWrite(mod_17k,LOW);
        delayMicroseconds(200);
        Te = (millis() - Tbeg)/1000;

        //Filter
        sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
        sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
        sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
        sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
        sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
        sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
        Tbeg= millis();

        data_toSend[0] = sol1[0];
        data_toSend[1] = sol2[0];
        data_toSend[2] = sol3[0];
        data_toSend[3] = sol4[0];
        data_toSend[4] = sol5[0];
        data_toSend[5] = sol6[0];

        //Send data
        Codage(data_toSend,tab_1);
        HeaderSendnUInt8_RS232(tab_1,NBBYTE2SEND,Header);
    }

    void Codage(int16_t *d_send, uint8_t *tab_Send)
    {
        int i;
        for(i=0; i<NBDATASEND ;i++)
        {
           d_send[i]=d_send[i]+8192;
           tab_Send[2*i]= (uint8_t) ((d_send[i] & 127));              //lấy 7 bit đầu
           tab_Send[2*i+1]= (uint8_t) ((d_send[i] & 16256)>>7);       //lấy 7 bit sau
        }
    }

    uint8_t HeaderSendnUInt8_RS232(uint8_t *ToSend, uint8_t NbToSend, uint8_t Header)
    {
        Serial1.write(&Header,1);         //Header đâu phải pointer??
        return(Serial1.write((const uint8_t*)ToSend, NbToSend));
    }

    float *Fkalman(float xprec[2],float ymes,float P[4],float Te){
                         // Filtre proprement dit
        float *sol = NULL ;
        sol = (float*) malloc (sizeof(float) * 6);
        float xpred[2];
        float Ppred[4] ;
        float Kf[2] ;
        int q = 0.05;
        int r = 100;

        //x prediction
        xpred[0] = xprec[0] + Te*xprec[1];
        xpred[1] = xprec[1];

        //P_pred = F.P.F'+Q
        Ppred[0] = q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
        Ppred[1] = P[1] + Te*P[3];
        Ppred[2] = P[2] + Te*P[3] ;
        Ppred[3] = q+ P[3];

        //Kf = (P_pred.C').inv(C.P_pred.C'+R)
        Kf[0]  = (Ppred[0]/(r+Ppred[0]));
        Kf[1]  = (Ppred[2]/(r+Ppred[0]));

        //X_est
        sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
        sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);

        //P_est = (I-Kf*C)*P_pred
        sol[2] = Ppred[0]*(1-Kf[0]);
        sol[3] = Ppred[1]*(1-Kf[0]);
        sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
        sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
        return sol;
      }

If you find any problem related to the Fkalman function or my loop function, please tell me. Thank you!!

body:
It's not recommended, however you're only working with small amounts, and the same amount each time (6 floats per "sol" and 6 "sols", so 36 floats, or 144 bytes). Since it's always the same amount I would expect the same block of memory to be allocated each time.

Personally I would use local array variables in the calling function and pass them as a parameter to the function(s) that manipulate them, rather than returning a pointer to an allocated array.

    float sol1[6];
    Fkalman(xprec1,data_toSend[0],P1,Te,sol1);

    ....

    void Fkalman(float xprec[2],float ymes,float P[4],float Te, float *sol){

etc.

However I can't see it causing an issue, so if you would clarify "doesn't work as well" we may be able to point you in a better direction.


body:
As Majenko already explained it is only 144 bytes. You can use local variables as he proposes.

If you need to keep the values over multiple calls to the Fkalman function, create the space as a variable of an array for each of the calls (if the function is called a fixed number of times).

Besides this, malloc cost some time and for performance reasons it is better to do this during start up once, so the loop function is not hindered by mallocs and free.